diff --git a/app/lib/src/graph/tree_canvas.dart b/app/lib/src/graph/tree_canvas.dart index f51ac29..9649c16 100644 --- a/app/lib/src/graph/tree_canvas.dart +++ b/app/lib/src/graph/tree_canvas.dart @@ -46,22 +46,30 @@ class TreeItem { } } -/// Hub branches: root hubs (hubs that are no other hub's member) with their members, -/// recursively, plus the notes that live in no hub (orphans included). A hub is expanded once -/// (the first time it is reached) and never inside itself, so cycles and shared sub-hubs stay -/// bounded; later occurrences are leaves. -List _hubBranches(GraphModel g) { - final branches = []; +/// Builds the tree in which every page appears exactly once: hubs first (root hubs with +/// their members, recursively; a page belongs to one hub), then namespaces (`a/b/c` titles +/// split on `/`, straight off the centre) for pages in no hub, then the remaining notes +/// (orphans included) straight off the centre. Journals and tags are left out. Nothing is +/// capped: large branches are collapsed in the canvas instead. +TreeItem buildNamespaceTree(GraphModel g, {String name = 'Graph'}) { + final root = TreeItem(name); + final placed = {}; + 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 nested = {for (final m in members.values) ...m}; - final expanded = {}; - 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); - if (!expanded.add(hub)) return item; for (final m in members[hub] ?? const {}) { - item.children.add( - g.isHub(m) ? build(m) : TreeItem(g.node(m).title, global: m), - ); + if (!page(m)) continue; + 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; } @@ -70,72 +78,43 @@ List _hubBranches(GraphModel g) { 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)); + for (final h in [...hubs.where((h) => !nested.contains(h)), ...hubs]) { + 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 -/// directly to the centre) and tags (each tag with the pages using it). Nothing is capped: -/// 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'); + // Namespaces, for pages no hub has placed. A namespace level takes its page when that + // page is still free; otherwise it is a plain grouping node. final byTitle = {}; for (var i = 0; i < g.nodeCount; i++) { - if (!g.isJournal(i) && !g.isTag(i)) { - byTitle[g.node(i).title.toLowerCase()] = i; - } + if (page(i)) byTitle[g.node(i).title.toLowerCase()] = i; } + final ns = TreeItem('Namespaces'); for (var i = 0; i < g.nodeCount; i++) { 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; final parts = t.split('/'); for (var k = 0; k < parts.length; k++) { at = at.child(parts[k].trim()); - final path = parts.sublist(0, k + 1).join('/').toLowerCase(); - at.global ??= byTitle[path]; + if (at.global != null) continue; + 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); - final tags = TreeItem('Tags'); - for (final tag in g.tags) { - final item = TreeItem('#${g.node(tag).title}', global: tag); - final seen = {}; - for (final e in g.adjacency[tag]) { - 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)); - } + + // Everything else hangs straight off the centre. + for (var i = 0; i < g.nodeCount; i++) { + if (page(i) && !g.isHub(i) && placed.add(i)) { + root.children.add(TreeItem(g.node(i).title, global: i)); } - tags.children.add(item); } - if (tags.children.isNotEmpty) root.children.add(tags); _measure(root, 0, null); - _place(root, 0, 2 * math.pi); + _place(root, 0, 2 * math.pi, _radii(root)); _colorize(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). 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 _radii(TreeItem root) { + final count = []; + for (final t in _walk(root)) { + while (count.length <= t.depth) { + count.add(0); + } + count[t.depth]++; + } + final r = [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 radii) { 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)); var a = a0; for (final c in t.children) { final span = (a1 - a0) * c.leaves / t.leaves; - _place(c, a, a + span); + _place(c, a, a + span, radii); a += span; } } @@ -203,11 +199,22 @@ Iterable _shown(TreeItem t) sync* { } } -/// Opens levels breadth-first while the canvas stays readable (about `budget` items), so a -/// small graph shows whole and a large one its top levels. Small branches (up to `small` -/// children) always open: a crowded centre must not leave them folded. -void expandInitial(TreeItem root, {int budget = 150, int small = 12}) { +/// Opens the whole tree when it has up to `all` items. Larger trees open breadth-first while +/// the canvas stays readable (about `budget` items); small branches (up to `small` children) +/// always open, so a crowded centre does not leave them folded. +void expandInitial( + TreeItem root, { + int all = 1500, + int budget = 400, + int small = 12, +}) { 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 level = root.children; while (level.isNotEmpty) { @@ -233,7 +240,6 @@ class TreeCanvas extends StatefulWidget { super.key, required this.model, required this.onTap, - this.onTag, this.name = 'Graph', }); final GraphModel model; @@ -242,10 +248,6 @@ class TreeCanvas extends StatefulWidget { final String name; 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 State createState() => TreeCanvasState(); } @@ -342,7 +344,8 @@ class TreeCanvasState extends State { } final n = _items.length - 1; 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; for (var k = 1; k < _items.length; k++) { s[e] = _index[_items[k].parent!]!; @@ -360,15 +363,8 @@ class TreeCanvasState extends State { // Name hit areas belong to the old layout until the next paint. _labelRects.clear(); _repaint.value++; - // A fresh tree relaxes its radial seed harder (warm up before the first step). - if (fresh) { - final gen = _generation; - _engine!.reheat(0.8).whenComplete(() { - if (mounted && gen == _generation) _run(); - }); - } else { - _run(); - } + // The radial seed is already a tree: the layout only relaxes it (no reheat). + _run(); } Future _run() async { @@ -477,19 +473,7 @@ class TreeCanvasState extends State { setState(_relayout); } - /// Opens the page (or tag) behind `t`, as a click on its name does. - 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 _open(int global) => widget.onTap(global); void _onTap(Offset local) { final k = _hitNode(local); @@ -504,7 +488,7 @@ class TreeCanvasState extends State { } final l = _hitLabel(local); if (l?.global != null) { - openItem(l!); + _open(l!.global!); } else if (l != null) { toggle(l); } diff --git a/app/lib/src/views/graph_view.dart b/app/lib/src/views/graph_view.dart index 7dc3fd6..dea4775 100644 --- a/app/lib/src/views/graph_view.dart +++ b/app/lib/src/views/graph_view.dart @@ -429,7 +429,6 @@ class _GraphViewState extends State { return TreeCanvas( model: m, onTap: _open, - onTag: AppScope.read(context).openTag, name: AppScope.read(context).backend.graphName, ); } diff --git a/app/test/graph_view_test.dart b/app/test/graph_view_test.dart index c942795..74abde1 100644 --- a/app/test/graph_view_test.dart +++ b/app/test/graph_view_test.dart @@ -123,24 +123,29 @@ void main() { 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 root = buildNamespaceTree(model); 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. + // Namespaces have no node of their own: `proj` hangs off the centre, next to the + // notes in no hub. Tags are not part of the tree. 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('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( @@ -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()); expect(m.isTag(2), isTrue); - expect(m.tags, [2]); final root = buildNamespaceTree(m); - final tags = root.children.firstWhere((c) => c.label == 'Tags'); - final ocio = tags.children.single; - 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, - ); + expect(_treeItems(root).where((t) => t.global == 2), isEmpty); + expect(root.children.where((c) => c.label == 'Tags'), isEmpty); }); test('filtering by a tag node keeps the tagged pages', () { final m = GraphModel(tagData()); 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(find.byType(TreeCanvas)); - final tags = buildNamespaceTree(m).children - .firstWhere((c) => c.label == 'Tags'); - state.openItem(tags.children.single); - expect(opened, 'ocio'); - }); }); group('hubs', () { @@ -431,12 +399,8 @@ void main() { }); 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, - ); + // Media is already placed: it does not show again under TV (no loop, no repeat). + expect(tv.children.map((c) => c.label).toSet(), {'Anime'}); }); 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 hub = root.children.single; expect(hub.children, hasLength(200)); expect(hub.children.every((c) => c.global != null), isTrue); expandInitial(root); - expect(root.expanded, isTrue); - expect(hub.expanded, isFalse); + expect(root.expanded && hub.expanded, isTrue); + }); + + 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', () { @@ -498,7 +467,9 @@ void main() { await pumpGraph(tester, _HubBackend(bigHub())); await mode(tester, 'Tree'); final state = tester.state(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); state.toggle(state.root.children.single); await settle(tester); @@ -521,3 +492,11 @@ class _HubBackend extends MemoryBackend { @override Future graphData() async => _data; } + +/// Every item of a tree, depth first. +Iterable _treeItems(TreeItem t) sync* { + yield t; + for (final c in t.children) { + yield* _treeItems(c); + } +} diff --git a/docs/app.md b/docs/app.md index 07fab12..d036f00 100644 --- a/docs/app.md +++ b/docs/app.md @@ -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 of the tag; journals and untagged pages stay out) or by "Communities" (Louvain: groups found automatically from link density, no names). Colours follow group size. -- **Tree**: hubs (root hubs, then members recursively, cycle-safe, each hub expanded once, - folder glyph; membership = CONTAINS edges), namespaces (`a/b/c` titles, straight off the - centre), the notes in no hub (orphans included) and Tags (each tag node with its pages; - clicking a tag opens its tag view). Nothing is - capped. Laid out by the same `ForceLayout` as the network (edges = parent/child, seeded - from a radial layout). The centre carries the store name; every arm and sub-branch has its - own colour (arms evenly spread over the hue circle, children split their parent's sector). - Levels open breadth-first up to ~150 nodes; the rest start collapsed (ring + `+N` badge). - Click a branch to expand/collapse 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. +- **Tree**: every page appears exactly once. Hubs first (root hubs, then members + recursively, cycle-safe, folder glyph; membership = CONTAINS edges; a page is in one hub), + then namespaces (`a/b/c` titles, straight off the centre) for pages in no hub, then the + remaining notes (orphans included) off the centre. Journals and tags are not in the tree. + Nothing is capped. Laid out by the same `ForceLayout` as the network (stiff parent/child + edges, seeded from a radial layout whose rings widen with the nodes on them, no reheat). + The centre carries the store name; every arm and sub-branch has its own colour (arms + evenly spread over the hue circle, children split their parent's sector). Trees of up to + 1,500 items open whole; larger ones open breadth-first up to ~400 (small branches always + open) and the rest start collapsed (ring + `+N` badge). Click a branch to expand/collapse + 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. Data and layout live in Rust: `SynapseGraph::graph_data()` returns the whole page-level