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

+57
View File
@@ -1,5 +1,9 @@
import 'dart:typed_data';
import '../graph/graph_model.dart';
import '../rust/api/dto.dart';
import '../rust/api/graph.dart';
import '../rust/api/layout.dart';
export '../rust/api/dto.dart';
@@ -49,6 +53,39 @@ abstract class GraphBackend {
/// Local path of an `asset://<hash>` blob, if present.
String? assetPath(String hash);
Future<AssetDto> putAssetFile(String path, {String? mime});
/// The whole page-level graph (cached by the core until the graph changes).
Future<GraphData> graphData();
/// A force layout over `nodeCount` nodes and the given (local) edges.
LayoutEngine createLayout(
int nodeCount,
Uint32List sources,
Uint32List targets,
Float32List weights, {
Float32List? initial,
});
}
class _FfiLayout implements LayoutEngine {
_FfiLayout(this._l);
final ForceLayout _l;
@override
Future<(Float32List, double)> step(int iterations) async {
final f = await _l.step(iterations: iterations);
return (f.positions, f.alpha);
}
@override
Future<void> pin(int index, double x, double y) =>
_l.pin(index: index, x: x, y: y);
@override
Future<void> unpin(int index) => _l.unpin(index: index);
@override
Future<void> reheat(double alpha) => _l.reheat(alpha: alpha);
@override
void dispose() => _l.dispose();
}
class FfiGraphBackend implements GraphBackend {
@@ -145,4 +182,24 @@ class FfiGraphBackend implements GraphBackend {
@override
Future<AssetDto> putAssetFile(String path, {String? mime}) =>
_g.putAssetFile(path: path, mime: mime);
@override
Future<GraphData> graphData() => _g.graphData();
@override
LayoutEngine createLayout(
int nodeCount,
Uint32List sources,
Uint32List targets,
Float32List weights, {
Float32List? initial,
}) => _FfiLayout(
ForceLayout(
nodeCount: nodeCount,
sources: sources,
targets: targets,
weights: weights,
initial: initial,
),
);
}
+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;
}
+129 -1
View File
@@ -8,7 +8,7 @@ import '../frb_generated.dart';
import 'package:flutter_rust_bridge/flutter_rust_bridge_for_generated.dart';
// These functions are ignored because they are not marked as `pub`: `new`
// These function are ignored because they are on traits that is not defined in current crate (put an empty `#[frb]` on it to unignore): `assert_fields_are_eq`, `assert_fields_are_eq`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `from`, `from`
// These function are ignored because they are on traits that is not defined in current crate (put an empty `#[frb]` on it to unignore): `assert_fields_are_eq`, `assert_fields_are_eq`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `clone`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `eq`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `fmt`, `from`, `from`
class AssetDto {
final String hash;
@@ -182,6 +182,134 @@ class EditDto {
edits == other.edits;
}
/// The whole page-level graph, edges as parallel arrays (cheap to move across the FFI).
/// Edges are directed source → target, except synapses (stored once, `source < target`).
class GraphData {
final List<GraphNode> nodes;
final Uint32List sources;
final Uint32List targets;
/// See [`edge_kind`].
final Uint8List kinds;
/// Number of references (structural edges) or synapse strength.
final Float32List weights;
/// Op-log sequence the data was built at.
final PlatformInt64 seq;
const GraphData({
required this.nodes,
required this.sources,
required this.targets,
required this.kinds,
required this.weights,
required this.seq,
});
@override
int get hashCode =>
nodes.hashCode ^
sources.hashCode ^
targets.hashCode ^
kinds.hashCode ^
weights.hashCode ^
seq.hashCode;
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is GraphData &&
runtimeType == other.runtimeType &&
nodes == other.nodes &&
sources == other.sources &&
targets == other.targets &&
kinds == other.kinds &&
weights == other.weights &&
seq == other.seq;
}
class GraphNode {
final String id;
final String title;
final String? journalDate;
final String? originJournal;
final PlatformInt64 createdAt;
/// Distinct neighbours over structural edges (links, tags, properties, block refs).
final int degree;
/// Distinct pages referencing this one.
final int backlinks;
/// Community (Louvain), numbered by size: 0 is the largest.
final int cluster;
/// Node index of the tag this page uses most, if any.
final int? primaryTag;
const GraphNode({
required this.id,
required this.title,
this.journalDate,
this.originJournal,
required this.createdAt,
required this.degree,
required this.backlinks,
required this.cluster,
this.primaryTag,
});
@override
int get hashCode =>
id.hashCode ^
title.hashCode ^
journalDate.hashCode ^
originJournal.hashCode ^
createdAt.hashCode ^
degree.hashCode ^
backlinks.hashCode ^
cluster.hashCode ^
primaryTag.hashCode;
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is GraphNode &&
runtimeType == other.runtimeType &&
id == other.id &&
title == other.title &&
journalDate == other.journalDate &&
originJournal == other.originJournal &&
createdAt == other.createdAt &&
degree == other.degree &&
backlinks == other.backlinks &&
cluster == other.cluster &&
primaryTag == other.primaryTag;
}
/// One batch of layout iterations.
class LayoutFrame {
/// `x0, y0, x1, y1, ...`
final Float32List positions;
/// Remaining "temperature"; the layout is settled when it reaches 0.
final double alpha;
const LayoutFrame({required this.positions, required this.alpha});
@override
int get hashCode => positions.hashCode ^ alpha.hashCode;
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is LayoutFrame &&
runtimeType == other.runtimeType &&
positions == other.positions &&
alpha == other.alpha;
}
class PageBrief {
final String id;
final String title;
+4
View File
@@ -34,6 +34,10 @@ abstract class SynapseGraph implements RustOpaqueInterface {
/// Graph directory.
String dir();
/// The whole page-level graph (journals included; the UI filters). Cached until the
/// graph changes.
Future<GraphData> graphData();
/// Tab: the block becomes the last child of its previous sibling (no-op for a first child).
Future<List<BlockDto>> indentBlock({required String id});
+45
View File
@@ -0,0 +1,45 @@
// This file is automatically generated, so please do not edit it.
// @generated by `flutter_rust_bridge`@ 2.13.0.
// ignore_for_file: invalid_use_of_internal_member, unused_import, unnecessary_import
import '../frb_generated.dart';
import 'dto.dart';
import 'package:flutter_rust_bridge/flutter_rust_bridge_for_generated.dart';
// These functions are ignored because they are not marked as `pub`: `accumulate`, `build_tree`, `insert`, `new`, `quadrant`, `repulsion`, `split`, `tick`
// These types are ignored because they are neither used by any `pub` functions nor (for structs and enums) marked `#[frb(unignore)]`: `Cell`
// These function are ignored because they are on traits that is not defined in current crate (put an empty `#[frb]` on it to unignore): `clone`
// Rust type: RustOpaqueMoi<flutter_rust_bridge::for_generated::RustAutoOpaqueInner<ForceLayout>>
abstract class ForceLayout implements RustOpaqueInterface {
/// A layout for `node_count` nodes and edges `sources[i] → targets[i]` (weights scale the
/// spring strength). `initial` positions (`x0, y0, ...`) are reused when given, e.g. to keep
/// the picture stable after filtering; otherwise nodes start on a phyllotaxis spiral.
factory ForceLayout({
required int nodeCount,
required List<int> sources,
required List<int> targets,
required List<double> weights,
Float32List? initial,
}) => RustLib.instance.api.crateApiLayoutForceLayoutNew(
nodeCount: nodeCount,
sources: sources,
targets: targets,
weights: weights,
initial: initial,
);
/// Holds node `index` at `(x, y)` (while dragging) and keeps the layout warm.
Future<void> pin({required int index, required double x, required double y});
/// Restarts the simulation at temperature `alpha` (0..1).
Future<void> reheat({required double alpha});
/// Runs up to `iterations` ticks (stops early once settled).
Future<LayoutFrame> step({required int iterations});
/// Releases a pinned node and lets the layout cool down again.
Future<void> unpin({required int index});
}
File diff suppressed because it is too large. Load diff
+215
View File
@@ -5,6 +5,7 @@
import 'api/dto.dart';
import 'api/graph.dart';
import 'api/layout.dart';
import 'dart:async';
import 'dart:convert';
@@ -22,6 +23,10 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
required super.portManager,
});
CrossPlatformFinalizerArg
get rust_arc_decrement_strong_count_ForceLayoutPtr => wire
._rust_arc_decrement_strong_count_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerForceLayoutPtr;
CrossPlatformFinalizerArg
get rust_arc_decrement_strong_count_SynapseGraphPtr => wire
._rust_arc_decrement_strong_count_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraphPtr;
@@ -29,18 +34,36 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected
AnyhowException dco_decode_AnyhowException(dynamic raw);
@protected
ForceLayout
dco_decode_Auto_Owned_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerForceLayout(
dynamic raw,
);
@protected
SynapseGraph
dco_decode_Auto_Owned_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph(
dynamic raw,
);
@protected
ForceLayout
dco_decode_Auto_RefMut_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerForceLayout(
dynamic raw,
);
@protected
SynapseGraph
dco_decode_Auto_Ref_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph(
dynamic raw,
);
@protected
ForceLayout
dco_decode_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerForceLayout(
dynamic raw,
);
@protected
SynapseGraph
dco_decode_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph(
@@ -77,18 +100,30 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected
Place dco_decode_box_autoadd_place(dynamic raw);
@protected
int dco_decode_box_autoadd_u_32(dynamic raw);
@protected
EditDto dco_decode_edit_dto(dynamic raw);
@protected
double dco_decode_f_32(dynamic raw);
@protected
GraphData dco_decode_graph_data(dynamic raw);
@protected
GraphNode dco_decode_graph_node(dynamic raw);
@protected
int dco_decode_i_32(dynamic raw);
@protected
PlatformInt64 dco_decode_i_64(dynamic raw);
@protected
LayoutFrame dco_decode_layout_frame(dynamic raw);
@protected
List<String> dco_decode_list_String(dynamic raw);
@@ -104,6 +139,9 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected
List<EditDto> dco_decode_list_edit_dto(dynamic raw);
@protected
List<GraphNode> dco_decode_list_graph_node(dynamic raw);
@protected
List<PageBrief> dco_decode_list_page_brief(dynamic raw);
@@ -113,6 +151,18 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected
List<PageDto> dco_decode_list_page_dto(dynamic raw);
@protected
List<double> dco_decode_list_prim_f_32_loose(dynamic raw);
@protected
Float32List dco_decode_list_prim_f_32_strict(dynamic raw);
@protected
List<int> dco_decode_list_prim_u_32_loose(dynamic raw);
@protected
Uint32List dco_decode_list_prim_u_32_strict(dynamic raw);
@protected
List<int> dco_decode_list_prim_u_8_loose(dynamic raw);
@@ -137,6 +187,12 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected
PageData? dco_decode_opt_box_autoadd_page_data(dynamic raw);
@protected
int? dco_decode_opt_box_autoadd_u_32(dynamic raw);
@protected
Float32List? dco_decode_opt_list_prim_f_32_strict(dynamic raw);
@protected
PageBrief dco_decode_page_brief(dynamic raw);
@@ -185,18 +241,36 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected
AnyhowException sse_decode_AnyhowException(SseDeserializer deserializer);
@protected
ForceLayout
sse_decode_Auto_Owned_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerForceLayout(
SseDeserializer deserializer,
);
@protected
SynapseGraph
sse_decode_Auto_Owned_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph(
SseDeserializer deserializer,
);
@protected
ForceLayout
sse_decode_Auto_RefMut_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerForceLayout(
SseDeserializer deserializer,
);
@protected
SynapseGraph
sse_decode_Auto_Ref_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph(
SseDeserializer deserializer,
);
@protected
ForceLayout
sse_decode_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerForceLayout(
SseDeserializer deserializer,
);
@protected
SynapseGraph
sse_decode_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph(
@@ -235,18 +309,30 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected
Place sse_decode_box_autoadd_place(SseDeserializer deserializer);
@protected
int sse_decode_box_autoadd_u_32(SseDeserializer deserializer);
@protected
EditDto sse_decode_edit_dto(SseDeserializer deserializer);
@protected
double sse_decode_f_32(SseDeserializer deserializer);
@protected
GraphData sse_decode_graph_data(SseDeserializer deserializer);
@protected
GraphNode sse_decode_graph_node(SseDeserializer deserializer);
@protected
int sse_decode_i_32(SseDeserializer deserializer);
@protected
PlatformInt64 sse_decode_i_64(SseDeserializer deserializer);
@protected
LayoutFrame sse_decode_layout_frame(SseDeserializer deserializer);
@protected
List<String> sse_decode_list_String(SseDeserializer deserializer);
@@ -264,6 +350,9 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected
List<EditDto> sse_decode_list_edit_dto(SseDeserializer deserializer);
@protected
List<GraphNode> sse_decode_list_graph_node(SseDeserializer deserializer);
@protected
List<PageBrief> sse_decode_list_page_brief(SseDeserializer deserializer);
@@ -273,6 +362,18 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected
List<PageDto> sse_decode_list_page_dto(SseDeserializer deserializer);
@protected
List<double> sse_decode_list_prim_f_32_loose(SseDeserializer deserializer);
@protected
Float32List sse_decode_list_prim_f_32_strict(SseDeserializer deserializer);
@protected
List<int> sse_decode_list_prim_u_32_loose(SseDeserializer deserializer);
@protected
Uint32List sse_decode_list_prim_u_32_strict(SseDeserializer deserializer);
@protected
List<int> sse_decode_list_prim_u_8_loose(SseDeserializer deserializer);
@@ -301,6 +402,14 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected
PageData? sse_decode_opt_box_autoadd_page_data(SseDeserializer deserializer);
@protected
int? sse_decode_opt_box_autoadd_u_32(SseDeserializer deserializer);
@protected
Float32List? sse_decode_opt_list_prim_f_32_strict(
SseDeserializer deserializer,
);
@protected
PageBrief sse_decode_page_brief(SseDeserializer deserializer);
@@ -354,6 +463,13 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
SseSerializer serializer,
);
@protected
void
sse_encode_Auto_Owned_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerForceLayout(
ForceLayout self,
SseSerializer serializer,
);
@protected
void
sse_encode_Auto_Owned_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph(
@@ -361,6 +477,13 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
SseSerializer serializer,
);
@protected
void
sse_encode_Auto_RefMut_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerForceLayout(
ForceLayout self,
SseSerializer serializer,
);
@protected
void
sse_encode_Auto_Ref_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph(
@@ -368,6 +491,13 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
SseSerializer serializer,
);
@protected
void
sse_encode_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerForceLayout(
ForceLayout self,
SseSerializer serializer,
);
@protected
void
sse_encode_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph(
@@ -411,18 +541,30 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected
void sse_encode_box_autoadd_place(Place self, SseSerializer serializer);
@protected
void sse_encode_box_autoadd_u_32(int self, SseSerializer serializer);
@protected
void sse_encode_edit_dto(EditDto self, SseSerializer serializer);
@protected
void sse_encode_f_32(double self, SseSerializer serializer);
@protected
void sse_encode_graph_data(GraphData self, SseSerializer serializer);
@protected
void sse_encode_graph_node(GraphNode self, SseSerializer serializer);
@protected
void sse_encode_i_32(int self, SseSerializer serializer);
@protected
void sse_encode_i_64(PlatformInt64 self, SseSerializer serializer);
@protected
void sse_encode_layout_frame(LayoutFrame self, SseSerializer serializer);
@protected
void sse_encode_list_String(List<String> self, SseSerializer serializer);
@@ -441,6 +583,12 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected
void sse_encode_list_edit_dto(List<EditDto> self, SseSerializer serializer);
@protected
void sse_encode_list_graph_node(
List<GraphNode> self,
SseSerializer serializer,
);
@protected
void sse_encode_list_page_brief(
List<PageBrief> self,
@@ -453,6 +601,30 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected
void sse_encode_list_page_dto(List<PageDto> self, SseSerializer serializer);
@protected
void sse_encode_list_prim_f_32_loose(
List<double> self,
SseSerializer serializer,
);
@protected
void sse_encode_list_prim_f_32_strict(
Float32List self,
SseSerializer serializer,
);
@protected
void sse_encode_list_prim_u_32_loose(
List<int> self,
SseSerializer serializer,
);
@protected
void sse_encode_list_prim_u_32_strict(
Uint32List self,
SseSerializer serializer,
);
@protected
void sse_encode_list_prim_u_8_loose(List<int> self, SseSerializer serializer);
@@ -492,6 +664,15 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
SseSerializer serializer,
);
@protected
void sse_encode_opt_box_autoadd_u_32(int? self, SseSerializer serializer);
@protected
void sse_encode_opt_list_prim_f_32_strict(
Float32List? self,
SseSerializer serializer,
);
@protected
void sse_encode_page_brief(PageBrief self, SseSerializer serializer);
@@ -558,6 +739,40 @@ class RustLibWire implements BaseWire {
RustLibWire(ffi.DynamicLibrary dynamicLibrary)
: _lookup = dynamicLibrary.lookup;
void
rust_arc_increment_strong_count_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerForceLayout(
ffi.Pointer<ffi.Void> ptr,
) {
return _rust_arc_increment_strong_count_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerForceLayout(
ptr,
);
}
late final _rust_arc_increment_strong_count_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerForceLayoutPtr =
_lookup<ffi.NativeFunction<ffi.Void Function(ffi.Pointer<ffi.Void>)>>(
'frbgen_synapse_rust_arc_increment_strong_count_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerForceLayout',
);
late final _rust_arc_increment_strong_count_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerForceLayout =
_rust_arc_increment_strong_count_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerForceLayoutPtr
.asFunction<void Function(ffi.Pointer<ffi.Void>)>();
void
rust_arc_decrement_strong_count_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerForceLayout(
ffi.Pointer<ffi.Void> ptr,
) {
return _rust_arc_decrement_strong_count_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerForceLayout(
ptr,
);
}
late final _rust_arc_decrement_strong_count_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerForceLayoutPtr =
_lookup<ffi.NativeFunction<ffi.Void Function(ffi.Pointer<ffi.Void>)>>(
'frbgen_synapse_rust_arc_decrement_strong_count_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerForceLayout',
);
late final _rust_arc_decrement_strong_count_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerForceLayout =
_rust_arc_decrement_strong_count_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerForceLayoutPtr
.asFunction<void Function(ffi.Pointer<ffi.Void>)>();
void
rust_arc_increment_strong_count_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph(
ffi.Pointer<ffi.Void> ptr,
+207
View File
@@ -8,6 +8,7 @@
import 'api/dto.dart';
import 'api/graph.dart';
import 'api/layout.dart';
import 'dart:async';
import 'dart:convert';
@@ -24,6 +25,10 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
required super.portManager,
});
CrossPlatformFinalizerArg
get rust_arc_decrement_strong_count_ForceLayoutPtr => wire
.rust_arc_decrement_strong_count_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerForceLayout;
CrossPlatformFinalizerArg
get rust_arc_decrement_strong_count_SynapseGraphPtr => wire
.rust_arc_decrement_strong_count_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph;
@@ -31,18 +36,36 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected
AnyhowException dco_decode_AnyhowException(dynamic raw);
@protected
ForceLayout
dco_decode_Auto_Owned_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerForceLayout(
dynamic raw,
);
@protected
SynapseGraph
dco_decode_Auto_Owned_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph(
dynamic raw,
);
@protected
ForceLayout
dco_decode_Auto_RefMut_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerForceLayout(
dynamic raw,
);
@protected
SynapseGraph
dco_decode_Auto_Ref_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph(
dynamic raw,
);
@protected
ForceLayout
dco_decode_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerForceLayout(
dynamic raw,
);
@protected
SynapseGraph
dco_decode_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph(
@@ -79,18 +102,30 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected
Place dco_decode_box_autoadd_place(dynamic raw);
@protected
int dco_decode_box_autoadd_u_32(dynamic raw);
@protected
EditDto dco_decode_edit_dto(dynamic raw);
@protected
double dco_decode_f_32(dynamic raw);
@protected
GraphData dco_decode_graph_data(dynamic raw);
@protected
GraphNode dco_decode_graph_node(dynamic raw);
@protected
int dco_decode_i_32(dynamic raw);
@protected
PlatformInt64 dco_decode_i_64(dynamic raw);
@protected
LayoutFrame dco_decode_layout_frame(dynamic raw);
@protected
List<String> dco_decode_list_String(dynamic raw);
@@ -106,6 +141,9 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected
List<EditDto> dco_decode_list_edit_dto(dynamic raw);
@protected
List<GraphNode> dco_decode_list_graph_node(dynamic raw);
@protected
List<PageBrief> dco_decode_list_page_brief(dynamic raw);
@@ -115,6 +153,18 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected
List<PageDto> dco_decode_list_page_dto(dynamic raw);
@protected
List<double> dco_decode_list_prim_f_32_loose(dynamic raw);
@protected
Float32List dco_decode_list_prim_f_32_strict(dynamic raw);
@protected
List<int> dco_decode_list_prim_u_32_loose(dynamic raw);
@protected
Uint32List dco_decode_list_prim_u_32_strict(dynamic raw);
@protected
List<int> dco_decode_list_prim_u_8_loose(dynamic raw);
@@ -139,6 +189,12 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected
PageData? dco_decode_opt_box_autoadd_page_data(dynamic raw);
@protected
int? dco_decode_opt_box_autoadd_u_32(dynamic raw);
@protected
Float32List? dco_decode_opt_list_prim_f_32_strict(dynamic raw);
@protected
PageBrief dco_decode_page_brief(dynamic raw);
@@ -187,18 +243,36 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected
AnyhowException sse_decode_AnyhowException(SseDeserializer deserializer);
@protected
ForceLayout
sse_decode_Auto_Owned_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerForceLayout(
SseDeserializer deserializer,
);
@protected
SynapseGraph
sse_decode_Auto_Owned_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph(
SseDeserializer deserializer,
);
@protected
ForceLayout
sse_decode_Auto_RefMut_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerForceLayout(
SseDeserializer deserializer,
);
@protected
SynapseGraph
sse_decode_Auto_Ref_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph(
SseDeserializer deserializer,
);
@protected
ForceLayout
sse_decode_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerForceLayout(
SseDeserializer deserializer,
);
@protected
SynapseGraph
sse_decode_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph(
@@ -237,18 +311,30 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected
Place sse_decode_box_autoadd_place(SseDeserializer deserializer);
@protected
int sse_decode_box_autoadd_u_32(SseDeserializer deserializer);
@protected
EditDto sse_decode_edit_dto(SseDeserializer deserializer);
@protected
double sse_decode_f_32(SseDeserializer deserializer);
@protected
GraphData sse_decode_graph_data(SseDeserializer deserializer);
@protected
GraphNode sse_decode_graph_node(SseDeserializer deserializer);
@protected
int sse_decode_i_32(SseDeserializer deserializer);
@protected
PlatformInt64 sse_decode_i_64(SseDeserializer deserializer);
@protected
LayoutFrame sse_decode_layout_frame(SseDeserializer deserializer);
@protected
List<String> sse_decode_list_String(SseDeserializer deserializer);
@@ -266,6 +352,9 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected
List<EditDto> sse_decode_list_edit_dto(SseDeserializer deserializer);
@protected
List<GraphNode> sse_decode_list_graph_node(SseDeserializer deserializer);
@protected
List<PageBrief> sse_decode_list_page_brief(SseDeserializer deserializer);
@@ -275,6 +364,18 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected
List<PageDto> sse_decode_list_page_dto(SseDeserializer deserializer);
@protected
List<double> sse_decode_list_prim_f_32_loose(SseDeserializer deserializer);
@protected
Float32List sse_decode_list_prim_f_32_strict(SseDeserializer deserializer);
@protected
List<int> sse_decode_list_prim_u_32_loose(SseDeserializer deserializer);
@protected
Uint32List sse_decode_list_prim_u_32_strict(SseDeserializer deserializer);
@protected
List<int> sse_decode_list_prim_u_8_loose(SseDeserializer deserializer);
@@ -303,6 +404,14 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected
PageData? sse_decode_opt_box_autoadd_page_data(SseDeserializer deserializer);
@protected
int? sse_decode_opt_box_autoadd_u_32(SseDeserializer deserializer);
@protected
Float32List? sse_decode_opt_list_prim_f_32_strict(
SseDeserializer deserializer,
);
@protected
PageBrief sse_decode_page_brief(SseDeserializer deserializer);
@@ -356,6 +465,13 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
SseSerializer serializer,
);
@protected
void
sse_encode_Auto_Owned_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerForceLayout(
ForceLayout self,
SseSerializer serializer,
);
@protected
void
sse_encode_Auto_Owned_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph(
@@ -363,6 +479,13 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
SseSerializer serializer,
);
@protected
void
sse_encode_Auto_RefMut_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerForceLayout(
ForceLayout self,
SseSerializer serializer,
);
@protected
void
sse_encode_Auto_Ref_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph(
@@ -370,6 +493,13 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
SseSerializer serializer,
);
@protected
void
sse_encode_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerForceLayout(
ForceLayout self,
SseSerializer serializer,
);
@protected
void
sse_encode_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph(
@@ -413,18 +543,30 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected
void sse_encode_box_autoadd_place(Place self, SseSerializer serializer);
@protected
void sse_encode_box_autoadd_u_32(int self, SseSerializer serializer);
@protected
void sse_encode_edit_dto(EditDto self, SseSerializer serializer);
@protected
void sse_encode_f_32(double self, SseSerializer serializer);
@protected
void sse_encode_graph_data(GraphData self, SseSerializer serializer);
@protected
void sse_encode_graph_node(GraphNode self, SseSerializer serializer);
@protected
void sse_encode_i_32(int self, SseSerializer serializer);
@protected
void sse_encode_i_64(PlatformInt64 self, SseSerializer serializer);
@protected
void sse_encode_layout_frame(LayoutFrame self, SseSerializer serializer);
@protected
void sse_encode_list_String(List<String> self, SseSerializer serializer);
@@ -443,6 +585,12 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected
void sse_encode_list_edit_dto(List<EditDto> self, SseSerializer serializer);
@protected
void sse_encode_list_graph_node(
List<GraphNode> self,
SseSerializer serializer,
);
@protected
void sse_encode_list_page_brief(
List<PageBrief> self,
@@ -455,6 +603,30 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
@protected
void sse_encode_list_page_dto(List<PageDto> self, SseSerializer serializer);
@protected
void sse_encode_list_prim_f_32_loose(
List<double> self,
SseSerializer serializer,
);
@protected
void sse_encode_list_prim_f_32_strict(
Float32List self,
SseSerializer serializer,
);
@protected
void sse_encode_list_prim_u_32_loose(
List<int> self,
SseSerializer serializer,
);
@protected
void sse_encode_list_prim_u_32_strict(
Uint32List self,
SseSerializer serializer,
);
@protected
void sse_encode_list_prim_u_8_loose(List<int> self, SseSerializer serializer);
@@ -494,6 +666,15 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
SseSerializer serializer,
);
@protected
void sse_encode_opt_box_autoadd_u_32(int? self, SseSerializer serializer);
@protected
void sse_encode_opt_list_prim_f_32_strict(
Float32List? self,
SseSerializer serializer,
);
@protected
void sse_encode_page_brief(PageBrief self, SseSerializer serializer);
@@ -551,6 +732,22 @@ abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
class RustLibWire implements BaseWire {
RustLibWire.fromExternalLibrary(ExternalLibrary lib);
void
rust_arc_increment_strong_count_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerForceLayout(
int ptr,
) => wasmModule
.rust_arc_increment_strong_count_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerForceLayout(
ptr,
);
void
rust_arc_decrement_strong_count_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerForceLayout(
int ptr,
) => wasmModule
.rust_arc_decrement_strong_count_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerForceLayout(
ptr,
);
void
rust_arc_increment_strong_count_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph(
int ptr,
@@ -574,6 +771,16 @@ external RustLibWasmModule get wasmModule;
@JS()
@anonymous
extension type RustLibWasmModule._(JSObject _) implements JSObject {
external void
rust_arc_increment_strong_count_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerForceLayout(
int ptr,
);
external void
rust_arc_decrement_strong_count_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerForceLayout(
int ptr,
);
external void
rust_arc_increment_strong_count_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph(
int ptr,
+24
View File
@@ -1,6 +1,7 @@
import 'package:flutter/material.dart';
import '../backend/graph_backend.dart';
import '../graph/network_canvas.dart';
import 'write_queue.dart';
sealed class AppRoute {
@@ -19,6 +20,26 @@ class AllPagesRoute extends AppRoute {
const AllPagesRoute();
}
enum GraphMode {
network('Network', Icons.hub_outlined),
local('Local', Icons.adjust_rounded),
brain('Synapses', Icons.bolt_outlined),
clusters('Clusters', Icons.bubble_chart_outlined),
tree('Namespaces', Icons.account_tree_outlined),
timeline('Timeline', Icons.timeline_rounded);
const GraphMode(this.label, this.icon);
final String label;
final IconData icon;
}
/// The graph view in a given mode, optionally focused on a page.
class GraphRoute extends AppRoute {
const GraphRoute(this.mode, {this.focusId});
final GraphMode mode;
final String? focusId;
}
/// A page, by id or (for links that may not exist yet) by title.
class PageTarget extends AppRoute {
const PageTarget({this.id, this.title}) : assert(id != null || title != null);
@@ -49,6 +70,9 @@ class AppState extends ChangeNotifier {
ThemeMode themeMode = ThemeMode.system;
final List<PageBrief> recent = [];
/// Node positions shared by the graph views (stable layouts across modes and filters).
final graphPositions = PositionCache();
/// Last page shown (for synapse reinforcement on navigation).
String? _lastPageId;
+6 -1
View File
@@ -11,6 +11,9 @@ class WriteQueue {
/// Called with any error a task throws; the task's own future also completes with it.
void Function(Object error, StackTrace stack)? onError;
/// Bumped after each successful write (reads pass `report: false` and do not count).
final revision = ValueNotifier<int>(0);
final _tasks = Queue<Future<void> Function()>();
bool _running = false;
Completer<void>? _idle;
@@ -28,7 +31,9 @@ class WriteQueue {
final done = Completer<T>();
_tasks.add(() async {
try {
done.complete(await task());
final out = await task();
if (report) revision.value++;
done.complete(out);
} catch (e, st) {
if (report) onError?.call(e, st);
done.completeError(e, st);
+763
View File
@@ -0,0 +1,763 @@
import 'dart:async';
import 'dart:math' as math;
import 'package:flutter/material.dart';
import '../graph/graph_model.dart';
import '../graph/network_canvas.dart';
import '../graph/tree_canvas.dart';
import '../state/app_state.dart';
import '../theme/theme.dart';
import '../widgets/dates.dart';
import 'timeline_view.dart';
/// Loads the page-level graph after pending writes have reached the core.
Future<GraphModel> loadGraphModel(AppState app) async {
final data = await app.queue.run(app.backend.graphData, report: false);
return GraphModel(data);
}
/// One view, several ways of looking at the graph (mode selector on top).
class GraphView extends StatefulWidget {
const GraphView({super.key, this.mode = GraphMode.network, this.focusId});
final GraphMode mode;
/// Page to focus in the local and synapse modes.
final String? focusId;
@override
State<GraphView> createState() => _GraphViewState();
}
class _GraphViewState extends State<GraphView> {
late GraphMode _mode = widget.mode;
GraphModel? _model;
Object? _error;
GraphFilter _filter = const GraphFilter();
ColorBy _colorBy = ColorBy.cluster;
int _depth = 2;
/// Journals are context for a neighbourhood, so the local mode shows them by default.
bool _localJournals = true;
int? _focus;
BrainOverlay? _brain;
SubGraph? _sub;
final _query = TextEditingController();
@override
void initState() {
super.initState();
_load();
}
@override
void dispose() {
_query.dispose();
super.dispose();
}
Future<void> _load() async {
final app = AppScope.read(context);
try {
final m = await loadGraphModel(app);
if (!mounted) return;
int? focus = widget.focusId == null ? null : m.indexOf(widget.focusId!);
for (final r in app.recent) {
if (focus != null) break;
focus = m.indexOf(r.id);
}
if (focus == null && m.nodeCount > 0) {
focus = List.generate(
m.nodeCount,
(i) => i,
).reduce((a, b) => m.node(a).degree >= m.node(b).degree ? a : b);
}
setState(() {
_model = m;
_focus = focus;
});
_rebuildSub();
} catch (e) {
if (mounted) setState(() => _error = e);
}
}
void _setMode(GraphMode m) {
setState(() => _mode = m);
_rebuildSub();
}
void _setFilter(GraphFilter f) {
setState(() => _filter = f);
_rebuildSub();
}
void _setFocus(int global) {
setState(() => _focus = global);
_rebuildSub();
}
Future<void> _rebuildSub() async {
final m = _model;
if (m == null) return;
switch (_mode) {
case GraphMode.network || GraphMode.clusters:
setState(() => _sub = m.subgraph(_filter.apply(m), _filter.kinds));
case GraphMode.local:
final f = _focus;
if (f == null) return;
final kinds = _filter.kinds;
final hood = m.neighbourhood(f, _depth, kinds);
final nodes = hood.keys
.where((i) => i == f || _localJournals || !m.isJournal(i))
.toList();
setState(() => _sub = m.subgraph(nodes, kinds));
case GraphMode.brain:
final f = _focus;
if (f == null) return;
final app = AppScope.read(context);
final related = await app.backend.related(m.node(f).id, limit: 40);
if (!mounted || _focus != f || _mode != GraphMode.brain) return;
final top = related.isEmpty
? 1.0
: related.map((r) => r.score).reduce(math.max);
final activation = <int, double>{f: 1.0};
for (final r in related) {
final i = m.indexOf(r.page.id);
if (i != null) activation[i] = (r.score / top).clamp(0.05, 1.0) * 0.9;
}
final kinds = {...EdgeKind.values};
// Springs to the focus, stronger for more activated notes, keep the picture radial.
final sub = m.subgraph(
activation.keys.toList(),
kinds,
springs: [
for (final MapEntry(key: i, value: a) in activation.entries)
if (i != f) (f, i, 0.4 + 2 * a),
],
);
// Hops from the focus inside the subgraph drive the pulse.
final hops = <int, int>{f: 0};
var frontier = [f];
while (frontier.isNotEmpty) {
final next = <int>[];
for (final i in frontier) {
for (final e in m.adjacency[i]) {
final j = m.other(e, i);
if (sub.local.containsKey(j) && !hops.containsKey(j)) {
hops[j] = hops[i]! + 1;
next.add(j);
}
}
}
frontier = next;
}
// Related but unconnected inside the slice: outermost ring.
final outer = hops.values.fold(0, math.max) + 1;
for (final i in activation.keys) {
hops.putIfAbsent(i, () => outer);
}
setState(() {
_sub = sub;
_brain = BrainOverlay(focus: f, activation: activation, hops: hops);
});
case GraphMode.tree || GraphMode.timeline:
break;
}
}
void _open(int global) {
final m = _model!;
AppScope.read(context).openId(m.node(global).id);
}
@override
Widget build(BuildContext context) {
final colors = context.colors;
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Padding(
padding: const EdgeInsets.fromLTRB(20, 4, 20, 8),
child: Wrap(
spacing: 12,
runSpacing: 8,
crossAxisAlignment: WrapCrossAlignment.center,
children: [
SegmentedButton<GraphMode>(
key: const ValueKey('graph-modes'),
showSelectedIcon: false,
style: SegmentedButton.styleFrom(
visualDensity: VisualDensity.compact,
textStyle: const TextStyle(
fontFamily: uiFont,
fontSize: 12.5,
),
side: BorderSide(color: colors.line),
selectedBackgroundColor: colors.accentSoft,
),
segments: [
for (final m in GraphMode.values)
ButtonSegment(
value: m,
label: Text(m.label),
icon: Icon(m.icon, size: 16),
),
],
selected: {_mode},
onSelectionChanged: (s) => _setMode(s.first),
),
if (_model != null) ..._controls(context),
],
),
),
Divider(height: 1, color: colors.line),
Expanded(child: _body(context)),
],
);
}
List<Widget> _controls(BuildContext context) {
final m = _model!;
final colors = context.colors;
Widget chip(String label, bool on, ValueChanged<bool> f) => FilterChip(
label: Text(label, style: const TextStyle(fontSize: 12)),
selected: on,
onSelected: f,
visualDensity: VisualDensity.compact,
showCheckmark: false,
selectedColor: colors.accentSoft,
side: BorderSide(color: colors.line),
);
final search = SizedBox(
width: 200,
child: TextField(
controller: _query,
style: const TextStyle(fontSize: 13),
decoration: InputDecoration(
isDense: true,
prefixIcon: const Icon(Icons.search_rounded, size: 16),
prefixIconConstraints: const BoxConstraints(minWidth: 30),
hintText: _mode == GraphMode.network || _mode == GraphMode.clusters
? 'Filter pages'
: 'Focus page',
border: OutlineInputBorder(borderRadius: BorderRadius.circular(8)),
contentPadding: const EdgeInsets.symmetric(vertical: 8),
),
onChanged: (q) {
if (_mode == GraphMode.network || _mode == GraphMode.clusters) {
_setFilter(_filter.copyWith(query: q));
}
},
onSubmitted: (q) {
final lq = q.toLowerCase().trim();
for (var i = 0; i < m.nodeCount; i++) {
if (m.node(i).title.toLowerCase().contains(lq)) {
_setFocus(i);
return;
}
}
},
),
);
switch (_mode) {
case GraphMode.network || GraphMode.clusters:
return [
search,
chip(
'Journals',
_filter.journals,
(v) => _setFilter(_filter.copyWith(journals: v)),
),
chip(
'Orphans',
_filter.orphans,
(v) => _setFilter(_filter.copyWith(orphans: v)),
),
chip(
'Mentions',
_filter.kinds.contains(EdgeKind.mention),
(v) => _setFilter(
_filter.copyWith(
kinds: v
? {..._filter.kinds, EdgeKind.mention}
: ({..._filter.kinds}..remove(EdgeKind.mention)),
),
),
),
_Labeled(
'Min links ${_filter.minDegree}',
SizedBox(
width: 110,
child: Slider(
value: _filter.minDegree.toDouble(),
max: 10,
divisions: 10,
onChanged: (v) =>
_setFilter(_filter.copyWith(minDegree: v.round())),
),
),
),
_Dropdown<int?>(
value: _filter.tag,
hint: 'Any tag',
items: {
null: 'Any tag',
for (final t in m.tags.take(40)) t: '#${m.node(t).title}',
},
onChanged: (t) => _setFilter(_filter.copyWith(tag: () => t)),
),
TextButton.icon(
icon: const Icon(Icons.date_range_outlined, size: 16),
label: Text(
_filter.from == null
? 'Any date'
: '${shortDate(parseDay(_filter.from!))} – ${shortDate(parseDay(_filter.to!))}',
style: const TextStyle(fontSize: 12),
),
onPressed: () async {
final now = DateTime.now();
final r = await showDateRangePicker(
context: context,
firstDate: DateTime(1990),
lastDate: DateTime(now.year + 1),
);
if (r == null) return;
_setFilter(
_filter.copyWith(
from: () => formatDay(r.start),
to: () => formatDay(r.end),
),
);
},
),
if (_filter.from != null)
IconButton(
tooltip: 'Any date',
iconSize: 15,
visualDensity: VisualDensity.compact,
icon: const Icon(Icons.close_rounded),
onPressed: () => _setFilter(
_filter.copyWith(from: () => null, to: () => null),
),
),
if (_mode == GraphMode.network)
_Dropdown<ColorBy>(
value: _colorBy,
hint: 'Colour',
items: const {
ColorBy.cluster: 'Colour: cluster',
ColorBy.tag: 'Colour: tag',
ColorBy.none: 'Colour: none',
},
onChanged: (c) => setState(() => _colorBy = c ?? ColorBy.cluster),
),
];
case GraphMode.local:
return [
search,
_Labeled(
'Depth $_depth',
SizedBox(
width: 120,
child: Slider(
key: const ValueKey('depth'),
value: _depth.toDouble(),
min: 1,
max: 3,
divisions: 2,
onChanged: (v) {
setState(() => _depth = v.round());
_rebuildSub();
},
),
),
),
chip('Journals', _localJournals, (v) {
setState(() => _localJournals = v);
_rebuildSub();
}),
if (_focus != null)
_FocusLink(
title: m.node(_focus!).title,
onTap: () => _open(_focus!),
),
];
case GraphMode.brain:
return [
search,
if (_focus != null)
_FocusLink(
title: m.node(_focus!).title,
onTap: () => _open(_focus!),
),
TextButton.icon(
icon: const Icon(Icons.replay_rounded, size: 16),
label: const Text('Pulse', style: TextStyle(fontSize: 12)),
onPressed: () {
final b = _brain;
if (b == null) return;
// A new overlay object restarts the pulse animation.
setState(() => _brain = null);
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted) setState(() => _brain = b);
});
},
),
];
case GraphMode.tree || GraphMode.timeline:
return const [];
}
}
Widget _body(BuildContext context) {
final colors = context.colors;
if (_error != null) {
return Center(child: Text('Could not load the graph: $_error'));
}
if (_mode == GraphMode.timeline) return const TimelineView();
final m = _model;
if (m == null) {
return const Center(
child: SizedBox(
width: 18,
height: 18,
child: CircularProgressIndicator(strokeWidth: 2),
),
);
}
if (_mode == GraphMode.tree) return TreeCanvas(model: m, onTap: _open);
final sub = _sub;
if (sub == null) return const SizedBox.shrink();
final app = AppScope.read(context);
final explore = _mode == GraphMode.local || _mode == GraphMode.brain;
return Stack(
children: [
Positioned.fill(
child: NetworkCanvas(
key: ValueKey(_mode),
sub: sub,
cache: app.graphPositions,
colorBy: _mode == GraphMode.clusters ? ColorBy.cluster : _colorBy,
hulls: _mode == GraphMode.clusters,
focus: explore ? _focus : null,
brain: _mode == GraphMode.brain ? _brain : null,
onTap: explore ? _setFocus : _open,
),
),
Positioned(
left: 20,
bottom: 14,
child: _Legend(
mode: _mode,
stats: '${sub.length} pages · ${sub.edges.length} links',
colors: colors,
),
),
if (explore)
Positioned(
right: 20,
bottom: 14,
child: Text(
'Click a node to focus it',
style: TextStyle(fontSize: 12, color: colors.faint),
),
),
],
);
}
}
class _Labeled extends StatelessWidget {
const _Labeled(this.label, this.child);
final String label;
final Widget child;
@override
Widget build(BuildContext context) => Row(
mainAxisSize: MainAxisSize.min,
children: [
Text(label, style: TextStyle(fontSize: 12, color: context.colors.muted)),
child,
],
);
}
class _Dropdown<T> extends StatelessWidget {
const _Dropdown({
required this.value,
required this.hint,
required this.items,
required this.onChanged,
});
final T value;
final String hint;
final Map<T, String> items;
final ValueChanged<T?> onChanged;
@override
Widget build(BuildContext context) => DropdownButtonHideUnderline(
child: DropdownButton<T>(
value: value,
hint: Text(hint),
isDense: true,
style: TextStyle(
fontFamily: uiFont,
fontSize: 12.5,
color: context.colors.ink,
),
borderRadius: BorderRadius.circular(8),
items: [
for (final e in items.entries)
DropdownMenuItem(value: e.key, child: Text(e.value)),
],
onChanged: onChanged,
),
);
}
class _FocusLink extends StatelessWidget {
const _FocusLink({required this.title, required this.onTap});
final String title;
final VoidCallback onTap;
@override
Widget build(BuildContext context) => ActionChip(
avatar: Icon(
Icons.open_in_new_rounded,
size: 14,
color: context.colors.accent,
),
label: Text(title, style: const TextStyle(fontSize: 12)),
onPressed: onTap,
visualDensity: VisualDensity.compact,
side: BorderSide(color: context.colors.line),
);
}
class _Legend extends StatelessWidget {
const _Legend({
required this.mode,
required this.stats,
required this.colors,
});
final GraphMode mode;
final String stats;
final SynapseColors colors;
@override
Widget build(BuildContext context) {
final palette = graphPalette(Theme.of(context).brightness);
Widget line(Color c, String label, {bool dashed = false, double w = 1.5}) =>
Padding(
padding: const EdgeInsets.only(right: 14),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
CustomPaint(
size: const Size(18, 8),
painter: _LegendLine(c, dashed, w),
),
const SizedBox(width: 5),
Text(
label,
style: TextStyle(fontSize: 11.5, color: colors.muted),
),
],
),
);
final items = mode == GraphMode.brain
? [
line(palette[3], 'Synapse (thicker = stronger)', w: 3),
line(colors.accent, 'Activation pulse', w: 3),
]
: [
line(colors.muted, 'Link'),
line(colors.accent, 'Tag'),
line(palette[2], 'Property'),
line(colors.ref, 'Block ref / embed'),
line(colors.faint, 'Mention', dashed: true),
];
return Container(
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6),
decoration: BoxDecoration(
color: colors.paper.withValues(alpha: 0.85),
borderRadius: BorderRadius.circular(8),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
...items,
Text(stats, style: TextStyle(fontSize: 11.5, color: colors.faint)),
],
),
);
}
}
class _LegendLine extends CustomPainter {
_LegendLine(this.color, this.dashed, this.width);
final Color color;
final bool dashed;
final double width;
@override
void paint(Canvas canvas, Size size) {
final p = Paint()
..color = color
..strokeWidth = width
..strokeCap = StrokeCap.round;
final y = size.height / 2;
if (!dashed) {
canvas.drawLine(Offset(0, y), Offset(size.width, y), p);
return;
}
for (var x = 0.0; x < size.width; x += 6) {
canvas.drawLine(Offset(x, y), Offset(math.min(x + 3, size.width), y), p);
}
}
@override
bool shouldRepaint(_LegendLine old) => old.color != color;
}
/// Neighbourhood of a page as a small panel (page view side column).
class LocalGraphPanel extends StatefulWidget {
const LocalGraphPanel({super.key, required this.pageId, this.height = 240});
final String pageId;
final double height;
@override
State<LocalGraphPanel> createState() => _LocalGraphPanelState();
}
class _LocalGraphPanelState extends State<LocalGraphPanel> {
GraphModel? _model;
SubGraph? _sub;
int _depth = 1;
Timer? _refresh;
late final AppState _app = AppScope.read(context);
@override
void initState() {
super.initState();
_load();
_app.queue.revision.addListener(_edited);
}
@override
void dispose() {
_app.queue.revision.removeListener(_edited);
_refresh?.cancel();
super.dispose();
}
/// Edits (e.g. a link typed on this page) refresh the panel once typing pauses.
void _edited() {
_refresh?.cancel();
_refresh = Timer(const Duration(milliseconds: 1500), _load);
}
void _load() {
loadGraphModel(_app).then((m) {
if (!mounted) return;
if (_model != null && _model!.data.seq == m.data.seq) return;
_model = m;
_build();
}, onError: (Object _) {});
}
void _build() {
final m = _model;
final f = m?.indexOf(widget.pageId);
if (m == null || f == null) return;
const kinds = {
EdgeKind.link,
EdgeKind.tag,
EdgeKind.property,
EdgeKind.blockRef,
EdgeKind.embed,
EdgeKind.mention,
};
final hood = m.neighbourhood(f, _depth, kinds).keys.toList();
setState(() => _sub = m.subgraph(hood, kinds));
}
@override
Widget build(BuildContext context) {
final colors = context.colors;
final app = AppScope.read(context);
final m = _model;
final sub = _sub;
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Text('LOCAL GRAPH', style: Theme.of(context).textTheme.labelSmall),
const Spacer(),
for (final d in [1, 2, 3])
InkWell(
borderRadius: BorderRadius.circular(4),
onTap: () {
_depth = d;
_build();
},
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: 5,
vertical: 2,
),
child: Text(
'$d',
style: TextStyle(
fontSize: 11.5,
fontWeight: d == _depth
? FontWeight.w700
: FontWeight.w400,
color: d == _depth ? colors.accent : colors.faint,
),
),
),
),
IconButton(
tooltip: 'Open in graph view',
visualDensity: VisualDensity.compact,
iconSize: 15,
color: colors.muted,
icon: const Icon(Icons.open_in_full_rounded),
onPressed: () =>
app.go(GraphRoute(GraphMode.local, focusId: widget.pageId)),
),
],
),
const SizedBox(height: 6),
Container(
height: widget.height,
decoration: BoxDecoration(
color: colors.surface,
borderRadius: BorderRadius.circular(10),
),
clipBehavior: Clip.antiAlias,
child: m == null || sub == null
? const SizedBox.shrink()
: sub.length <= 1
? Center(
child: Text(
'No connections yet',
style: TextStyle(fontSize: 12, color: colors.faint),
),
)
: NetworkCanvas(
sub: sub,
compact: true,
focus: m.indexOf(widget.pageId),
cache: app.graphPositions,
onTap: (g) => app.openId(m.node(g).id),
),
),
],
);
}
}
+17 -2
View File
@@ -7,6 +7,7 @@ import '../state/outline_controller.dart';
import '../theme/theme.dart';
import '../widgets/common.dart';
import '../widgets/dates.dart';
import 'graph_view.dart';
import 'journals_view.dart';
/// A single page: title, aliases, outline, linked references and related notes.
@@ -108,8 +109,15 @@ class _PageScreenState extends State<PageScreen> {
SliverToBoxAdapter(
child: _LinkedReferences(groups: _backlinks),
),
if (!wide)
if (!wide) ...[
SliverToBoxAdapter(child: RelatedPanel(related: _related)),
SliverToBoxAdapter(
child: Padding(
padding: const EdgeInsets.only(top: 40),
child: LocalGraphPanel(pageId: view.page.id),
),
),
],
const SliverToBoxAdapter(child: SizedBox(height: 120)),
],
),
@@ -128,7 +136,14 @@ class _PageScreenState extends State<PageScreen> {
),
child: SingleChildScrollView(
padding: const EdgeInsets.fromLTRB(20, 44, 20, 40),
child: RelatedPanel(related: _related, compact: true),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
LocalGraphPanel(pageId: view.page.id),
const SizedBox(height: 32),
RelatedPanel(related: _related, compact: true),
],
),
),
),
],
+20 -2
View File
@@ -8,7 +8,7 @@ import 'all_pages_view.dart';
import 'journals_view.dart';
import 'page_screen.dart';
import 'quick_switcher.dart';
import 'timeline_view.dart';
import 'graph_view.dart';
/// App frame: sidebar (navigation, recents, theme), top bar and the current view.
class Shell extends StatefulWidget {
@@ -51,6 +51,12 @@ class _ShellState extends State<Shell> {
shift: true,
): () =>
app.go(const JournalsRoute()),
const SingleActivator(
LogicalKeyboardKey.keyG,
control: true,
shift: true,
): () =>
app.go(const GraphRoute(GraphMode.network)),
const SingleActivator(
LogicalKeyboardKey.keyT,
control: true,
@@ -111,7 +117,13 @@ class _ShellState extends State<Shell> {
key: ValueKey((route, app.generation)),
child: switch (route) {
JournalsRoute() => const JournalsView(),
TimelineRoute() => const TimelineView(),
TimelineRoute() => const GraphView(
mode: GraphMode.timeline,
),
GraphRoute() => GraphView(
mode: route.mode,
focusId: route.focusId,
),
AllPagesRoute() => const AllPagesView(),
PageTarget() => PageScreen(target: route),
},
@@ -257,6 +269,12 @@ class _Sidebar extends StatelessWidget {
selected: route is JournalsRoute,
onTap: () => go(const JournalsRoute()),
),
_NavItem(
icon: Icons.hub_outlined,
label: 'Graph',
selected: route is GraphRoute,
onTap: () => go(const GraphRoute(GraphMode.network)),
),
_NavItem(
icon: Icons.timeline_rounded,
label: 'Timeline',