feat(app): tree shows every page once, without tags, opened whole and compact

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
dasemuandClaude Opus 5.5 committed 2026-10-26 03:48:25 +01:00
1 parent 2576848d84
commit 50e5572575
4 files changed
+129 -166

No files matched your search

+81 -97
View File
@@ -46,22 +46,30 @@ class TreeItem {
} }
} }
/// Hub branches: root hubs (hubs that are no other hub's member) with their members, /// Builds the tree in which every page appears exactly once: hubs first (root hubs with
/// recursively, plus the notes that live in no hub (orphans included). A hub is expanded once /// their members, recursively; a page belongs to one hub), then namespaces (`a/b/c` titles
/// (the first time it is reached) and never inside itself, so cycles and shared sub-hubs stay /// split on `/`, straight off the centre) for pages in no hub, then the remaining notes
/// bounded; later occurrences are leaves. /// (orphans included) straight off the centre. Journals and tags are left out. Nothing is
List<TreeItem> _hubBranches(GraphModel g) { /// capped: large branches are collapsed in the canvas instead.
final branches = <TreeItem>[]; TreeItem buildNamespaceTree(GraphModel g, {String name = 'Graph'}) {
final root = TreeItem(name);
final placed = <int>{};
bool page(int i) => !g.isJournal(i) && !g.isTag(i);
// Hubs. A hub reached twice (cycles, shared sub-hubs) only shows the first time.
final members = g.hubMembers; final members = g.hubMembers;
final nested = {for (final m in members.values) ...m}; final nested = {for (final m in members.values) ...m};
final expanded = <int>{}; TreeItem? build(int hub) {
TreeItem build(int hub) { if (!placed.add(hub)) return null;
final item = TreeItem(g.node(hub).title, global: hub, isHub: true); final item = TreeItem(g.node(hub).title, global: hub, isHub: true);
if (!expanded.add(hub)) return item;
for (final m in members[hub] ?? const <int>{}) { for (final m in members[hub] ?? const <int>{}) {
item.children.add( if (!page(m)) continue;
g.isHub(m) ? build(m) : TreeItem(g.node(m).title, global: m), if (g.isHub(m)) {
); final sub = build(m);
if (sub != null) item.children.add(sub);
} else if (placed.add(m)) {
item.children.add(TreeItem(g.node(m).title, global: m));
}
} }
return item; return item;
} }
@@ -70,72 +78,43 @@ List<TreeItem> _hubBranches(GraphModel g) {
for (var i = 0; i < g.nodeCount; i++) for (var i = 0; i < g.nodeCount; i++)
if (g.isHub(i)) i, if (g.isHub(i)) i,
]; ];
for (final h in hubs) { for (final h in [...hubs.where((h) => !nested.contains(h)), ...hubs]) {
if (!nested.contains(h)) branches.add(build(h)); final b = build(h);
if (b != null) root.children.add(b);
} }
// 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).
for (var i = 0; i < g.nodeCount; i++) {
if (!g.isHub(i) &&
!g.isTag(i) &&
!g.isJournal(i) &&
!nested.contains(i) &&
!g.node(i).title.contains('/')) {
branches.add(TreeItem(g.node(i).title, global: i));
}
}
return branches;
}
/// Builds a tree from hubs (folders, straight off the centre, with loose notes), namespaces (`a/b/c` titles split on `/`, attached // Namespaces, for pages no hub has placed. A namespace level takes its page when that
/// directly to the centre) and tags (each tag with the pages using it). Nothing is capped: // page is still free; otherwise it is a plain grouping node.
/// large branches are collapsed in the canvas instead.
TreeItem buildNamespaceTree(GraphModel g, {String name = 'Graph'}) {
final root = TreeItem(name);
root.children.addAll(_hubBranches(g));
final ns = TreeItem('Namespaces');
final byTitle = <String, int>{}; final byTitle = <String, int>{};
for (var i = 0; i < g.nodeCount; i++) { for (var i = 0; i < g.nodeCount; i++) {
if (!g.isJournal(i) && !g.isTag(i)) { if (page(i)) byTitle[g.node(i).title.toLowerCase()] = i;
byTitle[g.node(i).title.toLowerCase()] = i;
}
} }
final ns = TreeItem('Namespaces');
for (var i = 0; i < g.nodeCount; i++) { for (var i = 0; i < g.nodeCount; i++) {
final t = g.node(i).title; final t = g.node(i).title;
if (g.isJournal(i) || g.isTag(i) || !t.contains('/')) continue; if (!page(i) || placed.contains(i) || !t.contains('/')) continue;
var at = ns; var at = ns;
final parts = t.split('/'); final parts = t.split('/');
for (var k = 0; k < parts.length; k++) { for (var k = 0; k < parts.length; k++) {
at = at.child(parts[k].trim()); at = at.child(parts[k].trim());
final path = parts.sublist(0, k + 1).join('/').toLowerCase(); if (at.global != null) continue;
at.global ??= byTitle[path]; final p = byTitle[parts.sublist(0, k + 1).join('/').toLowerCase()];
if (p != null && !placed.contains(p)) {
at.global = p;
placed.add(p);
}
} }
} }
// No "Namespaces" node: top-level namespaces hang straight off the centre.
root.children.addAll(ns.children); root.children.addAll(ns.children);
final tags = TreeItem('Tags');
for (final tag in g.tags) { // Everything else hangs straight off the centre.
final item = TreeItem('#${g.node(tag).title}', global: tag); for (var i = 0; i < g.nodeCount; i++) {
final seen = <int>{}; if (page(i) && !g.isHub(i) && placed.add(i)) {
for (final e in g.adjacency[tag]) { root.children.add(TreeItem(g.node(i).title, global: i));
final k = g.kind(e);
if ((k != EdgeKind.tag && k != EdgeKind.tagged) || g.target(e) != tag) {
continue;
}
final s = g.source(e);
if (seen.add(s)) {
item.children.add(TreeItem(g.node(s).title, global: s));
}
} }
tags.children.add(item);
} }
if (tags.children.isNotEmpty) root.children.add(tags);
_measure(root, 0, null); _measure(root, 0, null);
_place(root, 0, 2 * math.pi); _place(root, 0, 2 * math.pi, _radii(root));
_colorize(root); _colorize(root);
return root; return root;
} }
@@ -175,14 +154,31 @@ int _measure(TreeItem t, int depth, TreeItem? parent) {
/// Ring spacing of the seed layout (close to the force layout's link length). /// Ring spacing of the seed layout (close to the force layout's link length).
const _ring = 60.0; const _ring = 60.0;
void _place(TreeItem t, double a0, double a1) { /// Seed radius per depth: rings at least `_ring` apart, wide enough for the nodes on them
/// (about 14 px of circumference each) so the force layout starts compact but unpacked.
List<double> _radii(TreeItem root) {
final count = <int>[];
for (final t in _walk(root)) {
while (count.length <= t.depth) {
count.add(0);
}
count[t.depth]++;
}
final r = <double>[0];
for (var d = 1; d < count.length; d++) {
r.add(math.max(r[d - 1] + _ring, count[d] * 14 / (2 * math.pi)));
}
return r;
}
void _place(TreeItem t, double a0, double a1, List<double> radii) {
t.angle = (a0 + a1) / 2; t.angle = (a0 + a1) / 2;
final r = t.depth * _ring; final r = radii[t.depth];
t.pos = Offset(r * math.cos(t.angle), r * math.sin(t.angle)); t.pos = Offset(r * math.cos(t.angle), r * math.sin(t.angle));
var a = a0; var a = a0;
for (final c in t.children) { for (final c in t.children) {
final span = (a1 - a0) * c.leaves / t.leaves; final span = (a1 - a0) * c.leaves / t.leaves;
_place(c, a, a + span); _place(c, a, a + span, radii);
a += span; a += span;
} }
} }
@@ -203,11 +199,22 @@ Iterable<TreeItem> _shown(TreeItem t) sync* {
} }
} }
/// Opens levels breadth-first while the canvas stays readable (about `budget` items), so a /// Opens the whole tree when it has up to `all` items. Larger trees open breadth-first while
/// small graph shows whole and a large one its top levels. Small branches (up to `small` /// the canvas stays readable (about `budget` items); small branches (up to `small` children)
/// children) always open: a crowded centre must not leave them folded. /// always open, so a crowded centre does not leave them folded.
void expandInitial(TreeItem root, {int budget = 150, int small = 12}) { void expandInitial(
TreeItem root, {
int all = 1500,
int budget = 400,
int small = 12,
}) {
root.expanded = true; root.expanded = true;
if (_walk(root).length <= all) {
for (final t in _walk(root)) {
t.expanded = t.children.isNotEmpty;
}
return;
}
var shown = 1 + root.children.length; var shown = 1 + root.children.length;
var level = root.children; var level = root.children;
while (level.isNotEmpty) { while (level.isNotEmpty) {
@@ -233,7 +240,6 @@ class TreeCanvas extends StatefulWidget {
super.key, super.key,
required this.model, required this.model,
required this.onTap, required this.onTap,
this.onTag,
this.name = 'Graph', this.name = 'Graph',
}); });
final GraphModel model; final GraphModel model;
@@ -242,10 +248,6 @@ class TreeCanvas extends StatefulWidget {
final String name; final String name;
final void Function(int global) onTap; final void Function(int global) onTap;
/// Called with the tag name when a tag (which has no page) is clicked; falls back to
/// [onTap] when null.
final void Function(String name)? onTag;
@override @override
State<TreeCanvas> createState() => TreeCanvasState(); State<TreeCanvas> createState() => TreeCanvasState();
} }
@@ -342,7 +344,8 @@ class TreeCanvasState extends State<TreeCanvas> {
} }
final n = _items.length - 1; final n = _items.length - 1;
final s = Uint32List(n), t = Uint32List(n); final s = Uint32List(n), t = Uint32List(n);
final w = Float32List(n)..fillRange(0, n, 1); // Stiff parent links keep branches close to their parent instead of drifting apart.
final w = Float32List(n)..fillRange(0, n, 3);
var e = 0; var e = 0;
for (var k = 1; k < _items.length; k++) { for (var k = 1; k < _items.length; k++) {
s[e] = _index[_items[k].parent!]!; s[e] = _index[_items[k].parent!]!;
@@ -360,15 +363,8 @@ class TreeCanvasState extends State<TreeCanvas> {
// Name hit areas belong to the old layout until the next paint. // Name hit areas belong to the old layout until the next paint.
_labelRects.clear(); _labelRects.clear();
_repaint.value++; _repaint.value++;
// A fresh tree relaxes its radial seed harder (warm up before the first step). // The radial seed is already a tree: the layout only relaxes it (no reheat).
if (fresh) { _run();
final gen = _generation;
_engine!.reheat(0.8).whenComplete(() {
if (mounted && gen == _generation) _run();
});
} else {
_run();
}
} }
Future<void> _run() async { Future<void> _run() async {
@@ -477,19 +473,7 @@ class TreeCanvasState extends State<TreeCanvas> {
setState(_relayout); setState(_relayout);
} }
/// Opens the page (or tag) behind `t`, as a click on its name does. void _open(int global) => widget.onTap(global);
void openItem(TreeItem t) {
if (t.global != null) _open(t.global!);
}
void _open(int global) {
final g = widget.model;
if (g.isTag(global) && widget.onTag != null) {
widget.onTag!(g.node(global).title);
} else {
widget.onTap(global);
}
}
void _onTap(Offset local) { void _onTap(Offset local) {
final k = _hitNode(local); final k = _hitNode(local);
@@ -504,7 +488,7 @@ class TreeCanvasState extends State<TreeCanvas> {
} }
final l = _hitLabel(local); final l = _hitLabel(local);
if (l?.global != null) { if (l?.global != null) {
openItem(l!); _open(l!.global!);
} else if (l != null) { } else if (l != null) {
toggle(l); toggle(l);
} }
-1
View File
@@ -429,7 +429,6 @@ class _GraphViewState extends State<GraphView> {
return TreeCanvas( return TreeCanvas(
model: m, model: m,
onTap: _open, onTap: _open,
onTag: AppScope.read(context).openTag,
name: AppScope.read(context).backend.graphName, name: AppScope.read(context).backend.graphName,
); );
} }
+36 -57
View File
@@ -123,24 +123,29 @@ void main() {
await tester.pump(const Duration(seconds: 1)); await tester.pump(const Duration(seconds: 1));
}); });
test('tree groups a/b titles and tags', () async { test('tree groups a/b titles; tags stay out', () async {
final model = GraphModel(await demo().graphData()); final model = GraphModel(await demo().graphData());
final root = buildNamespaceTree(model); final root = buildNamespaceTree(model);
TreeItem branch(String l) => root.children.firstWhere((c) => c.label == l); 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, next to the
// Namespaces have no node of their own: `proj` hangs off the centre. // notes in no hub. Tags are not part of the tree.
expect(root.children.map((c) => c.label), [ expect(root.children.map((c) => c.label), [
'Alpha', 'Alpha',
'Beta', 'Beta',
'Lonely', 'Lonely',
'proj', 'proj',
'Tags',
'topic', 'topic',
]); ]);
expect(branch('proj').children.single.label, 'one'); 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('every page appears once in the tree', () async {
final model = GraphModel(await demo().graphData());
final globals = [
for (final t in _treeItems(buildNamespaceTree(model)))
if (t.global != null) t.global!,
];
expect(globals.toSet().length, globals.length);
}); });
test( test(
@@ -290,55 +295,18 @@ void main() {
); );
} }
test('the Tags branch is built from tag nodes, not loose notes', () { test('tag nodes stay out of the tree', () {
final m = GraphModel(tagData()); final m = GraphModel(tagData());
expect(m.isTag(2), isTrue); expect(m.isTag(2), isTrue);
expect(m.tags, [2]);
final root = buildNamespaceTree(m); final root = buildNamespaceTree(m);
final tags = root.children.firstWhere((c) => c.label == 'Tags'); expect(_treeItems(root).where((t) => t.global == 2), isEmpty);
final ocio = tags.children.single; expect(root.children.where((c) => c.label == 'Tags'), isEmpty);
expect(ocio.label, '#ocio');
expect(ocio.global, 2);
expect(ocio.children.map((c) => c.label).toSet(), {'Games', 'Chess'});
// Tag nodes are neither loose notes nor namespaces.
expect(
root.children.where((c) => c.label == 'ocio' || c.label == 'a'),
isEmpty,
);
}); });
test('filtering by a tag node keeps the tagged pages', () { test('filtering by a tag node keeps the tagged pages', () {
final m = GraphModel(tagData()); final m = GraphModel(tagData());
expect(const GraphFilter().copyWith(tag: () => 2).apply(m), [0, 1, 2]); expect(const GraphFilter().copyWith(tag: () => 2).apply(m), [0, 1, 2]);
}); });
testWidgets('a tag in the tree opens its tag view by name', (tester) async {
String? opened;
final m = GraphModel(tagData());
tester.view.physicalSize = const Size(1600, 1000);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.reset);
await tester.pumpWidget(
AppScope(
state: AppState(MemoryBackend()),
child: MaterialApp(
theme: buildTheme(Brightness.light),
home: Scaffold(
body: TreeCanvas(
model: m,
onTap: (_) {},
onTag: (name) => opened = name,
),
),
),
),
);
final state = tester.state<TreeCanvasState>(find.byType(TreeCanvas));
final tags = buildNamespaceTree(m).children
.firstWhere((c) => c.label == 'Tags');
state.openItem(tags.children.single);
expect(opened, 'ocio');
});
}); });
group('hubs', () { group('hubs', () {
@@ -431,12 +399,8 @@ void main() {
}); });
final tv = media.children.firstWhere((c) => c.label == 'TV'); final tv = media.children.firstWhere((c) => c.label == 'TV');
expect(tv.isHub, isTrue); expect(tv.isHub, isTrue);
// Media already on the path: a leaf, not an endless loop. // Media is already placed: it does not show again under TV (no loop, no repeat).
expect(tv.children.map((c) => c.label).toSet(), {'Anime', 'Media'}); expect(tv.children.map((c) => c.label).toSet(), {'Anime'});
expect(
tv.children.firstWhere((c) => c.label == 'Media').children,
isEmpty,
);
}); });
testWidgets('clusters mode groups by hub by default', (tester) async { testWidgets('clusters mode groups by hub by default', (tester) async {
@@ -473,14 +437,19 @@ void main() {
); );
} }
test('nothing is capped; big branches start collapsed', () { test('nothing is capped; a tree that fits opens whole', () {
final root = buildNamespaceTree(GraphModel(bigHub())); final root = buildNamespaceTree(GraphModel(bigHub()));
final hub = root.children.single; final hub = root.children.single;
expect(hub.children, hasLength(200)); expect(hub.children, hasLength(200));
expect(hub.children.every((c) => c.global != null), isTrue); expect(hub.children.every((c) => c.global != null), isTrue);
expandInitial(root); expandInitial(root);
expect(root.expanded, isTrue); expect(root.expanded && hub.expanded, isTrue);
expect(hub.expanded, isFalse); });
test('a huge tree opens only within the budget', () {
final root = buildNamespaceTree(GraphModel(bigHub()));
expandInitial(root, all: 100, budget: 50);
expect(root.children.single.expanded, isFalse);
}); });
test('small branches open even when the centre is crowded', () { test('small branches open even when the centre is crowded', () {
@@ -498,7 +467,9 @@ void main() {
await pumpGraph(tester, _HubBackend(bigHub())); await pumpGraph(tester, _HubBackend(bigHub()));
await mode(tester, 'Tree'); await mode(tester, 'Tree');
final state = tester.state<TreeCanvasState>(find.byType(TreeCanvas)); final state = tester.state<TreeCanvasState>(find.byType(TreeCanvas));
expect(state.visibleCount, 2); expect(state.visibleCount, 202);
state.toggle(state.root.children.single);
await settle(tester);
expect(find.text('2 of 202'), findsOneWidget); expect(find.text('2 of 202'), findsOneWidget);
state.toggle(state.root.children.single); state.toggle(state.root.children.single);
await settle(tester); await settle(tester);
@@ -521,3 +492,11 @@ class _HubBackend extends MemoryBackend {
@override @override
Future<GraphData> graphData() async => _data; Future<GraphData> graphData() async => _data;
} }
/// Every item of a tree, depth first.
Iterable<TreeItem> _treeItems(TreeItem t) sync* {
yield t;
for (final c in t.children) {
yield* _treeItems(c);
}
}
+12 -11
View File
@@ -195,17 +195,18 @@ One view (sidebar "Graph", Ctrl+Shift+G) with a mode selector:
alphabetical; hull labelled with the tag name; springs pull pages to the best connected page alphabetical; hull labelled with the tag name; springs pull pages to the best connected page
of the tag; journals and untagged pages stay out) or by "Communities" (Louvain: groups found of the tag; journals and untagged pages stay out) or by "Communities" (Louvain: groups found
automatically from link density, no names). Colours follow group size. automatically from link density, no names). Colours follow group size.
- **Tree**: hubs (root hubs, then members recursively, cycle-safe, each hub expanded once, - **Tree**: every page appears exactly once. Hubs first (root hubs, then members
folder glyph; membership = CONTAINS edges), namespaces (`a/b/c` titles, straight off the recursively, cycle-safe, folder glyph; membership = CONTAINS edges; a page is in one hub),
centre), the notes in no hub (orphans included) and Tags (each tag node with its pages; then namespaces (`a/b/c` titles, straight off the centre) for pages in no hub, then the
clicking a tag opens its tag view). Nothing is remaining notes (orphans included) off the centre. Journals and tags are not in the tree.
capped. Laid out by the same `ForceLayout` as the network (edges = parent/child, seeded Nothing is capped. Laid out by the same `ForceLayout` as the network (stiff parent/child
from a radial layout). The centre carries the store name; every arm and sub-branch has its edges, seeded from a radial layout whose rings widen with the nodes on them, no reheat).
own colour (arms evenly spread over the hue circle, children split their parent's sector). The centre carries the store name; every arm and sub-branch has its own colour (arms
Levels open breadth-first up to ~150 nodes; the rest start collapsed (ring + `+N` badge). evenly spread over the hue circle, children split their parent's sector). Trees of up to
Click a branch to expand/collapse it, a page (or any name) to open it; hover highlights the 1,500 items open whole; larger ones open breadth-first up to ~400 (small branches always
path to the centre; drag nodes, wheel/pinch to zoom. Bottom bar: shown/total count, expand open) and the rest start collapsed (ring + `+N` badge). Click a branch to expand/collapse
all, collapse all, fit. it, a page (or any name) to open it; hover highlights the path to the centre; drag nodes,
wheel/pinch to zoom. Bottom bar: shown/total count, expand all, collapse all, fit.
- **Timeline**: the journal timeline. - **Timeline**: the journal timeline.
Data and layout live in Rust: `SynapseGraph::graph_data()` returns the whole page-level Data and layout live in Rust: `SynapseGraph::graph_data()` returns the whole page-level