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:
dasemuandClaude Sonnet 5.5 committed 2026-10-26 02:45:22 +01:00
1 parent e18fd2c27e
commit 88ef4a97a5
32 files changed
+5431 -375

No files matched your search

+195 -36
View File
@@ -1,5 +1,9 @@
import 'package:flutter/material.dart';
import 'dart:typed_data';
import 'package:flutter_test/flutter_test.dart';
import 'package:synapse/src/backend/graph_backend.dart';
import 'package:synapse/src/graph/graph_model.dart';
import 'package:synapse/src/graph/network_canvas.dart';
import 'package:synapse/src/graph/tree_canvas.dart';
@@ -99,10 +103,6 @@ void main() {
testWidgets('switches between every mode', (tester) async {
await pumpGraph(tester, demo());
await mode(tester, 'Local');
expect(find.byKey(const ValueKey('depth')), findsOneWidget);
expect(find.byType(NetworkCanvas), findsOneWidget);
await mode(tester, 'Synapses');
expect(find.text('Pulse'), findsOneWidget);
expect(find.byType(NetworkCanvas), findsOneWidget);
@@ -111,7 +111,7 @@ void main() {
await mode(tester, 'Clusters');
expect(find.byType(NetworkCanvas), findsOneWidget);
await mode(tester, 'Namespaces');
await mode(tester, 'Tree');
expect(find.byType(TreeCanvas), findsOneWidget);
expect(find.byType(NetworkCanvas), findsNothing);
@@ -123,43 +123,88 @@ void main() {
await tester.pump(const Duration(seconds: 1));
});
testWidgets('local mode follows the depth slider', (tester) async {
final b = demo();
// Chain Alpha – Beta – Gamma – Delta.
final g = b.createPage('Gamma');
b.seed(g.id, [(0, '[[Beta]] [[Delta]]')]);
await pumpGraph(tester, b);
await mode(tester, 'Local');
// Focus is the highest-degree page until the user picks one; pick Delta.
await tester.enterText(find.byType(TextField), 'Delta');
await tester.testTextInput.receiveAction(TextInputAction.done);
await settle(tester);
expect(
canvas(tester).nodeCount,
3,
reason: 'Delta, Gamma, Beta at depth 2',
);
final slider = tester.widget<Slider>(find.byKey(const ValueKey('depth')));
slider.onChanged!(1);
await settle(tester);
expect(canvas(tester).nodeCount, 2);
slider.onChanged!(3);
await settle(tester);
expect(canvas(tester).nodeCount, 5, reason: 'adds Alpha and topic');
});
test('namespace tree groups a/b titles and tags', () async {
test('tree groups a/b titles and tags', () async {
final model = GraphModel(await demo().graphData());
final root = buildNamespaceTree(model);
final labels = root.children.map((c) => c.label).toList();
expect(labels, ['Namespaces', 'Tags']);
expect(root.children[0].children.single.label, 'proj');
expect(root.children[0].children.single.children.single.label, 'one');
final topic = root.children[1].children.single;
TreeItem branch(String l) => root.children.firstWhere((c) => c.label == l);
// Hubs are covered by the hubs group below; notes in no hub hang off the centre.
// Namespaces have no node of their own: `proj` hangs off the centre.
expect(root.children.map((c) => c.label), [
'Alpha',
'Beta',
'Lonely',
'proj',
'Tags',
'topic',
]);
expect(branch('proj').children.single.label, 'one');
final topic = branch('Tags').children.single;
expect(topic.label, '#topic');
expect(topic.children.map((c) => c.label).toSet(), {'Alpha', 'Beta'});
});
test(
'tree centre carries the store name; sibling branches get distinct hues',
() async {
final model = GraphModel(await demo().graphData());
final root = buildNamespaceTree(model, name: 'Mi almacén');
expect(root.label, 'Mi almacén');
final arms = root.children;
expect(arms.length, greaterThan(1));
// Arms are evenly spread over the hue circle.
final gap = arms[1].hue - arms[0].hue;
expect(gap, closeTo(360 / arms.length, 1e-9));
// Children split their parent's sector evenly and stay inside it.
for (final a in arms) {
final k = a.children.length;
for (var j = 1; j < k; j++) {
expect(
a.children[j].hue - a.children[j - 1].hue,
closeTo(a.span / k, 1e-9),
);
}
for (final c in a.children) {
expect((c.hue - a.hue).abs(), lessThanOrEqualTo(a.span / 2));
}
}
},
);
test('tag grouping uses each page\'s most used tag', () {
GraphNode n(String t, List<String> tags) => GraphNode(
id: t,
title: t,
createdAt: 0,
degree: 1,
backlinks: 0,
cluster: 0,
isHub: false,
tags: tags,
);
final m = GraphModel(
GraphData(
nodes: [
n('a', ['Tecnología', 'idea']),
n('b', ['tecnología']),
n('c', ['idea', 'lugar']),
n('d', []),
],
sources: Uint32List(0),
targets: Uint32List(0),
kinds: Uint8List(0),
weights: Float32List(0),
seq: 0,
),
);
// Tie (two pages each): alphabetical.
expect(m.homeTag(0), 'idea');
expect(m.homeTag(2), 'idea');
expect(m.homeTag(3), isNull);
expect(m.tagGroups, ['idea', 'tecnología']);
expect(m.tagLabel('tecnología'), 'Tecnología');
expect(m.tagSprings([0, 1, 2, 3]).map((s) => (s.$1, s.$2)), [(2, 0)]);
});
test('filter by tag, query and min degree', () async {
final model = GraphModel(await demo().graphData());
String t(int i) => model.node(i).title;
@@ -212,4 +257,118 @@ void main() {
expect(hull.length, 4);
expect(hull.contains(const Offset(5, 5)), isFalse);
});
group('hubs', () {
// Media (hub) -> TV (hub) -> Anime (page); Media -> Books; Notes (page) in Media;
// a TV -> Media CONTAINS edge (a cycle the tree must survive); a journal (never a member).
GraphData hubData() {
GraphNode n(
String id,
String title, {
bool hub = false,
int? home,
String? journal,
}) => GraphNode(
id: id,
title: title,
journalDate: journal,
createdAt: 0,
degree: 1,
backlinks: 0,
cluster: 0,
isHub: hub,
homeHub: home,
tags: const [],
);
final nodes = [
n('0', 'Media', hub: true, home: 0),
n('1', 'TV', hub: true, home: 1),
n('2', 'Anime', home: 1),
n('3', 'Books', home: 0),
n('4', 'Notes', home: 0),
n('5', '2024-01-01', journal: '2024-01-01'),
];
// (source, target, kind)
final edges = [
(0, 1, 7), // Media contains TV
(0, 3, 7), // Media contains Books
(0, 4, 7), // Media contains Notes
(1, 2, 7), // TV contains Anime
(1, 0, 7), // TV contains Media (cycle)
(0, 5, 0), // Media -> journal link: a link never makes a member
];
return GraphData(
nodes: nodes,
sources: Uint32List.fromList([for (final e in edges) e.$1]),
targets: Uint32List.fromList([for (final e in edges) e.$2]),
kinds: Uint8List.fromList([for (final e in edges) e.$3]),
weights: Float32List.fromList([for (final _ in edges) 1.0]),
seq: 1,
);
}
GraphModel hubModel() => GraphModel(hubData());
test('hub members are the CONTAINS targets', () {
final m = hubModel();
expect(EdgeKind.values[7], EdgeKind.contains);
expect(EdgeKind.contains.structural, isTrue);
expect(EdgeKind.values[8], EdgeKind.tagged);
expect(const GraphFilter().kinds, contains(EdgeKind.tagged));
expect(m.hubMembers[0], {1, 3, 4});
expect(m.hubMembers[1], {2, 0});
expect(m.hubOrder.first, 0, reason: 'Media is home hub of most pages');
expect(m.hubRank[1], 1);
});
test('contains is a default filter kind', () {
expect(const GraphFilter().kinds, contains(EdgeKind.contains));
});
test('hub springs pull members to their home hub', () {
final m = hubModel();
expect(m.hubSprings([0, 1, 2, 3, 4, 5]), [
(2, 1, 0.6),
(3, 0, 0.6),
(4, 0, 0.6),
]);
});
test('tree hubs hang off the centre, cycle-safe', () {
final root = buildNamespaceTree(hubModel());
// Media is a member of TV and TV of Media: no root hub, both still placed once.
expect(root.children.where((c) => c.label == 'Hubs'), isEmpty);
final media = root.children.firstWhere((c) => c.label == 'Media');
expect(media.isHub, isTrue);
expect(media.children.map((c) => c.label).toSet(), {
'TV',
'Books',
'Notes',
});
final tv = media.children.firstWhere((c) => c.label == 'TV');
expect(tv.isHub, isTrue);
// Media already on the path: a leaf, not an endless loop.
expect(tv.children.map((c) => c.label).toSet(), {'Anime', 'Media'});
expect(
tv.children.firstWhere((c) => c.label == 'Media').children,
isEmpty,
);
});
testWidgets('clusters mode groups by hub by default', (tester) async {
await pumpGraph(tester, _HubBackend(hubData()));
await mode(tester, 'Clusters');
expect(find.byKey(const ValueKey('cluster-group')), findsOneWidget);
expect(find.text('Group: hubs'), findsOneWidget);
});
});
}
/// A memory backend whose graph data is fixed (so tests don't depend on its demo graph).
class _HubBackend extends MemoryBackend {
_HubBackend(this._data);
final GraphData _data;
@override
Future<GraphData> graphData() async => _data;
}
+576
View File
@@ -0,0 +1,576 @@
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:synapse/src/backend/graph_backend.dart';
import 'package:synapse/src/state/app_state.dart';
import 'package:synapse/src/theme/theme.dart';
import 'package:synapse/src/views/all_pages_view.dart';
import 'package:synapse/src/views/graph_view.dart';
import 'package:synapse/src/views/shell.dart';
import 'support/memory_backend.dart';
/// Fun (hub) -> Fun/TV (sub-hub) -> Anime, Movies, Shows; Fun also holds Games and Books.
MemoryBackend demo() {
final b = MemoryBackend();
final fun = b.addHub('Fun', 'Things for the weekend');
final tv = b.addHub('Fun/TV');
b.hubsOfPage[tv.id] = {fun.id};
for (final t in ['Games', 'Books']) {
b.hubsOfPage[b.createPage(t).id] = {fun.id};
}
for (final t in ['Anime', 'Movies', 'Shows']) {
b.hubsOfPage[b.createPage(t).id] = {tv.id};
}
return b;
}
PageDto byTitle(MemoryBackend b, String t) =>
b.pages.values.firstWhere((p) => p.title == t);
Future<AppState> pump(
WidgetTester tester,
MemoryBackend b, {
Widget home = const Shell(),
AppRoute? route,
}) async {
tester.view.physicalSize = const Size(1600, 1000);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.reset);
final app = AppState(b);
if (route != null) app.go(route);
await tester.pumpWidget(
AppScope(
state: app,
child: MaterialApp(theme: buildTheme(Brightness.light), home: home),
),
);
await settle(tester);
return app;
}
Future<void> settle(WidgetTester tester) async {
for (var i = 0; i < 6; i++) {
await tester.pump(const Duration(milliseconds: 50));
}
}
void main() {
tagTests();
testWidgets('all pages hides hubs and sorts by title', (tester) async {
await pump(tester, demo(), home: const Scaffold(body: AllPagesView()));
expect(find.text('Fun'), findsNothing);
expect(find.text('Games'), findsOneWidget);
await tester.tap(find.byKey(const ValueKey('page-sort')));
await settle(tester);
await tester.tap(find.text('Title').last);
await settle(tester);
// Title sort is A-Z by default... descending arrow means newest/Z-A; flip to A-Z first.
await tester.tap(find.byKey(const ValueKey('page-sort-direction')));
await settle(tester);
final ys = [
for (final t in ['Anime', 'Books', 'Games', 'Movies', 'Shows'])
tester.getTopLeft(find.text(t)).dy,
];
expect(ys, [...ys]..sort());
});
testWidgets('page sidebar with the local graph toggles', (tester) async {
final b = demo();
final app = await pump(tester, b);
app.openId(byTitle(b, 'Games').id);
await settle(tester);
expect(find.byType(LocalGraphPanel), findsNothing);
await tester.tap(find.byKey(const ValueKey('page-sidebar-toggle')));
await settle(tester);
expect(find.byType(LocalGraphPanel), findsOneWidget);
await tester.tap(find.byKey(const ValueKey('page-sidebar-toggle')));
await settle(tester);
expect(find.byType(LocalGraphPanel), findsNothing);
});
testWidgets('sidebar hubs start collapsed and only list sub-hubs', (
tester,
) async {
await pump(tester, demo());
expect(find.text('HUBS'), findsOneWidget);
expect(find.text('Fun'), findsOneWidget);
expect(find.text('Fun/TV'), findsNothing);
await tester.tap(find.byIcon(Icons.chevron_right_rounded));
await settle(tester);
expect(find.text('Fun/TV'), findsOneWidget);
// Notes are never children in the sidebar.
expect(find.text('Games'), findsNothing);
expect(find.text('Anime'), findsNothing);
});
testWidgets('new note from a hub starts from its template', (tester) async {
final b = demo();
final hub = byTitle(b, 'Fun');
final t = await b.hubTemplate(hub.id);
b.seed(t, [(0, 'Rating'), (1, 'Notes')]);
final p = await b.createPageFromTemplate(hub.id, 'Chess');
expect(b.outlines[p.id]!.map((n) => n.content), ['Rating', 'Notes']);
expect(b.hubsOfPage[p.id], contains(hub.id));
});
testWidgets(
'sidebar shows HUBS with a plus even without hubs; plus creates',
(tester) async {
final b = MemoryBackend()..createPage('Solo');
await pump(tester, b);
expect(find.text('HUBS'), findsOneWidget);
await tester.tap(find.byKey(const ValueKey('new-hub')));
await settle(tester);
await tester.enterText(find.byType(TextField), 'Projects');
await tester.tap(find.text('Create'));
await settle(tester);
final hub = byTitle(b, 'Projects');
expect(hub.isHub, isTrue);
// The new hub opens as a hub screen.
expect(find.byKey(const ValueKey('hub-description')), findsOneWidget);
},
);
testWidgets('new hub with a taken title shows the error inline', (
tester,
) async {
await pump(tester, demo());
await tester.tap(find.byKey(const ValueKey('new-hub')));
await settle(tester);
await tester.enterText(find.byType(TextField), 'Games');
await tester.tap(find.text('Create'));
await settle(tester);
expect(find.textContaining('already exists'), findsOneWidget);
});
testWidgets(
'hub screen lists sub-hubs first, removes members, saves description',
(tester) async {
final b = demo();
final fun = byTitle(b, 'Fun');
await pump(tester, b, route: PageTarget(id: fun.id));
expect(find.byKey(const ValueKey('hub-description')), findsOneWidget);
expect(find.text('Things for the weekend'), findsOneWidget);
expect(find.text('MEMBERS'), findsOneWidget);
// Sub-hub row comes before the notes.
final rows = find.byWidgetPredicate(
(w) =>
w.key is ValueKey &&
'${(w.key as ValueKey).value}'.startsWith('member-'),
);
expect(rows, findsNWidgets(3));
final ys = [
for (final t in ['Fun/TV', 'Books', 'Games'])
tester
.getTopLeft(find.descendant(of: rows, matching: find.text(t)))
.dy,
];
expect(ys, orderedEquals([...ys]..sort()));
// Remove Books (the × shows on hover).
final books = byTitle(b, 'Books');
final gesture = await tester.createGesture(kind: PointerDeviceKind.mouse);
await gesture.addPointer(location: Offset.zero);
addTearDown(gesture.removePointer);
await gesture.moveTo(
tester.getCenter(
find.descendant(
of: find.byKey(ValueKey('member-${books.id}')),
matching: find.text('Books'),
),
),
);
await settle(tester);
await tester.tap(find.byKey(ValueKey('remove-${books.id}')));
await settle(tester);
expect(b.hubsOfPage[books.id], isEmpty);
expect(find.text('Books'), findsNothing);
// Description is saved on blur.
await tester.enterText(
find.byKey(const ValueKey('hub-description')),
'New text',
);
await tester.testTextInput.receiveAction(TextInputAction.done);
FocusManager.instance.primaryFocus?.unfocus();
await settle(tester);
expect(b.pages[fun.id]!.description, 'New text');
},
);
testWidgets('hub screen adds an existing note and creates a sub-hub', (
tester,
) async {
final b = demo();
final lone = b.createPage('Lonely');
final fun = byTitle(b, 'Fun');
await pump(tester, b, route: PageTarget(id: fun.id));
await tester.tap(find.text('Add'));
await settle(tester);
await tester.enterText(find.byType(TextField).last, 'Lone');
await settle(tester);
await tester.tap(find.byKey(ValueKey('pick-${lone.id}')));
await settle(tester);
expect(b.hubsOfPage[lone.id], {fun.id});
await tester.tap(find.text('Add'));
await settle(tester);
await tester.enterText(find.byType(TextField).last, 'Music');
await settle(tester);
await tester.tap(find.text('Create hub "Music"'));
await settle(tester);
final music = byTitle(b, 'Music');
expect(music.isHub, isTrue);
expect(b.hubsOfPage[music.id], {fun.id});
});
testWidgets('a hub cannot be added below itself (cycle error shown)', (
tester,
) async {
final b = demo();
final fun = byTitle(b, 'Fun');
final tv = byTitle(b, 'Fun/TV');
await pump(tester, b, route: PageTarget(id: tv.id));
await tester.tap(find.byKey(const ValueKey('page-menu')));
await settle(tester);
await tester.tap(find.text('Add to hub…'));
await settle(tester);
// Fun is already a parent, so it is not offered; the hub itself neither.
expect(find.byKey(ValueKey('pick-${fun.id}')), findsNothing);
await tester.tap(find.text('Cancel'));
await settle(tester);
// Adding Fun under Fun/TV is rejected by the backend.
expect(() => b.addToHub(fun.id, tv.id), throwsException);
});
testWidgets('note page: In chips can be removed, no hub pill', (
tester,
) async {
final b = demo();
final games = byTitle(b, 'Games');
final fun = byTitle(b, 'Fun');
await pump(tester, b, route: PageTarget(id: games.id));
expect(find.text('Hub'), findsNothing);
expect(find.text('In'), findsOneWidget);
await tester.tap(find.byKey(ValueKey('leave-${fun.id}')));
await settle(tester);
expect(b.hubsOfPage[games.id], isEmpty);
expect(find.text('In'), findsNothing);
});
testWidgets('note page: Add to hub picks a hub', (tester) async {
final b = demo();
final lone = b.createPage('Lonely');
final tv = byTitle(b, 'Fun/TV');
await pump(tester, b, route: PageTarget(id: lone.id));
await tester.tap(find.byKey(const ValueKey('page-menu')));
await settle(tester);
await tester.tap(find.text('Add to hub…'));
await settle(tester);
await tester.tap(find.byKey(ValueKey('pick-${tv.id}')));
await settle(tester);
expect(b.hubsOfPage[lone.id], {tv.id});
expect(find.text('Fun/TV'), findsWidgets);
});
testWidgets('convert to hub: shortened title, members, keep outline', (
tester,
) async {
final b = demo();
final anime = b.createPage('Entretenimiento/TV/Anime');
b.seed(anime.id, [
(0, 'A long list of shows I like'),
(0, '[[Naruto]]'),
(0, '[[Bleach]]'),
]);
final naruto = b.createPage('Naruto');
b.createPage('Bleach');
await pump(tester, b, route: PageTarget(id: anime.id));
await tester.tap(find.byKey(const ValueKey('page-menu')));
await settle(tester);
await tester.tap(find.text('Convert to hub…'));
await settle(tester);
expect(find.text('Convert to hub'), findsOneWidget);
final title = tester.widget<TextField>(
find.byKey(const ValueKey('convert-title')),
);
expect(title.controller!.text, 'Anime');
expect(find.text('MEMBERS (2/2)'), findsOneWidget);
// Uncheck Bleach; the outline has prose, so "keep" is on by default.
await tester.tap(find.byKey(ValueKey('member-${byTitle(b, 'Bleach').id}')));
await settle(tester);
expect(find.text('MEMBERS (1/2)'), findsOneWidget);
expect(
tester
.widget<CheckboxListTile>(find.byKey(const ValueKey('keep-outline')))
.value,
isTrue,
);
await tester.tap(find.text('Convert'));
await settle(tester);
// "Anime" already exists in the demo: the error is shown inline.
expect(find.byKey(const ValueKey('convert-error')), findsOneWidget);
await tester.enterText(
find.byKey(const ValueKey('convert-title')),
'Anime (TV)',
);
await tester.tap(find.text('Convert'));
await settle(tester);
final hub = b.pages[anime.id]!;
expect(hub.isHub, isTrue);
expect(hub.title, 'Anime (TV)');
expect(hub.description, 'A long list of shows I like');
expect(b.outlines[anime.id], isEmpty);
expect(b.hubsOfPage[naruto.id], {anime.id});
final note = byTitle(b, 'Anime (notes)');
expect(b.outlines[note.id], hasLength(3));
expect(b.hubsOfPage[note.id], {anime.id});
// The page now renders as a hub.
expect(find.byKey(const ValueKey('hub-description')), findsOneWidget);
});
testWidgets('convert is disabled while "keep outline" has no note title', (
tester,
) async {
final b = demo();
final p = b.createPage('Area of Work');
b.seed(p.id, [(0, 'Some prose')]);
await pump(tester, b, route: PageTarget(id: p.id));
await tester.tap(find.byKey(const ValueKey('page-menu')));
await settle(tester);
await tester.tap(find.text('Convert to hub…'));
await settle(tester);
FilledButton convert() => tester.widget<FilledButton>(
find.widgetWithText(FilledButton, 'Convert'),
);
expect(convert().onPressed, isNotNull);
await tester.enterText(
find.byKey(const ValueKey('convert-note-title')),
'',
);
await settle(tester);
expect(convert().onPressed, isNull);
expect(
find.text('A title is required to keep the outline'),
findsOneWidget,
);
// Unticking "keep" re-enables it (the outline is then dropped on purpose).
await tester.tap(find.byKey(const ValueKey('keep-outline')));
await settle(tester);
expect(convert().onPressed, isNotNull);
expect(b.outlines[p.id], isNotEmpty);
});
testWidgets('converting a page opened by title does not recreate the title', (
tester,
) async {
final b = demo();
final p = b.createPage('Area of Work');
b.seed(p.id, [(0, 'Some prose')]);
final app = await pump(tester, b, route: PageTarget(title: 'Area of Work'));
await tester.tap(find.byKey(const ValueKey('page-menu')));
await settle(tester);
await tester.tap(find.text('Convert to hub…'));
await settle(tester);
await tester.enterText(find.byKey(const ValueKey('convert-title')), 'Area');
await tester.tap(find.text('Convert'));
await settle(tester);
expect(find.byKey(const ValueKey('hub-description')), findsOneWidget);
expect(b.pages[p.id]!.title, 'Area');
expect(b.pages.values.where((q) => q.title == 'Area of Work'), isEmpty);
expect((app.route as PageTarget).id, p.id);
});
testWidgets('renaming rewrites history entries that open the old title', (
tester,
) async {
final b = demo();
final p = b.createPage('Old name');
final app = await pump(tester, b, route: PageTarget(title: 'Old name'));
app.go(PageTarget(id: byTitle(b, 'Games').id));
await settle(tester);
app.back();
await settle(tester);
await tester.enterText(find.byType(TextField).first, 'New name');
FocusManager.instance.primaryFocus?.unfocus();
await settle(tester);
expect(b.pages[p.id]!.title, 'New name');
expect(b.pages.values.where((q) => q.title == 'Old name'), isEmpty);
expect((app.route as PageTarget).id, p.id);
app.go(PageTarget(id: byTitle(b, 'Games').id));
app.back();
await settle(tester);
expect((app.route as PageTarget).id, p.id);
});
testWidgets('adding a note to another hub moves it', (tester) async {
final b = demo();
final other = b.addHub('Other');
final tv = byTitle(b, 'Fun/TV');
await b.addToHub(tv.id, other.id);
expect(b.hubsOfPage[tv.id], {other.id});
});
testWidgets('cleanup never preselects hubs or pages with content', (
tester,
) async {
final b = demo();
final todo = b.createPage('todo');
b.seed(todo.id, [(0, 'real tasks')]);
final hub = b.addHub('later');
final empty = b.createPage('now');
final contents = b.createPage('contents');
b.seed(contents.id, [(0, 'x')]);
for (final p in [todo, hub, empty, contents]) {
b.legacy[p.id] = 'Logseq built-in';
}
final c = {for (final x in await b.legacyCandidates()) x.title: x};
expect(c['todo']!.preselected, isFalse);
expect(c['later']!.preselected, isFalse);
expect(c['now']!.preselected, isTrue);
expect(c['contents']!.preselected, isTrue);
});
testWidgets('memory backend: inHubs only lists hubs, keep title is checked', (
tester,
) async {
final b = demo();
final p = b.createPage('Plain');
final notHub = b.createPage('NotHub');
b.hubsOfPage[p.id] = {byTitle(b, 'Fun').id, notHub.id};
final st = await b.pageStructure(p.id);
expect(st.inHubs.map((h) => h.title), ['Fun']);
b.seed(p.id, [(0, 'x')]);
await expectLater(
b.convertToHub(p.id, 'Same', '', [], keepOutlineAs: 'same'),
throwsException,
);
await expectLater(
b.convertToHub(p.id, 'Same', '', [], keepOutlineAs: ' '),
throwsException,
);
expect(b.pages[p.id]!.isHub, isFalse);
});
testWidgets('convert to note turns members into links', (tester) async {
final b = demo();
final tv = byTitle(b, 'Fun/TV');
await pump(tester, b, route: PageTarget(id: tv.id));
await tester.tap(find.byKey(const ValueKey('page-menu')));
await settle(tester);
await tester.tap(find.text('Convert to note'));
await settle(tester);
expect(b.pages[tv.id]!.isHub, isFalse);
expect(b.outlines[tv.id]!.map((n) => n.content), [
'[[Anime]]',
'[[Movies]]',
'[[Shows]]',
]);
});
testWidgets('page screen shows the namespace breadcrumb and children', (
tester,
) async {
final b = demo();
final a = b.createPage('Claude/Code');
b.createPage('Claude');
await pump(tester, b, route: PageTarget(id: a.id));
expect(find.byIcon(Icons.account_tree_outlined), findsWidgets);
final c = byTitle(b, 'Claude');
await pump(tester, b, route: PageTarget(id: c.id));
expect(find.text('NAMESPACE'), findsOneWidget);
});
testWidgets('cleanup deletes only the checked pages', (tester) async {
final b = demo();
final a = b.createPage('contents');
final c = b.createPage('Keep me');
b.seed(c.id, [(0, 'real content')]);
final d = b.createPage('card');
b.legacy[a.id] = 'Logseq built-in';
b.legacy[c.id] = 'type:: system';
b.legacy[d.id] = 'Logseq built-in';
await pump(tester, b, home: const Scaffold(body: AllPagesView()));
await tester.tap(find.text('Clean up'));
await settle(tester);
expect(find.text('Remove legacy Logseq pages'), findsOneWidget);
expect(find.text('Delete (2)'), findsOneWidget);
// Uncheck "card".
await tester.tap(
find.descendant(
of: find.byType(AlertDialog),
matching: find.text('card'),
),
);
await settle(tester);
expect(find.text('Delete (1)'), findsOneWidget);
await tester.tap(find.text('Delete (1)'));
await settle(tester);
expect(b.purged, [a.id]);
expect(b.pages.containsKey(a.id), isFalse);
expect(b.pages.containsKey(c.id), isTrue);
expect(b.pages.containsKey(d.id), isTrue);
});
testWidgets('cleanup with nothing to remove says so', (tester) async {
await pump(tester, demo(), home: const Scaffold(body: AllPagesView()));
await tester.tap(find.text('Clean up'));
await settle(tester);
expect(find.text('No legacy pages found.'), findsOneWidget);
});
}
void tagTests() {
testWidgets('tags are pages: pick one, create one, remove', (tester) async {
final b = demo();
final note = byTitle(b, 'Games');
await b.setPageTags(note.id, ['tema']);
await pump(tester, b, route: PageTarget(id: note.id));
expect(find.byKey(const ValueKey('tag-tema')), findsOneWidget);
expect(byTitle(b, 'tema').isTag, isTrue);
await tester.tap(find.byKey(const ValueKey('add-tag')));
await settle(tester);
// Tags already on the page are not offered again; a new name creates a tag page.
expect(find.byKey(const ValueKey('tag-opt-tema')), findsNothing);
await tester.enterText(find.byKey(const ValueKey('tag-input')), '#ocio');
await settle(tester);
await tester.tap(find.byKey(const ValueKey('tag-create')));
await settle(tester);
expect(byTitle(b, 'Games').tags, ['tema', 'ocio']);
expect(byTitle(b, 'ocio').isTag, isTrue);
await tester.tap(find.byKey(const ValueKey('untag-tema')));
await settle(tester);
expect(byTitle(b, 'Games').tags, ['ocio']);
// The tag page survives losing its last member.
expect(byTitle(b, 'tema').isTag, isTrue);
});
testWidgets('types: pick a suggestion, create a new one, remove', (
tester,
) async {
final b = demo();
final note = byTitle(b, 'Games');
await pump(tester, b, route: PageTarget(id: note.id));
await tester.tap(find.byKey(const ValueKey('add-type')));
await settle(tester);
expect(find.byKey(const ValueKey('type-opt-persona')), findsOneWidget);
await tester.tap(find.byKey(const ValueKey('type-opt-lugar')));
await settle(tester);
expect(find.byKey(const ValueKey('type-lugar')), findsOneWidget);
await tester.tap(find.byKey(const ValueKey('add-type')));
await settle(tester);
expect(find.byKey(const ValueKey('type-opt-lugar')), findsNothing);
await tester.enterText(find.byKey(const ValueKey('type-input')), 'ocio');
await settle(tester);
await tester.tap(find.byKey(const ValueKey('type-create')));
await settle(tester);
expect(byTitle(b, 'Games').types, ['lugar', 'ocio']);
// Types are names, never pages.
expect(b.pages.values.any((p) => p.title == 'ocio'), isFalse);
await tester.tap(find.byKey(const ValueKey('untype-lugar')));
await settle(tester);
expect(byTitle(b, 'Games').types, ['ocio']);
});
}
+174
View File
@@ -0,0 +1,174 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:synapse/src/editor/completion.dart';
import 'package:synapse/src/editor/markdown.dart';
import 'package:synapse/src/state/app_state.dart';
import 'package:synapse/src/state/keymap.dart';
import 'package:synapse/src/state/settings.dart';
import 'package:synapse/src/theme/theme.dart';
import 'package:synapse/src/views/settings_view.dart';
import 'support/memory_backend.dart';
void main() {
group('keymap', () {
test('round-trips combos and refuses duplicates', () {
final c = Combo(LogicalKeyboardKey.keyB, ctrl: true, shift: true);
expect(Combo.decode(c.encode()), c);
expect(c.label, 'Ctrl+Shift+B');
final k = Keymap();
expect(k.of(AppAction.bold), Combo(LogicalKeyboardKey.keyB, ctrl: true));
// Ctrl+K belongs to the quick switcher.
expect(
k.bind(AppAction.bold, AppAction.quickSwitcher.defaultCombo),
AppAction.quickSwitcher,
);
expect(k.bind(AppAction.bold, c), isNull);
expect(k.of(AppAction.bold), c);
expect(Keymap(k.toJson()).of(AppAction.bold), c);
k.reset(AppAction.bold);
expect(k.isCustom(AppAction.bold), isFalse);
});
test('default bindings are unique', () {
final seen = <Combo>{};
for (final a in AppAction.values) {
expect(seen.add(a.defaultCombo), isTrue, reason: a.name);
}
});
test('theme and bindings survive a restart', () {
final store = MemorySettings();
final a = AppState(MemoryBackend(), settings: store);
a.setTheme('sweet');
a.bindKey(AppAction.bold, Combo(LogicalKeyboardKey.keyY, ctrl: true));
final b = AppState(MemoryBackend(), settings: store);
expect(b.themeId, 'sweet');
expect(
b.keymap.of(AppAction.bold),
Combo(LogicalKeyboardKey.keyY, ctrl: true),
);
store.data['theme'] = 'nonsense';
expect(AppState(MemoryBackend(), settings: store).themeId, autoThemeId);
});
});
group('slash commands', () {
test('detects the trigger only at a word start', () {
expect(detectCompletion('/li', 3)!.kind, CompletionKind.command);
expect(detectCompletion('say /li', 7)!.query, 'li');
expect(detectCompletion('see http://x', 12), isNull);
expect(detectCompletion('a/b', 3), isNull);
});
test('/link leaves the caret inside the brackets', () {
final q = detectCompletion('x /li', 5)!;
final v = applyCompletion(
'x /li',
q,
const CompletionItem('/link', 'link'),
);
expect(v.text, 'x [[]]');
expect(v.selection.baseOffset, 4);
});
test('commands match by name, label and keyword', () {
expect(matchCommands('li').first.name, 'link');
expect(matchCommands('strong').map((c) => c.name), contains('bold'));
expect(matchCommands('zzz'), isEmpty);
});
test('wrapSelection wraps, unwraps and pairs at the caret', () {
const sel = TextSelection(baseOffset: 2, extentOffset: 5);
final w = wrapSelection(
const TextEditingValue(text: 'a bcd e', selection: sel),
'**',
'**',
);
expect(w.text, 'a **bcd** e');
expect(w.selection.textInside(w.text), 'bcd');
expect(wrapSelection(w, '**', '**').text, 'a bcd e');
final p = wrapSelection(
const TextEditingValue(
text: 'ab',
selection: TextSelection.collapsed(offset: 1),
),
'==',
'==',
);
expect(p.text, 'a====b');
expect(p.selection.baseOffset, 3);
});
});
test('backslash escapes show the character literally', () {
final r = BlockRenderer(
RenderContext(
colors: SynapseColors.light,
base: const TextStyle(fontSize: 15),
refs: BlockRefCache(MemoryBackend()),
assetPath: (_) => null,
onPage: (_) {},
onBlockRef: (_) {},
onUrl: (_) {},
),
).render(r'\*not italic\* and \[[no link]]');
final t = r.span.toPlainText(includePlaceholders: true);
expect(t, '*not italic* and [[no link]]');
r.dispose();
});
testWidgets('settings: pick a theme and rebind a key', (tester) async {
tester.view.physicalSize = const Size(1200, 1600);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.reset);
final app = AppState(MemoryBackend());
await tester.pumpWidget(
AppScope(
state: app,
child: ListenableBuilder(
listenable: app,
builder: (_, _) {
final t = themeById(app.themeId);
return MaterialApp(
theme: buildTheme(
t?.brightness ?? Brightness.light,
colors: t?.colors,
),
home: const Scaffold(body: SettingsView()),
);
},
),
),
);
await tester.tap(find.byKey(const ValueKey('theme-sweet')));
await tester.pump();
expect(app.themeId, 'sweet');
final bind = find.byKey(const ValueKey('bind-bold'));
await tester.ensureVisible(bind);
await tester.tap(bind);
await tester.pump();
expect(find.text('Press keys…'), findsOneWidget);
await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft);
await tester.sendKeyDownEvent(LogicalKeyboardKey.keyY);
await tester.sendKeyUpEvent(LogicalKeyboardKey.keyY);
await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft);
await tester.pump();
expect(
app.keymap.of(AppAction.bold),
Combo(LogicalKeyboardKey.keyY, ctrl: true),
);
});
test('hubs never enter recents', () {
final b = MemoryBackend();
final hub = b.addHub('Fun');
final note = b.createPage('Note');
final app = AppState(b);
app.pageShown(note);
app.pageShown(hub);
expect(app.recent.map((p) => p.title), ['Note']);
});
}
+614 -6
View File
@@ -11,6 +11,9 @@ class MemoryBackend implements GraphBackend {
MemoryBackend({this.todayDate = '2026-10-21'});
final String todayDate;
@override
String get graphName => 'Test graph';
final pages = <String, PageDto>{};
final outlines = <String, List<OutlineNode>>{};
final aliases = <String, String>{};
@@ -26,6 +29,11 @@ class MemoryBackend implements GraphBackend {
journalDate: journalDate,
createdAt: 0,
updatedAt: 0,
isHub: false,
description: '',
tags: const [],
isTag: false,
types: const [],
);
pages[p.id] = p;
outlines[p.id] = [];
@@ -138,18 +146,55 @@ class MemoryBackend implements GraphBackend {
@override
Future<PageDto> renamePage(String id, String newTitle) async {
final p = pages[id]!;
return pages[id] = PageDto(
id: p.id,
title: newTitle,
createdAt: p.createdAt,
updatedAt: p.updatedAt,
);
final t = newTitle.trim();
final clash = _byTitle(t);
if (clash != null && clash.id != id) {
throw Exception('A page titled "$t" already exists');
}
for (final l in outlines.values) {
for (final n in l) {
n.content = n.content.replaceAll('[[${p.title}]]', '[[$t]]');
}
}
final old = p.title;
_put(p, title: t);
if (p.isTag) {
for (final q in pages.values.toList()) {
if (q.tags.any((x) => _tagKey(x) == _tagKey(old))) {
_put(
q,
tags: [for (final x in q.tags) _tagKey(x) == _tagKey(old) ? t : x],
);
}
}
}
return pages[id]!;
}
@override
Future<void> deletePage(String id) async {
final gone = pages[id];
if (gone != null && gone.isTag) {
for (final q in pages.values.toList()) {
_put(
q,
tags: [
for (final x in q.tags)
if (_tagKey(x) != _tagKey(gone.title)) x,
],
);
}
}
pages.remove(id);
outlines.remove(id);
_forget(id);
}
void _forget(String id) {
hubsOfPage.remove(id);
for (final s in hubsOfPage.values) {
s.remove(id);
}
}
@override
@@ -170,6 +215,7 @@ class MemoryBackend implements GraphBackend {
String content,
) async {
calls.add('insert');
if (_isHub(pageId)) throw Exception('A hub has no blocks');
final n = OutlineNode(id: _id(), depth: 0, content: content);
OutlineOps.insert(
outlines[pageId]!,
@@ -280,6 +326,531 @@ class MemoryBackend implements GraphBackend {
Future<AssetDto> putAssetFile(String path, {String? mime}) =>
throw UnimplementedError();
/// Pages `legacyCandidates` reports, id to reason. Preselection follows the core: not a
/// hub, and empty or one of Logseq's organisational pages.
final legacy = <String, String>{};
/// Ids passed to `purgePages`, in call order.
final purged = <String>[];
/// Parent hubs of each page (membership lives on the member, like the core).
final hubsOfPage = <String, Set<String>>{};
/// Test shortcut: `hubFlags[id] = true` turns a page into a hub whose members are the
/// pages its outline linked to (same as converting it with all candidates kept).
late final hubFlags = _HubFlags(this);
bool _isHub(String id) => pages[id]?.isHub ?? false;
PageBrief _brief(PageDto p) => PageBrief(
id: p.id,
title: p.title,
isJournal: p.journalDate != null,
isHub: p.isHub,
);
void _put(
PageDto p, {
String? title,
bool? isHub,
String? description,
List<String>? tags,
bool? isTag,
List<String>? types,
}) {
pages[p.id] = PageDto(
id: p.id,
title: title ?? p.title,
journalDate: p.journalDate,
originJournal: p.originJournal,
createdAt: p.createdAt,
updatedAt: p.updatedAt,
isHub: isHub ?? p.isHub,
description: description ?? p.description,
tags: tags ?? p.tags,
isTag: isTag ?? p.isTag,
types: types ?? p.types,
);
}
/// Members of a hub: sub-hubs first, then notes, each by title.
List<PageDto> _members(String hubId) {
final out = [
for (final e in hubsOfPage.entries)
if (e.value.contains(hubId) && pages.containsKey(e.key)) pages[e.key]!,
];
out.sort((a, b) {
if (a.isHub != b.isHub) return a.isHub ? -1 : 1;
return a.title.toLowerCase().compareTo(b.title.toLowerCase());
});
return out;
}
/// Whether `target` is `hub` or lies below it.
bool _reaches(String hub, String target) {
if (hub == target) return true;
return _members(hub).any((m) => m.isHub && _reaches(m.id, target));
}
/// Pages a page's outline links to or tags (outline order, journals and self skipped).
List<PageDto> _linked(String id) {
final link = RegExp(r'\[\[([^\]]+)\]\]|(?:^|\s)#(\w+)');
final out = <PageDto>[];
for (final n in outlines[id] ?? const <OutlineNode>[]) {
for (final m in link.allMatches(n.content)) {
final p = _byTitle(m.group(1) ?? m.group(2)!);
if (p == null || p.id == id || p.journalDate != null) continue;
if (!out.any((b) => b.id == p.id)) out.add(p);
}
}
return out;
}
/// Makes `page` a hub, dropping its blocks; `members` are added when valid.
void makeHub(String id, {String? description, List<String>? members}) {
final linked = members ?? [for (final p in _linked(id)) p.id];
outlines[id] = [];
_put(pages[id]!, isHub: true, description: description);
for (final m in linked) {
_tryAdd(m, id);
}
}
bool _tryAdd(String page, String hub) {
final p = pages[page];
if (p == null ||
p.journalDate != null ||
!_isHub(hub) ||
page == hub ||
_reaches(page, hub)) {
return false;
}
(hubsOfPage[page] ??= {}).add(hub);
return true;
}
/// Synchronous `createHub` for test setup.
PageDto addHub(String title, [String description = '']) {
final p = createPage(title);
_put(p, isHub: true, description: description);
return pages[p.id]!;
}
@override
Future<PageDto> createHub(String title, String description) async {
final t = title.trim();
if (t.isEmpty) throw Exception('A title is required');
if (_byTitle(t) != null) {
throw Exception('A page titled "$t" already exists');
}
final p = createPage(t);
_put(p, isHub: true, description: description);
return pages[p.id]!;
}
final templates = <String, String>{};
String _tagKey(String t) => t.trim().toLowerCase();
@override
Future<PageDto> setPageTags(String pageId, List<String> tags) async {
final p = pages[pageId]!;
if (p.journalDate != null) throw Exception('Journals cannot have tags');
final next = <String>[];
for (final raw in tags) {
final t = raw.trim().replaceFirst(RegExp(r'^#+'), '').trim();
if (t.isNotEmpty && !next.any((x) => _tagKey(x) == _tagKey(t))) {
next.add(t);
}
}
final stored = <String>[];
for (final t in next) {
var tp = _byTitle(t);
if (tp == null) {
tp = createPage(t);
_put(tp, isTag: true);
} else if (tp.journalDate != null || tp.isHub) {
throw Exception('"$t" cannot be a tag');
} else if (!tp.isTag) {
_put(tp, isTag: true);
}
stored.add(pages[tp.id]!.title);
}
_put(p, tags: stored);
return pages[pageId]!;
}
static const suggestedTypes = ['persona', 'lugar', 'empresa'];
@override
Future<PageDto> setPageTypes(String pageId, List<String> types) async {
final p = pages[pageId]!;
if (p.journalDate != null) throw Exception('Journals cannot have types');
final next = <String>[];
for (final raw in types) {
final t = raw.trim();
if (t.isNotEmpty && !next.any((x) => _tagKey(x) == _tagKey(t))) {
next.add(t);
}
}
_put(p, types: next);
return pages[pageId]!;
}
@override
Future<PageDto> addPageType(String pageId, String ty) =>
setPageTypes(pageId, [...pages[pageId]!.types, ty]);
@override
Future<PageDto> removePageType(String pageId, String ty) =>
setPageTypes(pageId, [
for (final t in pages[pageId]!.types)
if (_tagKey(t) != _tagKey(ty)) t,
]);
@override
Future<List<TagDto>> typeCatalog() async {
final used = <String, TagDto>{};
for (final p in pages.values) {
for (final t in p.types) {
final k = _tagKey(t);
used[k] = TagDto(
name: used[k]?.name ?? t,
count: (used[k]?.count ?? 0) + 1,
suggested: suggestedTypes.contains(k),
);
}
}
final out = used.values.toList()
..sort((a, b) => b.count.compareTo(a.count));
for (final s in suggestedTypes) {
if (!used.containsKey(s)) {
out.add(TagDto(name: s, count: 0, suggested: true));
}
}
return out;
}
@override
Future<PageDto> addPageTag(String pageId, String tag) =>
setPageTags(pageId, [...pages[pageId]!.tags, tag]);
@override
Future<PageDto> removePageTag(String pageId, String tag) =>
setPageTags(pageId, [
for (final t in pages[pageId]!.tags)
if (_tagKey(t) != _tagKey(tag)) t,
]);
@override
Future<List<TagDto>> tagCatalog() async {
final out = [
for (final t in pages.values)
if (t.isTag)
TagDto(
name: t.title,
count: pages.values
.where((p) => p.tags.any((x) => _tagKey(x) == _tagKey(t.title)))
.length,
suggested: false,
),
]..sort((a, b) => b.count.compareTo(a.count));
return out;
}
@override
Future<List<PageBrief>> pagesWithTag(String tag) async => [
for (final p in pages.values)
if (p.tags.any((t) => _tagKey(t) == _tagKey(tag))) _brief(p),
];
@override
Future<String> hubTemplate(String hubId) async {
if (!_isHub(hubId)) throw Exception('Not a hub');
return templates.putIfAbsent(hubId, () {
final t = createPage('Template: ${pages[hubId]!.title}');
return t.id;
});
}
@override
Future<PageDto> createPageFromTemplate(String hubId, String title) async {
final t = await hubTemplate(hubId);
final name = title.trim();
if (name.isEmpty) throw Exception('A title is required');
if (_byTitle(name) != null) {
throw Exception('A page titled "$name" already exists');
}
final p = createPage(name);
seed(p.id, [for (final n in outlines[t]!) (n.depth, n.content)]);
await addToHub(p.id, hubId);
return pages[p.id]!;
}
@override
Future<PageDto> setHubDescription(String hubId, String description) async {
if (!_isHub(hubId)) throw Exception('Not a hub');
_put(pages[hubId]!, description: description);
return pages[hubId]!;
}
@override
Future<void> addToHub(String pageId, String hubId) async {
if (!_isHub(hubId)) throw Exception('The target is not a hub');
if (pageId == hubId) throw Exception('A hub cannot contain itself');
if (pages[pageId]?.journalDate != null) {
throw Exception('Journals cannot be in a hub');
}
if (_reaches(pageId, hubId)) throw Exception('That would create a cycle');
// A page belongs to one hub: adding it elsewhere moves it.
hubsOfPage[pageId] = {hubId};
}
@override
Future<void> removeFromHub(String pageId, String hubId) async {
hubsOfPage[pageId]?.remove(hubId);
}
@override
Future<HubPreviewDto> hubConversionPreview(String pageId) async {
final p = pages[pageId]!;
final title = p.title.split('/').last.trim();
final strip = RegExp(r'\[\[([^\]]+)\]\]|(?:^|\s)#\w+|^#+\s*|\w+::.*');
var prose = 0;
String? first;
final l = outlines[pageId] ?? const <OutlineNode>[];
for (final n in l) {
final text = n.content
.replaceAllMapped(strip, (m) => m.group(1) ?? '')
.trim();
if (text.isEmpty) continue;
prose++;
first ??= text;
}
final members = [..._linked(pageId)];
final ref = '[[${p.title}]]';
for (final q in pages.values) {
if (q.id == pageId || q.journalDate != null) continue;
final refs = (outlines[q.id] ?? const <OutlineNode>[]).any(
(n) => n.content.contains(ref) || n.content.contains('#${p.title}'),
);
if (refs && !members.any((m) => m.id == q.id)) members.add(q);
}
return HubPreviewDto(
suggestedTitle: title,
suggestedDescription: first ?? '',
members: [for (final m in members) _brief(m)],
proseBlocks: prose,
blocks: l.length,
suggestedNoteTitle: '$title (notes)',
);
}
@override
Future<PageDto> convertToHub(
String pageId,
String title,
String description,
List<String> memberIds, {
String? keepOutlineAs,
}) async {
final p = pages[pageId]!;
if (p.journalDate != null) throw Exception('Journals cannot be hubs');
if (p.isHub) throw Exception('Already a hub');
final t = title.trim();
if (t.isEmpty) throw Exception('A title is required');
final clash = _byTitle(t);
if (clash != null && clash.id != pageId) {
throw Exception('A page titled "$t" already exists');
}
final keep = keepOutlineAs?.trim();
if (keep != null) {
if (keep.isEmpty) {
throw Exception('The note that keeps the outline needs a title');
}
// Checked against the new hub title too, like the core (which rolls back).
// (the old title is free once the page is renamed).
final c = _byTitle(keep);
if ((c != null && c.id != pageId) ||
keep.toLowerCase() == t.toLowerCase()) {
throw Exception('A page titled "$keep" already exists');
}
}
if (t != p.title) {
for (final l in outlines.values) {
for (final n in l) {
n.content = n.content.replaceAll('[[${p.title}]]', '[[$t]]');
}
}
_put(p, title: t);
}
String? noteId;
if (keep != null) {
final note = createPage(keep);
outlines[note.id] = outlines[pageId]!;
noteId = note.id;
}
outlines[pageId] = [];
_put(pages[pageId]!, isHub: true, description: description);
if (noteId != null) _tryAdd(noteId, pageId);
for (final m in memberIds) {
_tryAdd(m, pageId);
}
return pages[pageId]!;
}
@override
Future<PageDto> convertToNote(String pageId) async {
final p = pages[pageId]!;
if (!p.isHub) throw Exception('Not a hub');
final members = _members(pageId);
final l = <OutlineNode>[];
if (p.description.isNotEmpty) {
l.add(OutlineNode(id: _id(), depth: 0, content: p.description));
}
for (final m in members) {
l.add(OutlineNode(id: _id(), depth: 0, content: '[[${m.title}]]'));
hubsOfPage[m.id]?.remove(pageId);
}
OutlineOps.fixParents(l);
outlines[pageId] = l;
_put(p, isHub: false, description: '');
return pages[pageId]!;
}
@override
Future<HubsDto> hubs() async {
final all = [
for (final p in pages.values)
if (p.isHub) p,
]..sort((a, b) => a.title.compareTo(b.title));
final roots = [
for (final p in all)
if (!(hubsOfPage[p.id] ?? const {}).any(_isHub)) p.id,
];
final depth = <String, int>{};
var frontier = roots;
for (var d = 0; frontier.isNotEmpty; d++) {
final next = <String>[];
for (final id in frontier) {
if (depth.containsKey(id)) continue;
depth[id] = d;
next.addAll([
for (final m in _members(id))
if (m.isHub) m.id,
]);
}
frontier = next;
}
return HubsDto(
hubs: [
for (final p in all)
HubDto(
id: p.id,
title: p.title,
description: p.description,
depth: depth[p.id] ?? 0,
members: [for (final m in _members(p.id)) _brief(m)],
subHubs: [
for (final m in _members(p.id))
if (m.isHub) m.id,
],
),
],
roots: roots,
);
}
/// Deepest hub containing each page (ties: fewer members, then title); a hub maps to
/// itself.
Map<String, String> _home(HubsDto h) {
final byId = {for (final x in h.hubs) x.id: x};
final home = <String, String>{};
for (final p in pages.values) {
if (p.isHub) {
home[p.id] = p.id;
continue;
}
final cand = [
for (final id in hubsOfPage[p.id] ?? const <String>{})
if (byId.containsKey(id)) byId[id]!,
];
if (cand.isEmpty) continue;
cand.sort((a, b) {
final d = b.depth.compareTo(a.depth);
if (d != 0) return d;
final m = a.members.length.compareTo(b.members.length);
return m != 0 ? m : a.title.compareTo(b.title);
});
home[p.id] = cand.first.id;
}
return home;
}
@override
Future<PageStructure> pageStructure(String pageId) async {
final p = pages[pageId]!;
final parts = p.title.split('/');
final path = <NamespaceEntry>[];
for (var i = 1; i < parts.length; i++) {
final t = parts.sublist(0, i).join('/');
path.add(NamespaceEntry(title: t, id: _byTitle(t)?.id));
}
final prefix = '${p.title}/';
final children = [
for (final q in pages.values)
if (q.title.startsWith(prefix) &&
!q.title.substring(prefix.length).contains('/'))
NamespaceEntry(title: q.title, id: q.id),
]..sort((a, b) => a.title.compareTo(b.title));
final inHubs = [
for (final id in hubsOfPage[pageId] ?? const <String>{})
if (pages[id] != null && pages[id]!.isHub) pages[id]!,
]..sort((a, b) => a.title.compareTo(b.title));
return PageStructure(
isHub: p.isHub,
description: p.description,
members: p.isHub ? [for (final m in _members(pageId)) _brief(m)] : [],
inHubs: [for (final h in inHubs) _brief(h)],
nsPath: path,
nsChildren: children,
);
}
@override
Future<List<LegacyCandidate>> legacyCandidates() async => [
for (final e in legacy.entries)
if (pages.containsKey(e.key))
LegacyCandidate(
id: e.key,
title: pages[e.key]!.title,
reason: e.value,
blocks: outlines[e.key]?.length ?? 0,
preselected: _preselected(e.key),
),
];
bool _preselected(String id) {
final p = pages[id]!;
final t = p.title.toLowerCase();
return !p.isHub &&
((outlines[id]?.length ?? 0) == 0 ||
const ['contents', 'card', 'favorites'].contains(t) ||
t.startsWith('hls__'));
}
@override
Future<int> purgePages(List<String> ids) async {
var n = 0;
for (final id in ids) {
if (pages.remove(id) != null) n++;
outlines.remove(id);
_forget(id);
purged.add(id);
}
return n;
}
/// Links (`[[x]]`) and tags (`#x`) between pages, built like the Rust side but simpler.
@override
Future<GraphData> graphData() async {
@@ -288,6 +859,13 @@ class MemoryBackend implements GraphBackend {
final s = <int>[], t = <int>[], k = <int>[];
final link = RegExp(r'\[\[([^\]]+)\]\]');
final tag = RegExp(r'(?:^|\s)#(\w+)');
final hubData = await hubs();
final home = _home(hubData);
final containsEdges = <(String, String)>[
for (final e in hubsOfPage.entries)
for (final h in e.value)
if (pages.containsKey(e.key) && pages.containsKey(h)) (h, e.key),
];
final degree = List.filled(ids.length, 0, growable: true);
for (final id in List.of(ids)) {
for (final n in outlines[id]!) {
@@ -306,6 +884,24 @@ class MemoryBackend implements GraphBackend {
}
}
}
for (final (h, m) in containsEdges) {
s.add(index[h]!);
t.add(index[m]!);
k.add(EdgeKind.contains.index);
}
// A note points at each of its tag pages.
for (final p in pages.values) {
final i = index[p.id];
if (i == null) continue;
for (final tg in p.tags) {
final tp = _byTitle(tg);
final j = tp == null ? null : index[tp.id];
if (j == null) continue;
s.add(i);
t.add(j);
k.add(EdgeKind.tagged.index);
}
}
while (degree.length < ids.length) {
degree.add(0);
}
@@ -324,6 +920,9 @@ class MemoryBackend implements GraphBackend {
degree: degree[i],
backlinks: 0,
cluster: 0,
isHub: _isHub(ids[i]),
homeHub: home[ids[i]] == null ? null : index[home[ids[i]]!],
tags: pages[ids[i]]!.tags,
),
],
sources: Uint32List.fromList(s),
@@ -394,3 +993,12 @@ class FakeLayout implements LayoutEngine {
@override
void dispose() => disposed = true;
}
/// Map-like shortcut for tests: assigning `true` converts the page to a hub.
class _HubFlags {
_HubFlags(this._b);
final MemoryBackend _b;
void operator []=(String id, bool hub) {
if (hub && !_b._isHub(id)) _b.makeHub(id);
}
}