feat(graph): graph view with network, local, synapse, cluster and namespace modes

- synapse-ffi: graph_data() returns the whole page-level graph (links, tags,
  property refs, block refs/embeds per page, unlinked mentions, decayed
  synapses) as parallel arrays with degree, backlinks, Louvain clusters and
  primary tags; cached by op seq, synapse state and hour.
- synapse-ffi: ForceLayout, a Barnes-Hut force layout stepped from Dart on a
  Rust worker thread (pin/unpin for dragging, reheat).
- app: Graph view with a mode selector (Network, Local, Synapses, Clusters,
  Namespaces, Timeline), filters (title, tag, date range, min links,
  orphans, journals, mentions), pan/zoom, node drag, hover highlighting,
  activation pulse, cluster hulls, radial namespace/tag tree, and a local
  graph panel on every page. Edges render as one vertex mesh, nodes in
  colour/size batches, culled to the viewport.
- Tests: Rust extraction/mentions/cache/clusters/layout; widget tests for
  mode switching, filters and layout restarts; a real-app integration
  smoke test with frame timings.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
dasemuandClaude Opus 5.5 committed 2026-10-21 15:39:07 +02:00
1 parent 6a4a76670b
commit e43452f5af
29 files changed
+6177 -76

No files matched your search

+281
View File
@@ -0,0 +1,281 @@
import 'dart:collection';
import 'dart:typed_data';
import '../backend/graph_backend.dart';
/// Edge kinds, matching `synapse_ffi::api::dto::edge_kind`.
enum EdgeKind {
link('Link'),
tag('Tag'),
property('Property'),
blockRef('Block ref'),
embed('Embed'),
mention('Mention'),
synapse('Synapse');
const EdgeKind(this.label);
final String label;
bool get structural => this != EdgeKind.mention && this != EdgeKind.synapse;
}
/// The page-level graph with adjacency, built once per [GraphData].
class GraphModel {
GraphModel(this.data)
: _kinds = [for (final k in data.kinds) EdgeKind.values[k]] {
final n = data.nodes.length;
adjacency = List.generate(n, (_) => <int>[]);
for (var e = 0; e < edgeCount; e++) {
adjacency[data.sources[e]].add(e);
adjacency[data.targets[e]].add(e);
}
for (var i = 0; i < n; i++) {
_byId[data.nodes[i].id] = i;
}
}
final GraphData data;
final List<EdgeKind> _kinds;
late final List<List<int>> adjacency;
final _byId = <String, int>{};
int get nodeCount => data.nodes.length;
int get edgeCount => data.kinds.length;
GraphNode node(int i) => data.nodes[i];
EdgeKind kind(int e) => _kinds[e];
int source(int e) => data.sources[e];
int target(int e) => data.targets[e];
double weight(int e) => data.weights[e];
int? indexOf(String id) => _byId[id];
int other(int e, int i) => source(e) == i ? target(e) : source(e);
bool isJournal(int i) => node(i).journalDate != null;
/// Tag pages actually used as tags, most used first.
late final List<int> tags = () {
final count = <int, int>{};
for (var e = 0; e < edgeCount; e++) {
if (kind(e) == EdgeKind.tag) {
count[target(e)] = (count[target(e)] ?? 0) + 1;
}
}
final l = count.keys.toList()
..sort((a, b) => count[b]!.compareTo(count[a]!));
return l;
}();
/// Hop distance from `seed` over edges of `kinds`, up to `depth`.
Map<int, int> neighbourhood(int seed, int depth, Set<EdgeKind> kinds) {
final dist = <int, int>{seed: 0};
final q = Queue<int>()..add(seed);
while (q.isNotEmpty) {
final i = q.removeFirst();
final d = dist[i]!;
if (d >= depth) continue;
for (final e in adjacency[i]) {
if (!kinds.contains(kind(e))) continue;
final j = other(e, i);
if (!dist.containsKey(j)) {
dist[j] = d + 1;
q.add(j);
}
}
}
return dist;
}
/// The induced subgraph on `nodes` (global indices) with edges of `kinds`. Parallel
/// edges between the same pair are merged for the layout but kept for drawing.
///
/// `springs` adds layout-only attractions (global pairs and strengths) that are not drawn.
SubGraph subgraph(
List<int> nodes,
Set<EdgeKind> kinds, {
List<(int, int, double)> springs = const [],
}) {
final local = <int, int>{};
for (var k = 0; k < nodes.length; k++) {
local[nodes[k]] = k;
}
final edges = <int>[];
for (final i in nodes) {
for (final e in adjacency[i]) {
if (source(e) != i) continue; // visit each edge once, from its source
if (!kinds.contains(kind(e))) continue;
if (local.containsKey(target(e))) edges.add(e);
}
}
return SubGraph(this, nodes, local, edges, springs: springs);
}
}
/// Filters of the network modes.
class GraphFilter {
const GraphFilter({
this.journals = false,
this.orphans = true,
this.minDegree = 0,
this.tag,
this.query = '',
this.from,
this.to,
this.kinds = const {
EdgeKind.link,
EdgeKind.tag,
EdgeKind.property,
EdgeKind.blockRef,
EdgeKind.embed,
EdgeKind.mention,
},
});
final bool journals;
final bool orphans;
final int minDegree;
/// Only pages tagged with this tag page (and the tag itself).
final int? tag;
/// Title substring.
final String query;
/// Created-at range (inclusive days, `YYYY-MM-DD`).
final String? from;
final String? to;
final Set<EdgeKind> kinds;
GraphFilter copyWith({
bool? journals,
bool? orphans,
int? minDegree,
int? Function()? tag,
String? query,
String? Function()? from,
String? Function()? to,
Set<EdgeKind>? kinds,
}) => GraphFilter(
journals: journals ?? this.journals,
orphans: orphans ?? this.orphans,
minDegree: minDegree ?? this.minDegree,
tag: tag == null ? this.tag : tag(),
query: query ?? this.query,
from: from == null ? this.from : from(),
to: to == null ? this.to : to(),
kinds: kinds ?? this.kinds,
);
List<int> apply(GraphModel g) {
final q = query.trim().toLowerCase();
final tagged = tag == null
? null
: {
tag!,
for (final e in g.adjacency[tag!])
if (g.kind(e) == EdgeKind.tag && g.target(e) == tag) g.source(e),
};
String day(int i) {
final ms = g.node(i).createdAt.toInt();
final d = DateTime.fromMillisecondsSinceEpoch(ms);
return '${d.year.toString().padLeft(4, '0')}-${d.month.toString().padLeft(2, '0')}'
'-${d.day.toString().padLeft(2, '0')}';
}
final base = <int>[
for (var i = 0; i < g.nodeCount; i++)
if ((journals || !g.isJournal(i)) &&
(tagged == null || tagged.contains(i)) &&
(q.isEmpty || g.node(i).title.toLowerCase().contains(q)) &&
(from == null || day(i).compareTo(from!) >= 0) &&
(to == null || day(i).compareTo(to!) <= 0))
i,
];
if (orphans && minDegree == 0) return base;
// Degree counts only neighbours that are themselves shown, over the visible kinds.
final shown = base.toSet();
int degree(int i) {
final seen = <int>{};
for (final e in g.adjacency[i]) {
if (!kinds.contains(g.kind(e))) continue;
final j = g.other(e, i);
if (shown.contains(j)) seen.add(j);
}
return seen.length;
}
return [
for (final i in base)
if (() {
final d = degree(i);
return d >= minDegree && (orphans || d > 0);
}())
i,
];
}
}
/// A view-sized piece of the graph: global node indices, a global→local map and the global
/// ids of the edges between them.
class SubGraph {
SubGraph(
this.model,
this.nodes,
this.local,
this.edges, {
this.springs = const [],
});
final GraphModel model;
final List<int> nodes;
final Map<int, int> local;
final List<int> edges;
/// Layout-only attractions between global node pairs.
final List<(int, int, double)> springs;
int get length => nodes.length;
/// Edge endpoints in local indices, deduplicated per pair, with summed weights (for the
/// layout). Synapse weights are scaled so strong synapses pull harder.
(Uint32List, Uint32List, Float32List) layoutEdges() {
final pairs = <int, double>{};
for (final e in edges) {
final a = local[model.source(e)]!;
final b = local[model.target(e)]!;
final key = a < b ? a * length + b : b * length + a;
final w = model.kind(e) == EdgeKind.synapse
? model.weight(e)
: model.kind(e) == EdgeKind.mention
? 0.3
: 1.0;
pairs[key] = (pairs[key] ?? 0) + w;
}
for (final (ga, gb, w) in springs) {
final a = local[ga], b = local[gb];
if (a == null || b == null || a == b) continue;
final key = a < b ? a * length + b : b * length + a;
pairs[key] = (pairs[key] ?? 0) + w;
}
final s = Uint32List(pairs.length);
final t = Uint32List(pairs.length);
final w = Float32List(pairs.length);
var k = 0;
pairs.forEach((key, weight) {
s[k] = key ~/ length;
t[k] = key % length;
w[k] = weight;
k++;
});
return (s, t, w);
}
}
/// Runs a force layout; implemented over the Rust `ForceLayout` (and by a fake in tests).
abstract class LayoutEngine {
/// Runs up to `iterations` ticks: positions `x0, y0, ...` and the remaining alpha (0 when
/// settled).
Future<(Float32List, double)> step(int iterations);
Future<void> pin(int index, double x, double y);
Future<void> unpin(int index);
Future<void> reheat(double alpha);
void dispose();
}
+962
View File
@@ -0,0 +1,962 @@
import 'dart:math' as math;
import 'dart:typed_data';
import 'dart:ui' as ui;
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';
enum ColorBy { cluster, tag, none }
/// Calm categorical palette (cluster / tag colours), tuned for each theme.
List<Color> graphPalette(Brightness b) => b == Brightness.light
? const [
Color(0xFF1F7A74),
Color(0xFFB0741E),
Color(0xFF5B6BB5),
Color(0xFFA2536B), //
Color(0xFF5E8F4A),
Color(0xFF7A5BA6),
Color(0xFF2F86A8),
Color(0xFFB35A3C),
Color(0xFF8A8A3A), Color(0xFF4F7A8F),
]
: const [
Color(0xFF63C2B8),
Color(0xFFD9A55A),
Color(0xFF8E9BE0),
Color(0xFFD9839B), //
Color(0xFF93C27E),
Color(0xFFAE90D6),
Color(0xFF6FB8D6),
Color(0xFFE08D6E),
Color(0xFFC4C46E), Color(0xFF86AFC4),
];
/// Remembers node positions by page id across views, so switching modes or filters keeps
/// the picture stable.
class PositionCache {
final _pos = <String, Offset>{};
Offset? operator [](String id) => _pos[id];
void operator []=(String id, Offset p) => _pos[id] = p;
}
/// Extra per-node data for the synapse (brain) mode.
class BrainOverlay {
const BrainOverlay({
required this.focus,
required this.activation,
required this.hops,
});
/// Global index of the focused node.
final int focus;
/// Global index → activation 0..1.
final Map<int, double> activation;
/// Global index → hop distance from the focus (drives the pulse).
final Map<int, int> hops;
}
/// A force-directed drawing of a [SubGraph]: Rust lays it out off the UI thread, this widget
/// paints culled batches (one draw call per edge kind and node colour/size bucket), and
/// handles pan/zoom, node drag, hover highlighting and taps.
class NetworkCanvas extends StatefulWidget {
const NetworkCanvas({
super.key,
required this.sub,
required this.onTap,
this.colorBy = ColorBy.cluster,
this.hulls = false,
this.focus,
this.brain,
this.cache,
this.compact = false,
});
final SubGraph sub;
final void Function(int global) onTap;
final ColorBy colorBy;
final bool hulls;
/// Highlighted node (local graph, brain).
final int? focus;
final BrainOverlay? brain;
final PositionCache? cache;
/// Side-panel use: fewer labels, no legend.
final bool compact;
@override
State<NetworkCanvas> createState() => NetworkCanvasState();
}
class NetworkCanvasState extends State<NetworkCanvas>
with SingleTickerProviderStateMixin {
LayoutEngine? _engine;
Float32List _pos = Float32List(0);
double _alpha = 1;
/// Generation whose layout loop is running, if any.
int? _loopGen;
int _generation = 0;
final _repaint = ValueNotifier<int>(0);
// Camera: screen = world * scale + offset.
double _scale = 1;
Offset _offset = Offset.zero;
bool _userMoved = false;
Size _size = Size.zero;
int? _hover;
int? _drag;
// Reused point buffers (no per-frame allocation or boxing).
final _edgeBufs = <EdgeKind, _Buf>{};
final _nodeBufs = <(int, int), _Buf>{};
Float32List _meshPos = Float32List(0);
Int32List _meshCol = Int32List(0);
double _startScale = 1;
late final AnimationController _pulse = AnimationController(
vsync: this,
duration: const Duration(milliseconds: 1800),
)..addListener(() => _repaint.value++);
// Per-node style, rebuilt with the subgraph.
late Float32List _radius;
late List<int> _colorIndex;
late List<List<int>> _localAdj;
@visibleForTesting
int get nodeCount => widget.sub.length;
/// Whether the layout has cooled down.
bool get settled => _alpha == 0;
@override
void initState() {
super.initState();
_rebuild();
}
@override
void didUpdateWidget(NetworkCanvas oldWidget) {
final old = oldWidget;
super.didUpdateWidget(old);
if (!identical(old.sub, widget.sub)) {
_saveCache(old.sub);
_rebuild();
} else if (old.colorBy != widget.colorBy) {
_styles();
}
if (widget.brain != null && old.brain?.focus != widget.brain!.focus) {
_pulse.forward(from: 0);
}
}
@override
void dispose() {
_saveCache(widget.sub);
_generation++;
_engine?.dispose();
_pulse.dispose();
_repaint.dispose();
super.dispose();
}
/// Stores the current positions, which belong to `sub` (the subgraph being replaced).
void _saveCache(SubGraph sub) {
final c = widget.cache;
if (c == null || _pos.length != 2 * sub.length) return;
for (var k = 0; k < sub.length && 2 * k + 1 < _pos.length; k++) {
c[sub.model.node(sub.nodes[k]).id] = Offset(_pos[2 * k], _pos[2 * k + 1]);
}
}
void _styles() {
final sub = widget.sub;
final g = sub.model;
_radius = Float32List(sub.length);
_colorIndex = List.filled(sub.length, -1);
for (var k = 0; k < sub.length; k++) {
final n = g.node(sub.nodes[k]);
_radius[k] = (3.0 + math.sqrt(n.degree + n.backlinks) * 1.7).clamp(
3.0,
22.0,
);
_colorIndex[k] = switch (widget.colorBy) {
ColorBy.cluster => n.cluster < 10 ? n.cluster : -1,
ColorBy.tag =>
n.primaryTag == null
? -1
: (() {
final i = g.tags.indexOf(n.primaryTag!);
return i < 10 ? i : -1;
})(),
ColorBy.none => -1,
};
}
}
void _rebuild() {
_engine?.dispose();
_generation++;
final sub = widget.sub;
_styles();
_localAdj = List.generate(sub.length, (_) => <int>[]);
for (final e in sub.edges) {
final a = sub.local[sub.model.source(e)]!;
final b = sub.local[sub.model.target(e)]!;
_localAdj[a].add(b);
_localAdj[b].add(a);
}
final cache = widget.cache;
Float32List? initial;
if (cache != null) {
var hits = 0;
final p = Float32List(2 * sub.length);
for (var k = 0; k < sub.length; k++) {
final c = cache[sub.model.node(sub.nodes[k]).id];
if (c != null) {
hits++;
p[2 * k] = c.dx;
p[2 * k + 1] = c.dy;
} else {
// New nodes start near a known neighbour, or spread around the origin.
final nb = _localAdj[k].map(
(j) => cache[sub.model.node(sub.nodes[j]).id],
);
final anchor = nb.firstWhere((o) => o != null, orElse: () => null);
final a = k * 2.399963;
final r = anchor == null ? 30.0 * math.sqrt(k + 1) : 18.0;
p[2 * k] = (anchor?.dx ?? 0) + r * math.cos(a);
p[2 * k + 1] = (anchor?.dy ?? 0) + r * math.sin(a);
}
}
if (hits > sub.length / 3) initial = p;
}
final (s, t, w) = sub.layoutEdges();
final backend = AppScope.read(context).backend;
_engine = backend.createLayout(sub.length, s, t, w, initial: initial);
_pos = initial ?? Float32List(2 * sub.length);
_alpha = 1;
_hover = null;
_drag = null;
_run();
if (widget.brain != null) _pulse.forward(from: 0);
}
Future<void> _run() async {
if (_loopGen == _generation) return;
_loopGen = _generation;
final gen = _generation;
final engine = _engine!;
final n = widget.sub.length;
// Keep each batch around a frame's worth of work.
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('layout stopped: $e');
} finally {
if (_loopGen == gen) _loopGen = null;
}
}
/// Fits the camera to the nodes (eased while the layout settles).
void _fit({bool animate = false}) {
if (_size.isEmpty || _pos.isEmpty) return;
// Robust bounds: a few far-flung orphans should not shrink the main body to a dot.
final xs = <double>[], ys = <double>[];
// Sample large graphs: bounds need percentiles, not every point.
final stride = 2 * math.max(1, _pos.length ~/ 3000).toInt();
for (var k = 0; k + 1 < _pos.length; k += stride) {
if (_pos[k].isFinite && _pos[k + 1].isFinite) {
xs.add(_pos[k]);
ys.add(_pos[k + 1]);
}
}
if (xs.isEmpty) return;
xs.sort();
ys.sort();
final cut = xs.length > 40 ? (xs.length * 0.03).floor() : 0;
final x0 = xs[cut], x1 = xs[xs.length - 1 - cut];
final y0 = ys[cut], y1 = ys[ys.length - 1 - cut];
final pad = widget.compact ? 16.0 : (widget.sub.length < 60 ? 110.0 : 60.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.6);
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;
int? _hit(Offset screen) {
final p = _toWorld(screen);
int? best;
var bestD = double.infinity;
for (var k = 0; k < widget.sub.length && 2 * k + 1 < _pos.length; k++) {
final dx = _pos[2 * k] - p.dx, dy = _pos[2 * k + 1] - p.dy;
final d = dx * dx + dy * dy;
final r = _radius[k] + 4 / _scale;
if (d <= r * r && d < bestD) {
bestD = d;
best = k;
}
}
return best;
}
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++;
}
/// Re-fits and lets the camera follow the layout again.
void recenter() {
_userMoved = false;
_fit();
_repaint.value++;
}
@override
Widget build(BuildContext context) {
final colors = context.colors;
final palette = graphPalette(Theme.of(context).brightness);
return LayoutBuilder(
builder: (context, box) {
final size = box.biggest;
if (size != _size) {
_size = size;
if (!_userMoved) _fit();
}
return MouseRegion(
cursor: _hover != null ? SystemMouseCursors.click : MouseCursor.defer,
onHover: (e) {
final h = _hit(e.localPosition);
if (h != _hover) setState(() => _hover = h);
},
onExit: (_) => setState(() => _hover = null),
child: Listener(
onPointerSignal: (e) {
if (e is PointerScrollEvent) {
// Claim the wheel so an enclosing scroll view does not scroll too.
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) {
final h = _hit(d.localPosition);
if (h != null) widget.onTap(widget.sub.nodes[h]);
},
onScaleStart: (d) {
_startScale = _scale;
_drag = d.pointerCount == 1 ? _hit(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: _NetworkPainter(
state: this,
colors: colors,
palette: palette,
textScaler: MediaQuery.textScalerOf(context),
),
),
),
),
),
);
},
);
}
}
class _NetworkPainter extends CustomPainter {
_NetworkPainter({
required this.state,
required this.colors,
required this.palette,
required this.textScaler,
}) : super(repaint: state._repaint);
final NetworkCanvasState state;
final SynapseColors colors;
final List<Color> palette;
final TextScaler textScaler;
/// Laid-out labels per subgraph, invalidated when the text colour changes.
static final _labels = Expando<(Color, Map<int, TextPainter>)>();
Color _edgeColor(EdgeKind k) => switch (k) {
EdgeKind.link => colors.muted,
EdgeKind.tag => colors.accent,
EdgeKind.property => palette[2],
EdgeKind.blockRef => colors.ref,
EdgeKind.embed => colors.ref,
EdgeKind.mention => colors.faint,
EdgeKind.synapse => palette[3],
};
@override
void paint(Canvas canvas, Size size) {
final s = state;
final sub = s.widget.sub;
final g = sub.model;
final pos = s._pos;
if (pos.length < 2 * sub.length || sub.length == 0) return;
final scale = s._scale;
final brain = s.widget.brain;
final hover = s._hover;
final focusLocal = s.widget.focus == null
? null
: sub.local[s.widget.focus!];
final highlight = <int>{
if (hover != null) ...[hover, ...s._localAdj[hover]],
};
final dim = hover != null;
// Visible world rect.
final view = Rect.fromLTWH(
-s._offset.dx / scale,
-s._offset.dy / scale,
size.width / scale,
size.height / scale,
).inflate(30 / scale);
bool visible(int k) => view.contains(Offset(pos[2 * k], pos[2 * k + 1]));
canvas.save();
canvas.translate(s._offset.dx, s._offset.dy);
canvas.scale(scale);
// Cluster hulls.
if (s.widget.hulls) _hulls(canvas, sub, pos, scale);
// Edges, batched by kind.
final pulse = s._pulse.value;
final maxHop = brain == null ? 0 : brain.hops.values.fold(0, math.max);
final front = pulse * (maxHop + 1);
final batches = s._edgeBufs;
for (final b in batches.values) {
b.n = 0;
}
final strong = <(int, int, EdgeKind, double)>[];
for (final e in sub.edges) {
final a = sub.local[g.source(e)]!, b = sub.local[g.target(e)]!;
final ax = pos[2 * a],
ay = pos[2 * a + 1],
bx = pos[2 * b],
by = pos[2 * b + 1];
if (math.max(ax, bx) < view.left ||
math.min(ax, bx) > view.right ||
math.max(ay, by) < view.top ||
math.min(ay, by) > view.bottom) {
continue;
}
final k = g.kind(e);
if (brain != null ||
(dim &&
highlight.contains(a) &&
highlight.contains(b) &&
(a == hover || b == hover))) {
strong.add((a, b, k, g.weight(e)));
continue;
}
final list = batches.putIfAbsent(k, _Buf.new);
if (k == EdgeKind.mention) {
_dashes(list, ax, ay, bx, by, 5 / scale);
} else {
list.add4(ax, ay, bx, by);
}
}
_edgeMesh(canvas, batches, scale, dim);
for (final (a, b, k, w) in strong) {
final p = Offset(pos[2 * a], pos[2 * a + 1]),
q = Offset(pos[2 * b], pos[2 * b + 1]);
if (brain != null) {
final aa = brain.activation[sub.nodes[a]] ?? 0,
ab = brain.activation[sub.nodes[b]] ?? 0;
final act = math.max(aa, ab);
final width =
(k == EdgeKind.synapse ? 1 + w.clamp(0, 10) * 0.6 : 1.0) / scale;
canvas.drawLine(
p,
q,
Paint()
..color = (k == EdgeKind.synapse ? palette[3] : colors.faint)
.withValues(alpha: 0.15 + 0.6 * act)
..strokeWidth = width
..strokeCap = StrokeCap.round,
);
// Pulse travelling outward along edges from hop h to h + 1.
final ha = brain.hops[sub.nodes[a]], hb = brain.hops[sub.nodes[b]];
if (ha != null && hb != null && ha != hb && pulse > 0 && pulse < 1) {
final (from, to, h) = ha < hb ? (p, q, ha) : (q, p, hb);
final t = (front - h).clamp(0.0, 1.0);
if (t > 0 && t < 1) {
canvas.drawLine(
from,
Offset.lerp(from, to, t)!,
Paint()
..color = colors.accent.withValues(alpha: 0.9)
..strokeWidth = width + 1.5 / scale
..strokeCap = StrokeCap.round,
);
}
}
} else {
canvas.drawLine(
p,
q,
Paint()
..color = _edgeColor(k).withValues(alpha: 0.9)
..strokeWidth = 1.6 / scale,
);
}
}
// Nodes, batched by colour and radius (one drawRawPoints per bucket).
final buckets = s._nodeBufs;
for (final b in buckets.values) {
b.n = 0;
}
final journalColor = colors.faint;
for (var k = 0; k < sub.length; k++) {
if (!visible(k)) continue;
final r = brain == null
? s._radius[k]
: 3 + 9 * (brain.activation[sub.nodes[k]] ?? 0);
final ci = g.isJournal(sub.nodes[k]) ? -2 : s._colorIndex[k];
final key = (ci, (r * 2).round());
buckets.putIfAbsent(key, _Buf.new).add2(pos[2 * k], pos[2 * k + 1]);
}
for (final MapEntry(key: (ci, d2), value: pts) in buckets.entries) {
if (pts.n == 0) continue;
var c = ci == -2 ? journalColor : (ci < 0 ? colors.muted : palette[ci]);
if (dim) c = c.withValues(alpha: 0.25);
if (brain != null) c = colors.faint;
canvas.drawRawPoints(
ui.PointMode.points,
pts.view,
Paint()
..color = c
..strokeWidth = d2.toDouble()
..strokeCap = StrokeCap.round,
);
}
// Activation glow (brain), highlighted and focused nodes on top.
if (brain != null) {
for (var k = 0; k < sub.length; k++) {
final act = brain.activation[sub.nodes[k]] ?? 0;
final c = Offset(pos[2 * k], pos[2 * k + 1]);
final r = 3 + 9 * act;
canvas.drawCircle(
c,
r,
Paint()
..color = Color.lerp(colors.faint, colors.accent, act.clamp(0, 1))!,
);
final h = brain.hops[sub.nodes[k]];
if (h != null && pulse > 0 && pulse < 1) {
final d = (front - h).abs();
if (d < 0.6) {
canvas.drawCircle(
c,
r + (6 + 10 * (0.6 - d)) / scale,
Paint()
..style = PaintingStyle.stroke
..strokeWidth = 2 / scale
..color = colors.accent.withValues(alpha: (0.6 - d) / 0.6),
);
}
}
}
}
for (final k in highlight) {
final ci = s._colorIndex[k];
canvas.drawCircle(
Offset(pos[2 * k], pos[2 * k + 1]),
s._radius[k],
Paint()..color = ci < 0 ? colors.ink : palette[ci],
);
}
if (focusLocal != null) {
canvas.drawCircle(
Offset(pos[2 * focusLocal], pos[2 * focusLocal + 1]),
(brain == null ? s._radius[focusLocal] : 12) + 4 / scale,
Paint()
..style = PaintingStyle.stroke
..strokeWidth = 2 / scale
..color = colors.accent,
);
}
canvas.restore();
_paintLabels(canvas, size, sub, pos, highlight, focusLocal);
}
/// All plain edges as one triangle mesh with per-vertex colours: a single draw call
/// and no per-frame stroke tessellation (which dominates raster time with 10k+ lines).
void _edgeMesh(
Canvas canvas,
Map<EdgeKind, _Buf> batches,
double scale,
bool dim,
) {
var segs = 0;
for (final b in batches.values) {
segs += b.n ~/ 4;
}
if (segs == 0) return;
final s = state;
if (s._meshPos.length < segs * 12) {
s._meshPos = Float32List(segs * 24);
s._meshCol = Int32List(segs * 12);
}
final pos = s._meshPos, col = s._meshCol;
var p = 0, c = 0;
// Dense graphs fade edges so structure shows instead of a solid hairball.
final density = math.sqrt(math.min(1.0, 2500 / segs));
for (final MapEntry(key: k, value: b) in batches.entries) {
if (b.n == 0) continue;
final color = _edgeColor(k)
.withValues(
alpha: (dim ? 0.12 : (k == EdgeKind.link ? 0.4 : 0.55)) * density,
)
.toARGB32()
.toSigned(32);
final half = (k == EdgeKind.tag ? 1.3 : 1.1) / scale / 2;
final d = b.data;
for (var i = 0; i + 3 < b.n; i += 4) {
final ax = d[i], ay = d[i + 1], bx = d[i + 2], by = d[i + 3];
final dx = bx - ax, dy = by - ay;
final len = math.sqrt(dx * dx + dy * dy);
if (len == 0) continue;
final nx = -dy / len * half, ny = dx / len * half;
pos[p++] = ax + nx;
pos[p++] = ay + ny;
pos[p++] = ax - nx;
pos[p++] = ay - ny;
pos[p++] = bx + nx;
pos[p++] = by + ny;
pos[p++] = bx + nx;
pos[p++] = by + ny;
pos[p++] = ax - nx;
pos[p++] = ay - ny;
pos[p++] = bx - nx;
pos[p++] = by - ny;
for (var v = 0; v < 6; v++) {
col[c++] = color;
}
}
}
canvas.drawVertices(
ui.Vertices.raw(
ui.VertexMode.triangles,
Float32List.sublistView(pos, 0, p),
colors: Int32List.sublistView(col, 0, c),
),
BlendMode.dst,
Paint(),
);
}
void _dashes(
_Buf out,
double ax,
double ay,
double bx,
double by,
double dash,
) {
final dx = bx - ax, dy = by - ay;
final len = math.sqrt(dx * dx + dy * dy);
if (len == 0) return;
final n = math.min(40, (len / (2 * dash)).floor());
if (n <= 1) {
out.add4(ax, ay, bx, by);
return;
}
final step = 1 / n;
for (var i = 0; i < n; i++) {
final t0 = i * step, t1 = t0 + step / 2;
out.add4(ax + dx * t0, ay + dy * t0, ax + dx * t1, ay + dy * t1);
}
}
void _hulls(Canvas canvas, SubGraph sub, Float32List pos, double scale) {
final byCluster = <int, List<Offset>>{};
for (var k = 0; k < sub.length; k++) {
final c = sub.model.node(sub.nodes[k]).cluster;
if (c >= 10) continue;
byCluster
.putIfAbsent(c, () => [])
.add(Offset(pos[2 * k], pos[2 * k + 1]));
}
for (final MapEntry(key: c, value: pts) in byCluster.entries) {
if (pts.length < 3) continue;
final hull = convexHull(corePoints(pts));
if (hull.length < 3) continue;
final path = Path()..addPolygon(hull, true);
final color = palette[c];
canvas.drawPath(
path,
Paint()
..color = color.withValues(alpha: 0.08)
..style = PaintingStyle.fill,
);
canvas.drawPath(
path,
Paint()
..color = color.withValues(alpha: 0.25)
..style = PaintingStyle.stroke
..strokeWidth = 28 / scale
..strokeJoin = StrokeJoin.round,
);
}
}
void _paintLabels(
Canvas canvas,
Size size,
SubGraph sub,
Float32List pos,
Set<int> highlight,
int? focus,
) {
final s = state;
final scale = s._scale;
final compact = s.widget.compact;
var entry = _labels[sub];
if (entry == null || entry.$1 != colors.ink) {
entry = _labels[sub] = (colors.ink, <int, TextPainter>{});
}
final cache = entry.$2;
// Candidates: big enough on screen, or highlighted; biggest first.
final candidates = <int>[];
for (var k = 0; k < sub.length; k++) {
final sx = pos[2 * k] * scale + s._offset.dx;
final sy = pos[2 * k + 1] * scale + s._offset.dy;
if (sx < -50 ||
sy < -20 ||
sx > size.width + 50 ||
sy > size.height + 20) {
continue;
}
final screenR = s._radius[k] * scale;
final brainAct = s.widget.brain?.activation[sub.nodes[k]];
if (highlight.contains(k) ||
k == focus ||
(brainAct != null && brainAct > 0.15) ||
screenR >= (compact ? 7 : (sub.length > 200 ? 8.5 : 5.5)) ||
(sub.length <= 40 && !compact)) {
candidates.add(k);
}
}
candidates.sort((a, b) {
int pri(int k) => highlight.contains(k) || k == focus ? 1 : 0;
final p = pri(b) - pri(a);
return p != 0 ? p : s._radius[b].compareTo(s._radius[a]);
});
final occupied = <int>{};
var drawn = 0;
final maxLabels = compact ? 14 : (sub.length > 200 ? 70 : 180);
for (final k in candidates) {
if (drawn >= maxLabels) break;
final tp = cache[k] ??= TextPainter(
text: TextSpan(
text: sub.model.node(sub.nodes[k]).title,
style: TextStyle(
fontFamily: uiFont,
fontSize: compact ? 10.5 : 11.5,
color: colors.ink,
),
),
textDirection: TextDirection.ltr,
maxLines: 1,
ellipsis: '…',
textScaler: textScaler,
)..layout(maxWidth: 160);
final sx = pos[2 * k] * scale + s._offset.dx;
final sy =
pos[2 * k + 1] * scale + s._offset.dy + s._radius[k] * scale + 3;
final rect = Rect.fromLTWH(sx - tp.width / 2, sy, tp.width, tp.height);
// Coarse occupancy grid avoids overlapping labels.
final cells = <int>[];
for (
var cx = (rect.left / 40).floor();
cx <= (rect.right / 40).floor();
cx++
) {
for (
var cy = (rect.top / 14).floor();
cy <= (rect.bottom / 14).floor();
cy++
) {
cells.add(cx * 100003 + cy);
}
}
final important = highlight.contains(k) || k == focus;
if (!important && cells.any(occupied.contains)) continue;
occupied.addAll(cells);
final dimmed = highlight.isNotEmpty && !highlight.contains(k);
if (dimmed) {
canvas.saveLayer(
rect.inflate(2),
Paint()..color = const Color(0x55000000),
);
}
canvas.drawRRect(
RRect.fromRectAndRadius(rect.inflate(2), const Radius.circular(3)),
Paint()..color = colors.paper.withValues(alpha: 0.75),
);
tp.paint(canvas, rect.topLeft);
if (dimmed) canvas.restore();
drawn++;
}
}
@override
bool shouldRepaint(_NetworkPainter old) =>
old.colors != colors || !identical(old.state, state);
}
/// Growable float buffer reused across frames.
class _Buf {
Float32List data = Float32List(256);
int n = 0;
void _grow(int extra) {
if (n + extra <= data.length) return;
final next = Float32List(math.max(data.length * 2, n + extra));
next.setRange(0, n, data);
data = next;
}
void add2(double a, double b) {
_grow(2);
data[n++] = a;
data[n++] = b;
}
void add4(double a, double b, double c, double d) {
_grow(4);
data[n++] = a;
data[n++] = b;
data[n++] = c;
data[n++] = d;
}
Float32List get view => Float32List.sublistView(data, 0, n);
}
/// Drops stray members (beyond 2.5× the median distance to the centroid) so a hull hugs
/// the body of its cluster instead of spanning the canvas.
List<Offset> corePoints(List<Offset> pts) {
if (pts.length < 6) return pts;
var cx = 0.0, cy = 0.0;
for (final p in pts) {
cx += p.dx;
cy += p.dy;
}
final c = Offset(cx / pts.length, cy / pts.length);
final d = [for (final p in pts) (p - c).distance]..sort();
final limit = 2.5 * math.max(d[d.length ~/ 2], 1.0);
return [
for (final p in pts)
if ((p - c).distance <= limit) p,
];
}
/// Convex hull (monotone chain), counter-clockwise.
List<Offset> convexHull(List<Offset> points) {
final p = List.of(
points,
)..sort((a, b) => a.dx != b.dx ? a.dx.compareTo(b.dx) : a.dy.compareTo(b.dy));
if (p.length < 3) return p;
double cross(Offset o, Offset a, Offset b) =>
(a.dx - o.dx) * (b.dy - o.dy) - (a.dy - o.dy) * (b.dx - o.dx);
final lower = <Offset>[];
for (final q in p) {
while (lower.length >= 2 &&
cross(lower[lower.length - 2], lower.last, q) <= 0) {
lower.removeLast();
}
lower.add(q);
}
final upper = <Offset>[];
for (final q in p.reversed) {
while (upper.length >= 2 &&
cross(upper[upper.length - 2], upper.last, q) <= 0) {
upper.removeLast();
}
upper.add(q);
}
lower.removeLast();
upper.removeLast();
return [...lower, ...upper];
}
+271
View File
@@ -0,0 +1,271 @@
import 'dart:math' as math;
import 'package:flutter/material.dart';
import '../theme/theme.dart';
import 'graph_model.dart';
import 'network_canvas.dart';
/// A node of the namespace / tag tree.
class TreeItem {
TreeItem(this.label, {this.global});
final String label;
/// Page index when the item is a page.
int? global;
final children = <TreeItem>[];
int depth = 0;
int leaves = 1;
double angle = 0;
Offset pos = Offset.zero;
TreeItem child(String label) {
for (final c in children) {
if (c.label == label) return c;
}
final c = TreeItem(label);
children.add(c);
return c;
}
}
/// Builds a tree with two branches: namespaces (`a/b/c` titles split on `/`) and tags (each
/// tag with the pages using it, most used tags first).
TreeItem buildNamespaceTree(
GraphModel g, {
int maxTags = 24,
int maxPerTag = 30,
}) {
final root = TreeItem('Graph');
final ns = TreeItem('Namespaces');
final byTitle = <String, int>{};
for (var i = 0; i < g.nodeCount; i++) {
if (!g.isJournal(i)) byTitle[g.node(i).title.toLowerCase()] = i;
}
for (var i = 0; i < g.nodeCount; i++) {
final t = g.node(i).title;
if (g.isJournal(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 (ns.children.isNotEmpty) root.children.add(ns);
final tags = TreeItem('Tags');
for (final tag in g.tags.take(maxTags)) {
final item = TreeItem('#${g.node(tag).title}', global: tag);
final seen = <int>{};
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) {
item.children.add(TreeItem(g.node(s).title, global: s));
}
}
tags.children.add(item);
}
if (tags.children.isNotEmpty) root.children.add(tags);
// With a single branch, that branch is the centre.
final top = root.children.length == 1 ? root.children.single : root;
_measure(top, 0);
_place(top, 0, 2 * math.pi);
return top;
}
int _measure(TreeItem t, int depth) {
t.depth = depth;
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));
}
const _ring = 120.0;
void _place(TreeItem t, double a0, double a1) {
t.angle = (a0 + a1) / 2;
final r = t.depth * _ring;
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);
a += span;
}
}
Iterable<TreeItem> _walk(TreeItem t) sync* {
yield t;
for (final c in t.children) {
yield* _walk(c);
}
}
/// Radial tree of namespaces and tags; pan/zoom with the GPU transform (no repaint).
class TreeCanvas extends StatefulWidget {
const TreeCanvas({super.key, required this.model, required this.onTap});
final GraphModel model;
final void Function(int global) onTap;
@override
State<TreeCanvas> createState() => _TreeCanvasState();
}
class _TreeCanvasState extends State<TreeCanvas> {
late TreeItem _root = buildNamespaceTree(widget.model);
final _transform = TransformationController();
bool _placed = false;
@override
void didUpdateWidget(TreeCanvas oldWidget) {
super.didUpdateWidget(oldWidget);
if (!identical(oldWidget.model, widget.model)) {
_root = buildNamespaceTree(widget.model);
}
}
@override
void dispose() {
_transform.dispose();
super.dispose();
}
double get _extent {
final maxDepth = _walk(_root).fold(0, (m, t) => math.max(m, t.depth));
return maxDepth * _ring + 170;
}
@override
Widget build(BuildContext context) {
final colors = context.colors;
if (_root.children.isEmpty) {
return Center(
child: Text(
'No namespaces (a/b titles) or tags yet.',
style: TextStyle(color: colors.muted),
),
);
}
final extent = _extent;
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 - extent * s,
box.maxHeight / 2 - extent * s,
0,
1,
)
..scaleByDouble(s, s, 1, 1);
}
return InteractiveViewer(
transformationController: _transform,
constrained: false,
minScale: 0.05,
maxScale: 6,
boundaryMargin: const EdgeInsets.all(double.infinity),
child: GestureDetector(
onTapUp: (d) {
final p = d.localPosition - Offset(extent, extent);
for (final t in _walk(_root)) {
if (t.global != null && (t.pos - p).distance < 10) {
widget.onTap(t.global!);
return;
}
}
},
child: CustomPaint(
size: Size(2 * extent, 2 * extent),
painter: _TreePainter(
_root,
extent,
colors,
graphPalette(Theme.of(context).brightness),
),
),
),
);
},
);
}
}
class _TreePainter extends CustomPainter {
_TreePainter(this.root, this.extent, this.colors, this.palette);
final TreeItem root;
final double extent;
final SynapseColors colors;
final List<Color> palette;
@override
void paint(Canvas canvas, Size size) {
canvas.translate(extent, extent);
final link = Paint()
..style = PaintingStyle.stroke
..strokeWidth = 1.2
..color = colors.line;
for (final t in _walk(root)) {
for (final c in t.children) {
// Curve from parent to child bending through the child's angle.
final mid = Offset.fromDirection(
c.angle,
t.depth * _ring + _ring * 0.5,
);
canvas.drawPath(
Path()
..moveTo(t.pos.dx, t.pos.dy)
..quadraticBezierTo(mid.dx, mid.dy, c.pos.dx, c.pos.dy),
link,
);
}
}
var branch = 0;
// Colour per first-level branch; with a single-branch tree each subtree gets its own.
for (final b in root.children) {
final color = palette[branch++ % palette.length];
for (final t in _walk(b)) {
final r = t.children.isEmpty ? 3.5 : 5.5;
canvas.drawCircle(
t.pos,
r,
Paint()..color = t.global == null ? colors.faint : color,
);
final tp = TextPainter(
text: TextSpan(
text: t.label,
style: TextStyle(
fontFamily: uiFont,
fontSize: t.children.isEmpty ? 11 : 12.5,
fontWeight: t.children.isEmpty
? FontWeight.w400
: FontWeight.w600,
color: t.children.isEmpty ? colors.muted : colors.ink,
),
),
textDirection: TextDirection.ltr,
maxLines: 1,
ellipsis: '…',
)..layout(maxWidth: 150);
// Labels outside the circle, left of the node on the left half.
final left = math.cos(t.angle) < 0;
final at = t.pos + Offset(left ? -tp.width - 8 : 8, -tp.height / 2);
tp.paint(canvas, at);
}
}
canvas.drawCircle(Offset.zero, 7, Paint()..color = colors.accent);
}
@override
bool shouldRepaint(_TreePainter old) =>
!identical(old.root, root) || old.colors != colors;
}