From 45699bf4e783c9003965934825ecfd54bf35f14c Mon Sep 17 00:00:00 2001 From: Dasemu Date: Mon, 26 Oct 2026 03:12:05 +0100 Subject: [PATCH] feat(app): interactive force-laid tree with collapsible branches Co-Authored-By: Claude Opus 5.5 --- app/lib/src/graph/tree_canvas.dart | 907 ++++++++++++++++++++++------- app/test/graph_view_test.dart | 53 ++ 2 files changed, 738 insertions(+), 222 deletions(-) diff --git a/app/lib/src/graph/tree_canvas.dart b/app/lib/src/graph/tree_canvas.dart index 9dd5249..c8156c5 100644 --- a/app/lib/src/graph/tree_canvas.dart +++ b/app/lib/src/graph/tree_canvas.dart @@ -1,7 +1,12 @@ import 'dart:math' as math; -import 'package:flutter/material.dart'; +import 'dart:typed_data'; +import 'package:flutter/gestures.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/scheduler.dart'; + +import '../state/app_state.dart'; import '../theme/theme.dart'; import 'graph_model.dart'; @@ -16,6 +21,10 @@ class TreeItem { /// Page index when the item is a page. int? global; final children = []; + TreeItem? parent; + + /// Whether the children are shown in the canvas. + bool expanded = false; int depth = 0; int leaves = 1; double angle = 0; @@ -38,9 +47,10 @@ 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, int maxPerHub, int maxLoose) { +/// 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 = []; final members = g.hubMembers; final nested = {for (final m in members.values) ...m}; @@ -48,19 +58,11 @@ List _hubBranches(GraphModel g, int maxPerHub, int maxLoose) { TreeItem build(int hub) { final item = TreeItem(g.node(hub).title, global: hub, isHub: true); if (!expanded.add(hub)) return item; - var shown = 0; - final all = members[hub] ?? const {}; - // Sub-hubs are always listed; plain pages are capped. - for (final m in all) { - if (g.isHub(m)) { - item.children.add(build(m)); - } else if (shown < maxPerHub) { - shown++; - item.children.add(TreeItem(g.node(m).title, global: m)); - } + for (final m in members[hub] ?? const {}) { + item.children.add( + g.isHub(m) ? build(m) : 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; } @@ -77,35 +79,23 @@ List _hubBranches(GraphModel g, int maxPerHub, int maxLoose) { } // 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')); + for (var i = 0; i < g.nodeCount; i++) { + if (!g.isHub(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, most used tags first). -TreeItem buildNamespaceTree( - GraphModel g, { - String name = 'Graph', - int maxTags = 24, - int maxPerTag = 30, - int maxPerHub = 40, - int maxLoose = 80, -}) { +/// 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, maxPerHub, maxLoose)); + root.children.addAll(_hubBranches(g)); final ns = TreeItem('Namespaces'); final byTitle = {}; for (var i = 0; i < g.nodeCount; i++) { @@ -125,20 +115,20 @@ TreeItem buildNamespaceTree( // 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)) { + for (final tag in g.tags) { final item = TreeItem('#${g.node(tag).title}', global: tag); final seen = {}; for (final e in g.adjacency[tag]) { if (g.kind(e) != EdgeKind.tag || g.target(e) != tag) continue; final s = g.source(e); - if (seen.add(s) && seen.length <= maxPerTag) { + 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); + _measure(root, 0, null); _place(root, 0, 2 * math.pi); _colorize(root); return root; @@ -166,16 +156,18 @@ Color treeColor(TreeItem t, Brightness b) { return HSLColor.fromAHSL(1, (t.hue % 360 + 360) % 360, 0.62, l).toColor(); } -int _measure(TreeItem t, int depth) { +int _measure(TreeItem t, int depth, TreeItem? parent) { t.depth = depth; + t.parent = parent; if (t.children.isEmpty) return t.leaves = 1; t.children.sort( (a, b) => a.label.toLowerCase().compareTo(b.label.toLowerCase()), ); - return t.leaves = t.children.fold(0, (n, c) => n + _measure(c, depth + 1)); + return t.leaves = t.children.fold(0, (n, c) => n + _measure(c, depth + 1, t)); } -const _ring = 120.0; +/// 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) { t.angle = (a0 + a1) / 2; @@ -189,16 +181,6 @@ void _place(TreeItem t, double a0, double a1) { } } -void _shift(TreeItem t, Offset d) { - for (final x in _walk(t)) { - x.pos += d; - } -} - -class _Tick extends ChangeNotifier { - void bump() => notifyListeners(); -} - Iterable _walk(TreeItem t) sync* { yield t; for (final c in t.children) { @@ -206,7 +188,37 @@ Iterable _walk(TreeItem t) sync* { } } -/// Radial tree of hubs, namespaces and tags; pan/zoom with the GPU transform (no repaint). +/// The items on screen: the root and every child of an expanded item. +Iterable _shown(TreeItem t) sync* { + yield t; + if (!t.expanded) return; + for (final c in t.children) { + yield* _shown(c); + } +} + +/// 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. +void expandInitial(TreeItem root, {int budget = 150}) { + root.expanded = true; + var shown = 1 + root.children.length; + var level = root.children; + while (level.isNotEmpty) { + final next = []; + for (final t in level) { + if (t.children.isEmpty) continue; + if (shown + t.children.length > budget) continue; + t.expanded = true; + shown += t.children.length; + next.addAll(t.children); + } + level = next; + } +} + +/// Interactive tree of hubs, namespaces and tags laid out by the force engine (the same one +/// as the network view): click a branch to expand or collapse it, click a page (or a branch's +/// name) to open it, drag nodes, wheel or pinch to zoom. class TreeCanvas extends StatefulWidget { const TreeCanvas({ super.key, @@ -221,55 +233,264 @@ class TreeCanvas extends StatefulWidget { final void Function(int global) onTap; @override - State createState() => _TreeCanvasState(); + State createState() => TreeCanvasState(); } -class _TreeCanvasState extends State { - late TreeItem _root = buildNamespaceTree(widget.model, name: widget.name); - final _tick = _Tick(); - TreeItem? _drag; - bool _pan = true; - final _transform = TransformationController(); - bool _placed = false; +class TreeCanvasState extends State { + late TreeItem _root; + List _items = const []; + final _index = {}; + LayoutEngine? _engine; + Float32List _pos = Float32List(0); + double _alpha = 1; + int _generation = 0; + int? _loopGen; + final _repaint = ValueNotifier(0); + + // Camera: screen = world * scale + offset. + double _scale = 1; + Offset _offset = Offset.zero; + bool _userMoved = false; + Size _size = Size.zero; + double _startScale = 1; + + TreeItem? _hover; + int? _drag; + + /// Where each label was drawn (screen space), for clicks on names. + final _labelRects = <(Rect, TreeItem)>[]; + + @visibleForTesting + TreeItem get root => _root; + + @visibleForTesting + int get visibleCount => _items.length; + + @override + void initState() { + super.initState(); + _build(); + } @override void didUpdateWidget(TreeCanvas oldWidget) { super.didUpdateWidget(oldWidget); if (!identical(oldWidget.model, widget.model) || oldWidget.name != widget.name) { - _root = buildNamespaceTree(widget.model, name: widget.name); + _build(); } } @override void dispose() { - _transform.dispose(); - _tick.dispose(); + _generation++; + _engine?.dispose(); + _repaint.dispose(); super.dispose(); } - double get _extent { - final maxDepth = _walk(_root).fold(0, (m, t) => math.max(m, t.depth)); - return maxDepth * _ring + 170; + void _build() { + _root = buildNamespaceTree(widget.model, name: widget.name); + expandInitial(_root); + _items = const []; + _userMoved = false; + _relayout(); } - /// Nodes can be dragged away from the rings, so the scene is larger than the layout. - double get _half => _extent * 1.6; + /// Restarts the layout over the shown items; known items keep their place, new ones start + /// fanned out around their parent. + void _relayout() { + for (final t in _items) { + final k = _index[t]!; + if (2 * k + 1 < _pos.length) t.pos = Offset(_pos[2 * k], _pos[2 * k + 1]); + } + final known = {..._items}; + _items = _shown(_root).toList(); + _index + ..clear() + ..addAll({for (var k = 0; k < _items.length; k++) _items[k]: k}); + final fresh = known.isEmpty; + for (final t in _items) { + if (fresh || known.contains(t)) continue; + final p = t.parent!; + final away = p.parent == null + ? t.angle + : (p.pos - p.parent!.pos).direction; + final k = p.children.indexOf(t), n = p.children.length; + final spread = p.parent == null ? math.pi : math.pi * 0.45; + final a = away + (n == 1 ? 0 : spread * (2 * k / (n - 1) - 1)); + t.pos = p.pos + Offset.fromDirection(a, 30 + 4 * (k % 3)); + } + final initial = Float32List(2 * _items.length); + for (var k = 0; k < _items.length; k++) { + initial[2 * k] = _items[k].pos.dx; + initial[2 * k + 1] = _items[k].pos.dy; + } + final n = _items.length - 1; + final s = Uint32List(n), t = Uint32List(n); + final w = Float32List(n)..fillRange(0, n, 1); + var e = 0; + for (var k = 1; k < _items.length; k++) { + s[e] = _index[_items[k].parent!]!; + t[e++] = k; + } + _generation++; + _engine?.dispose(); + _engine = AppScope.read(context).backend + .createLayout(_items.length, s, t, w, initial: initial); - 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; + _pos = initial; + _alpha = 1; + _hover = null; + _drag = null; + // 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(); + } + } + + Future _run() async { + if (_loopGen == _generation) return; + _loopGen = _generation; + final gen = _generation; + final engine = _engine!; + final n = _items.length; + final iterations = n > 3000 ? 2 : (n > 800 ? 5 : 12); + try { + while (mounted && gen == _generation) { + final (pos, alpha) = await engine.step(iterations); + if (!mounted || gen != _generation) break; + _pos = pos; + _alpha = alpha; + if (!_userMoved) _fit(animate: true); + _repaint.value++; + if (alpha == 0 && _drag == null) break; + await SchedulerBinding.instance.endOfFrame; + } + } catch (e) { + debugPrint('tree layout stopped: $e'); + } finally { + if (_loopGen == gen) _loopGen = null; + } + } + + /// Whether the layout has cooled down. + bool get settled => _alpha == 0; + + void _fit({bool animate = false}) { + if (_size.isEmpty || _pos.isEmpty) return; + var x0 = double.infinity, y0 = double.infinity; + var x1 = -double.infinity, y1 = -double.infinity; + for (var k = 0; k + 1 < _pos.length; k += 2) { + x0 = math.min(x0, _pos[k]); + x1 = math.max(x1, _pos[k]); + y0 = math.min(y0, _pos[k + 1]); + y1 = math.max(y1, _pos[k + 1]); + } + if (!x0.isFinite || !y0.isFinite) return; + const pad = 70.0; + final w = math.max(x1 - x0, 40.0), h = math.max(y1 - y0, 40.0); + final s = math + .min((_size.width - 2 * pad) / w, (_size.height - 2 * pad) / h) + .clamp(0.05, 1.8); + final o = Offset( + _size.width / 2 - (x0 + x1) / 2 * s, + _size.height / 2 - (y0 + y1) / 2 * s, + ); + if (animate) { + _scale += (s - _scale) * 0.25; + _offset = Offset.lerp(_offset, o, 0.25)!; + } else { + _scale = s; + _offset = o; + } + } + + Offset _toWorld(Offset screen) => (screen - _offset) / _scale; + + Offset _at(int k) => Offset(_pos[2 * k], _pos[2 * k + 1]); + + double _radius(TreeItem t) { + if (t.parent == null) return 8; + if (t.children.isEmpty) return 3.5; + return math.min(4.5 + math.sqrt(t.children.length) * 0.9, 13); + } + + int? _hitNode(Offset screen) { + final p = _toWorld(screen); + int? best; + var bestD = double.infinity; + for (var k = 0; k < _items.length && 2 * k + 1 < _pos.length; k++) { + final d = (_at(k) - p).distanceSquared; + final r = _radius(_items[k]) + 5 / _scale; + if (d <= r * r && d < bestD) { + bestD = d; + best = k; } } return best; } + TreeItem? _hitLabel(Offset screen) { + for (final (r, t) in _labelRects.reversed) { + if (r.inflate(2).contains(screen)) return t; + } + return null; + } + + /// Expands or collapses `t` (a branch). + @visibleForTesting + void toggle(TreeItem t) { + if (t.children.isEmpty) return; + setState(() => t.expanded = !t.expanded); + _relayout(); + } + + void _setAll(bool open) { + for (final t in _walk(_root)) { + if (t.children.isNotEmpty) t.expanded = open; + } + _root.expanded = true; + _userMoved = false; + setState(_relayout); + } + + void _onTap(Offset local) { + final k = _hitNode(local); + if (k != null) { + final t = _items[k]; + if (t.children.isNotEmpty) { + toggle(t); + } else if (t.global != null) { + widget.onTap(t.global!); + } + return; + } + final l = _hitLabel(local); + if (l?.global != null) { + widget.onTap(l!.global!); + } else if (l != null) { + toggle(l); + } + } + + void _zoomAt(double factor, Offset focal) { + final s = (_scale * factor).clamp(0.03, 8.0); + final w = _toWorld(focal); + _scale = s; + _offset = focal - w * s; + _userMoved = true; + _repaint.value++; + } + @override Widget build(BuildContext context) { final colors = context.colors; @@ -281,176 +502,418 @@ class _TreeCanvasState extends State { ), ); } - final extent = _extent; - final half = _half; - return LayoutBuilder( - builder: (context, box) { - if (!_placed) { - _placed = true; - final s = math.min( - 1.0, - math.min(box.maxWidth, box.maxHeight) / (2 * extent), - ); - _transform.value = Matrix4.identity() - ..translateByDouble( - box.maxWidth / 2 - half * s, - box.maxHeight / 2 - half * s, - 0, - 1, - ) - ..scaleByDouble(s, s, 1, 1); - } - return InteractiveViewer( - transformationController: _transform, - constrained: false, - panEnabled: _pan, - minScale: 0.05, - maxScale: 6, - boundaryMargin: const EdgeInsets.all(double.infinity), - 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); + final total = _walk(_root).length; + return Stack( + children: [ + Positioned.fill( + child: LayoutBuilder( + builder: (context, box) { + final size = box.biggest; + if (size != _size) { + _size = size; + if (!_userMoved) _fit(); } - }, - 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, + return MouseRegion( + cursor: _hover != null + ? SystemMouseCursors.click + : MouseCursor.defer, + onHover: (e) { + final k = _hitNode(e.localPosition); + final h = k == null ? _hitLabel(e.localPosition) : _items[k]; + if (h != _hover) { + setState(() => _hover = h); + _repaint.value++; + } + }, + onExit: (_) { + setState(() => _hover = null); + _repaint.value++; + }, + child: Listener( + onPointerSignal: (e) { + if (e is PointerScrollEvent) { + GestureBinding.instance.pointerSignalResolver.register( + e, + (e) { + final s = e as PointerScrollEvent; + _zoomAt( + math.pow(1.0015, -s.scrollDelta.dy).toDouble(), + s.localPosition, + ); + }, + ); + } + }, + child: GestureDetector( + behavior: HitTestBehavior.opaque, + onTapUp: (d) => _onTap(d.localPosition), + onScaleStart: (d) { + _startScale = _scale; + _drag = d.pointerCount == 1 + ? _hitNode(d.localFocalPoint) + : null; + if (_drag != null) { + final w = _toWorld(d.localFocalPoint); + _engine?.pin(_drag!, w.dx, w.dy); + _run(); + } + }, + onScaleUpdate: (d) { + if (_drag != null) { + final w = _toWorld(d.localFocalPoint); + _pos[2 * _drag!] = w.dx; + _pos[2 * _drag! + 1] = w.dy; + _engine?.pin(_drag!, w.dx, w.dy); + _repaint.value++; + return; + } + if (d.scale != 1) { + _zoomAt( + _startScale * d.scale / _scale, + d.localFocalPoint, + ); + } + _offset += d.focalPointDelta; + _userMoved = true; + _repaint.value++; + }, + onScaleEnd: (_) { + if (_drag != null) { + _engine?.unpin(_drag!); + _drag = null; + _run(); + } + }, + child: ClipRect( + child: CustomPaint( + size: size, + painter: _TreePainter( + state: this, + colors: colors, + brightness: Theme.of(context).brightness, + textScaler: MediaQuery.textScalerOf(context), + ), + ), + ), + ), ), - ), - ), + ); + }, ), - ); - }, + ), + Positioned( + left: 16, + bottom: 14, + child: _TreeBar( + shown: _items.length, + total: total, + onExpandAll: () => _setAll(true), + onCollapseAll: () => _setAll(false), + onFit: () { + _userMoved = false; + _fit(); + _repaint.value++; + }, + ), + ), + ], ); } +} - void _release() { - if (_drag == null) return; - _drag = null; - setState(() => _pan = true); +class _TreeBar extends StatelessWidget { + const _TreeBar({ + required this.shown, + required this.total, + required this.onExpandAll, + required this.onCollapseAll, + required this.onFit, + }); + final int shown; + final int total; + final VoidCallback onExpandAll; + final VoidCallback onCollapseAll; + final VoidCallback onFit; + + @override + Widget build(BuildContext context) { + final colors = context.colors; + Widget button(IconData i, String tip, VoidCallback f, String key) => + IconButton( + key: ValueKey(key), + tooltip: tip, + iconSize: 17, + visualDensity: VisualDensity.compact, + color: colors.muted, + onPressed: f, + icon: Icon(i), + ); + return Container( + padding: const EdgeInsets.only(left: 12, right: 4), + decoration: BoxDecoration( + color: colors.paper.withValues(alpha: 0.9), + border: Border.all(color: colors.line), + borderRadius: BorderRadius.circular(10), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Tooltip( + message: + 'Click a branch to expand or collapse it; click a page or a ' + 'name to open it. Drag nodes, scroll to zoom.', + child: Text( + '$shown of $total', + style: TextStyle(fontSize: 12, color: colors.muted), + ), + ), + const SizedBox(width: 4), + button( + Icons.unfold_more_rounded, + 'Expand all', + onExpandAll, + 'tree-expand-all', + ), + button( + Icons.unfold_less_rounded, + 'Collapse all', + onCollapseAll, + 'tree-collapse-all', + ), + button( + Icons.center_focus_strong_outlined, + 'Fit to view', + onFit, + 'tree-fit', + ), + ], + ), + ); } } class _TreePainter extends CustomPainter { - _TreePainter( - this.root, - this.extent, - this.colors, - this.brightness, - Listenable tick, - ) : super(repaint: tick); - final TreeItem root; - final double extent; + _TreePainter({ + required this.state, + required this.colors, + required this.brightness, + required this.textScaler, + }) : super(repaint: state._repaint); + final TreeCanvasState state; final SynapseColors colors; final Brightness brightness; + final TextScaler textScaler; + + /// Laid-out labels per item, invalidated when the text colours change. + static final _cache = Expando<(Color, TextPainter)>(); @override void paint(Canvas canvas, Size size) { - canvas.translate(extent, extent); + final s = state; + final items = s._items; + final pos = s._pos; + if (items.isEmpty || pos.length < 2 * items.length) return; + final scale = s._scale; + Offset screen(int k) => Offset( + pos[2 * k] * scale + s._offset.dx, + pos[2 * k + 1] * scale + s._offset.dy, + ); + final view = (Offset.zero & size).inflate(40); + + // Hover: the item, its path to the centre and its shown children stand out. + final hover = s._hover; + final lit = {}; + if (hover != null) { + for (TreeItem? t = hover; t != null; t = t.parent) { + lit.add(t); + } + if (hover.expanded) lit.addAll(hover.children); + } + final dim = lit.isNotEmpty; + final link = Paint() ..style = PaintingStyle.stroke - ..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 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) - ..quadraticBezierTo(mid.dx, mid.dy, c.pos.dx, c.pos.dy), - link, + ..strokeCap = StrokeCap.round; + for (var k = 1; k < items.length; k++) { + final t = items[k]; + final a = screen(s._index[t.parent!]!), b = screen(k); + if (!view.contains(a) && !view.contains(b)) continue; + final on = lit.contains(t) && lit.contains(t.parent); + link + ..color = treeColor( + t, + brightness, + ).withValues(alpha: dim ? (on ? 0.95 : 0.12) : 0.55) + ..strokeWidth = on ? 2.2 : 1.3; + canvas.drawLine(a, b, link); + } + + s._labelRects.clear(); + final occupied = {}; + final many = items.length > 250; + // Branches first so their names win the label space. + final order = [for (var k = 0; k < items.length; k++) k] + ..sort((a, b) { + int pri(int k) { + final t = items[k]; + return lit.contains(t) ? 0 : (t.children.isEmpty ? 2 : 1); + } + + return pri(a) - pri(b); + }); + final labels = <(int, Offset)>[]; + for (var k = 0; k < items.length; k++) { + final t = items[k]; + final p = screen(k); + if (!view.contains(p)) continue; + final faded = dim && !lit.contains(t); + final color = t.parent == null ? colors.accent : treeColor(t, brightness); + final r = s._radius(t) * scale.clamp(0.6, 1.6); + final fill = Paint() + ..color = color.withValues( + alpha: + (t.global == null && t.parent != null ? 0.6 : 1) * + (faded ? 0.25 : 1), + ); + if (t.isHub) { + _folder(canvas, p, r, fill); + } else { + canvas.drawCircle(p, r, fill); + } + // Collapsed branches: a ring and the number of hidden children. + if (t.children.isNotEmpty && !t.expanded) { + canvas.drawCircle( + p, + r + 3, + Paint() + ..style = PaintingStyle.stroke + ..strokeWidth = 1.4 + ..color = color.withValues(alpha: faded ? 0.25 : 0.8), + ); + final badge = TextPainter( + text: TextSpan( + text: '+${t.children.length}', + style: TextStyle( + fontFamily: uiFont, + fontSize: 9.5, + fontWeight: FontWeight.w700, + color: colors.muted.withValues(alpha: faded ? 0.4 : 1), + ), + ), + textDirection: TextDirection.ltr, + textScaler: textScaler, + )..layout(); + badge.paint(canvas, p + Offset(r + 3, -r - badge.height)); + } + if (t == hover) { + canvas.drawCircle( + p, + r + 6, + Paint() + ..style = PaintingStyle.stroke + ..strokeWidth = 1.5 + ..color = colors.ink.withValues(alpha: 0.5), ); } } - 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); + for (final k in order) { + final t = items[k]; + final p = screen(k); + if (!view.contains(p)) continue; + final branch = t.children.isNotEmpty; + final wanted = + lit.contains(t) || + t.parent == null || + (branch && (scale > 0.35 || !many)) || + (!branch && scale > (many ? 1.1 : 0.55)); + if (wanted) labels.add((k, p)); + } + for (final (k, p) in labels) { + final t = items[k]; + final branch = t.children.isNotEmpty; + final ink = branch || t.parent == null ? colors.ink : colors.muted; + var entry = _cache[t]; + if (entry == null || entry.$1 != ink) { + entry = _cache[t] = ( + ink, + TextPainter( + text: TextSpan( + text: t.label, + style: TextStyle( + fontFamily: uiFont, + fontSize: t.parent == null ? 14 : (branch ? 12.5 : 11.5), + fontWeight: t.parent == null + ? FontWeight.w700 + : (branch ? FontWeight.w600 : FontWeight.w400), + color: ink, + ), + ), + textDirection: TextDirection.ltr, + maxLines: 1, + ellipsis: '…', + textScaler: textScaler, + )..layout(maxWidth: 170), + ); } - 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), - ); + final tp = entry.$2; + final r = s._radius(t) * scale.clamp(0.6, 1.6); + // Labels on the outer side of the node, away from its parent. + final par = t.parent == null ? null : s._index[t.parent!]; + final left = par != null && screen(par).dx > p.dx; + final at = t.parent == null + ? p + Offset(-tp.width / 2, -r - tp.height - 4) + : p + Offset(left ? -tp.width - r - 5 : r + 5, -tp.height / 2); + final rect = at & tp.size; + final cells = []; + for ( + var cx = (rect.left / 30).floor(); + cx <= (rect.right / 30).floor(); + cx++ + ) { + for ( + var cy = (rect.top / 12).floor(); + cy <= (rect.bottom / 12).floor(); + cy++ + ) { + cells.add(cx * 100003 + cy); + } + } + final important = lit.contains(t) || t.parent == null; + if (!important && cells.any(occupied.contains)) continue; + occupied.addAll(cells); + final faded = dim && !lit.contains(t); + if (faded) { + canvas.saveLayer( + rect.inflate(2), + Paint()..color = const Color(0x44000000), + ); + } + if (important && dim) { + canvas.drawRRect( + RRect.fromRectAndRadius(rect.inflate(3), const Radius.circular(4)), + Paint()..color = colors.paper.withValues(alpha: 0.85), + ); + } + tp.paint(canvas, at); + if (faded) canvas.restore(); + s._labelRects.add((rect, t)); } - - 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) { + /// Small folder glyph (body plus tab) centred on `c`, about `r` in radius. + void _folder(Canvas canvas, Offset c, double r, Paint paint) { + final w = r * 2.4, h = r * 1.7; canvas.drawRRect( RRect.fromRectAndRadius( - Rect.fromCenter(center: c.translate(0, 1), width: 13, height: 9), - const Radius.circular(2), + Rect.fromCenter(center: c.translate(0, r * 0.15), width: w, height: h), + Radius.circular(r * 0.35), ), paint, ); canvas.drawRRect( RRect.fromRectAndRadius( - Rect.fromLTWH(c.dx - 6.5, c.dy - 5, 6, 3), - const Radius.circular(1.2), + Rect.fromLTWH(c.dx - w / 2, c.dy - h / 2 - r * 0.45, w * 0.45, r * 0.6), + Radius.circular(r * 0.2), ), paint, ); @@ -458,7 +921,7 @@ class _TreePainter extends CustomPainter { @override bool shouldRepaint(_TreePainter old) => - !identical(old.root, root) || old.colors != colors || - old.brightness != brightness; + old.brightness != brightness || + !identical(old.state, state); } diff --git a/app/test/graph_view_test.dart b/app/test/graph_view_test.dart index 75ba43f..1a41624 100644 --- a/app/test/graph_view_test.dart +++ b/app/test/graph_view_test.dart @@ -362,6 +362,59 @@ void main() { expect(find.text('Group: hubs'), findsOneWidget); }); }); + + group('interactive tree', () { + // One hub with 200 pages: far more than the tree used to show ("… N more"). + GraphData bigHub() { + GraphNode n(int i, {bool hub = false}) => GraphNode( + id: '$i', + title: hub ? 'Library' : 'Page $i', + createdAt: 0, + degree: 1, + backlinks: 0, + cluster: 0, + isHub: hub, + homeHub: 0, + tags: const [], + ); + const count = 200; + return GraphData( + nodes: [n(0, hub: true), for (var i = 1; i <= count; i++) n(i)], + sources: Uint32List.fromList([for (var i = 1; i <= count; i++) 0]), + targets: Uint32List.fromList([for (var i = 1; i <= count; i++) i]), + kinds: Uint8List.fromList([for (var i = 1; i <= count; i++) 7]), + weights: Float32List.fromList([for (var i = 1; i <= count; i++) 1]), + seq: 1, + ); + } + + test('nothing is capped; big branches start collapsed', () { + 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); + }); + + testWidgets('branches expand and collapse in the canvas', (tester) async { + await pumpGraph(tester, _HubBackend(bigHub())); + await mode(tester, 'Tree'); + final state = tester.state(find.byType(TreeCanvas)); + expect(state.visibleCount, 2); + expect(find.text('2 of 202'), findsOneWidget); + state.toggle(state.root.children.single); + await settle(tester); + expect(state.visibleCount, 202); + await tester.tap(find.byKey(const ValueKey('tree-collapse-all'))); + await settle(tester); + expect(state.visibleCount, 2); + await tester.tap(find.byKey(const ValueKey('tree-expand-all'))); + await settle(tester); + expect(find.text('202 of 202'), findsOneWidget); + }); + }); } /// A memory backend whose graph data is fixed (so tests don't depend on its demo graph).