mirror of
https://github.com/Dasemu/Synapse.git
synced 2026-11-26 07:16:17 +00:00
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:
1 parent
6a4a76670b
commit
e43452f5af
29 files changed
+6177
-76
No files matched your search
@@ -0,0 +1,121 @@
|
||||
// Runs the real app (Rust core over FFI) on a graph and exercises every graph mode.
|
||||
// flutter test integration_test/graph_smoke_test.dart -d linux \
|
||||
// --dart-define=GRAPH=/path/to/copy/of/graph [--dart-define=SHOTS=/dir]
|
||||
// Use a copy: opening a graph may write to it (today's journal).
|
||||
import 'dart:io';
|
||||
import 'dart:ui' as ui;
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/scheduler.dart';
|
||||
import 'package:flutter/rendering.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:integration_test/integration_test.dart';
|
||||
import 'package:synapse/src/app.dart';
|
||||
import 'package:synapse/src/backend/graph_backend.dart';
|
||||
import 'package:synapse/src/graph/network_canvas.dart';
|
||||
import 'package:synapse/src/rust/frb_generated.dart';
|
||||
import 'package:synapse/src/state/app_state.dart';
|
||||
import 'package:synapse/src/views/shell.dart';
|
||||
|
||||
const graph = String.fromEnvironment('GRAPH');
|
||||
const shots = String.fromEnvironment('SHOTS');
|
||||
|
||||
Future<void> wait(WidgetTester tester, Duration d) async {
|
||||
final end = DateTime.now().add(d);
|
||||
while (DateTime.now().isBefore(end)) {
|
||||
await tester.pump(const Duration(milliseconds: 16));
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> shot(WidgetTester tester, String name) async {
|
||||
if (shots.isEmpty) return;
|
||||
final boundary = tester.renderObject<RenderRepaintBoundary>(
|
||||
find
|
||||
.ancestor(
|
||||
of: find.byType(Shell),
|
||||
matching: find.byType(RepaintBoundary),
|
||||
)
|
||||
.first,
|
||||
);
|
||||
final image = await boundary.toImage();
|
||||
final png = await image.toByteData(format: ui.ImageByteFormat.png);
|
||||
File('$shots/$name.png').writeAsBytesSync(png!.buffer.asUint8List());
|
||||
}
|
||||
|
||||
void main() {
|
||||
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
|
||||
|
||||
testWidgets('graph modes on a real graph', (tester) async {
|
||||
if (graph.isEmpty) {
|
||||
markTestSkipped('pass --dart-define=GRAPH=<dir>');
|
||||
return;
|
||||
}
|
||||
await RustLib.init();
|
||||
final backend = await FfiGraphBackend.open(graph);
|
||||
await tester.pumpWidget(SynapseApp(backend: backend));
|
||||
await wait(tester, const Duration(seconds: 1));
|
||||
final app = AppScope.read(tester.element(find.byType(Shell)));
|
||||
|
||||
final timings = <FrameTiming>[];
|
||||
void collect(List<FrameTiming> t) => timings.addAll(t);
|
||||
SchedulerBinding.instance.addTimingsCallback(collect);
|
||||
final watch = Stopwatch()..start();
|
||||
app.go(const GraphRoute(GraphMode.network));
|
||||
// Wait for the Rust layout to settle.
|
||||
while (watch.elapsed < const Duration(seconds: 20)) {
|
||||
await wait(tester, const Duration(milliseconds: 200));
|
||||
final c = find.byType(NetworkCanvas);
|
||||
if (c.evaluate().isNotEmpty &&
|
||||
tester.state<NetworkCanvasState>(c).settled) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
final canvas = tester.state<NetworkCanvasState>(find.byType(NetworkCanvas));
|
||||
expect(canvas.settled, isTrue, reason: 'layout settles');
|
||||
expect(canvas.nodeCount, greaterThan(0));
|
||||
debugPrint(
|
||||
'network: ${canvas.nodeCount} nodes settled in ${watch.elapsed}',
|
||||
);
|
||||
// Pan for a second to measure steady-state frames.
|
||||
timings.clear();
|
||||
final centre = tester.getCenter(find.byType(NetworkCanvas));
|
||||
final gesture = await tester.startGesture(centre + const Offset(0, 200));
|
||||
for (var i = 0; i < 60; i++) {
|
||||
await gesture.moveBy(const Offset(3, 1));
|
||||
await tester.pump(const Duration(milliseconds: 16));
|
||||
}
|
||||
await gesture.up();
|
||||
await wait(tester, const Duration(milliseconds: 300));
|
||||
SchedulerBinding.instance.removeTimingsCallback(collect);
|
||||
if (timings.isNotEmpty) {
|
||||
int us(Duration d) => d.inMicroseconds;
|
||||
final build = timings.map((t) => us(t.buildDuration)).toList()..sort();
|
||||
final raster = timings.map((t) => us(t.rasterDuration)).toList()..sort();
|
||||
String p(List<int> l, double q) =>
|
||||
'${(l[((l.length - 1) * q).round()] / 1000).toStringAsFixed(1)} ms';
|
||||
debugPrint(
|
||||
'frames ${timings.length}: build p50 ${p(build, .5)} p90 ${p(build, .9)}, '
|
||||
'raster p50 ${p(raster, .5)} p90 ${p(raster, .9)}',
|
||||
);
|
||||
}
|
||||
await shot(tester, 'app-network');
|
||||
|
||||
for (final mode in [
|
||||
'Local',
|
||||
'Synapses',
|
||||
'Clusters',
|
||||
'Namespaces',
|
||||
'Timeline',
|
||||
]) {
|
||||
await tester.tap(find.text(mode).last);
|
||||
await wait(tester, const Duration(seconds: 3));
|
||||
expect(tester.takeException(), isNull);
|
||||
await shot(tester, 'app-${mode.toLowerCase()}');
|
||||
}
|
||||
|
||||
// Page view with the local graph panel.
|
||||
app.openTitle(app.recent.isEmpty ? 'contents' : app.recent.first.title);
|
||||
await wait(tester, const Duration(seconds: 3));
|
||||
await shot(tester, 'app-page');
|
||||
});
|
||||
}
|
||||
@@ -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,
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
@@ -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];
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -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});
|
||||
|
||||
|
||||
@@ -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
@@ -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,
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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;
|
||||
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
|
||||
@@ -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',
|
||||
|
||||
@@ -89,11 +89,24 @@ packages:
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.2.0"
|
||||
file:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: file
|
||||
sha256: a3b4f84adafef897088c160faf7dfffb7696046cb13ae90b508c2cbc95d3b8d4
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "7.0.1"
|
||||
flutter:
|
||||
dependency: "direct main"
|
||||
description: flutter
|
||||
source: sdk
|
||||
version: "0.0.0"
|
||||
flutter_driver:
|
||||
dependency: "direct dev"
|
||||
description: flutter
|
||||
source: sdk
|
||||
version: "0.0.0"
|
||||
flutter_lints:
|
||||
dependency: "direct dev"
|
||||
description:
|
||||
@@ -120,6 +133,11 @@ packages:
|
||||
description: flutter
|
||||
source: sdk
|
||||
version: "0.0.0"
|
||||
fuchsia_remote_debug_protocol:
|
||||
dependency: transitive
|
||||
description: flutter
|
||||
source: sdk
|
||||
version: "0.0.0"
|
||||
hooks:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -128,6 +146,11 @@ packages:
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.0.2"
|
||||
integration_test:
|
||||
dependency: "direct dev"
|
||||
description: flutter
|
||||
source: sdk
|
||||
version: "0.0.0"
|
||||
jni:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -304,6 +327,14 @@ packages:
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.1.8"
|
||||
process:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: process
|
||||
sha256: "4242ba3508d37e01808bdf71ad1d5bb93a8d671bf2e7450e6b1b353fb0808891"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "5.0.6"
|
||||
pub_semver:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -364,6 +395,14 @@ packages:
|
||||
relative: true
|
||||
source: path
|
||||
version: "0.0.1"
|
||||
sync_http:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: sync_http
|
||||
sha256: "7f0cd72eca000d2e026bcd6f990b81d0ca06022ef4e32fb257b30d3d1014a961"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "0.3.1"
|
||||
term_glyph:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -476,6 +515,14 @@ packages:
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.1.1"
|
||||
webdriver:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: webdriver
|
||||
sha256: "28b82ec894fed45dd71c23ba62d1af973ed97dd59a4f5790a4d38b0b13e5657e"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "3.2.0"
|
||||
xdg_directories:
|
||||
dependency: transitive
|
||||
description:
|
||||
|
||||
@@ -18,6 +18,10 @@ dependencies:
|
||||
dev_dependencies:
|
||||
flutter_test:
|
||||
sdk: flutter
|
||||
integration_test:
|
||||
sdk: flutter
|
||||
flutter_driver:
|
||||
sdk: flutter
|
||||
flutter_lints: ^6.0.0
|
||||
|
||||
flutter:
|
||||
|
||||
@@ -0,0 +1,215 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:synapse/src/graph/graph_model.dart';
|
||||
import 'package:synapse/src/graph/network_canvas.dart';
|
||||
import 'package:synapse/src/graph/tree_canvas.dart';
|
||||
import 'package:synapse/src/state/app_state.dart';
|
||||
import 'package:synapse/src/theme/theme.dart';
|
||||
import 'package:synapse/src/views/graph_view.dart';
|
||||
import 'package:synapse/src/views/timeline_view.dart';
|
||||
|
||||
import 'support/memory_backend.dart';
|
||||
|
||||
MemoryBackend demo() {
|
||||
final b = MemoryBackend();
|
||||
final a = b.createPage('Alpha');
|
||||
b.seed(a.id, [(0, 'see [[Beta]] and [[proj/one]] #topic')]);
|
||||
final beta = b.createPage('Beta');
|
||||
b.seed(beta.id, [(0, 'back to [[Alpha]] #topic')]);
|
||||
b.createPage('Lonely');
|
||||
return b;
|
||||
}
|
||||
|
||||
Future<AppState> pumpGraph(WidgetTester tester, MemoryBackend b) async {
|
||||
tester.view.physicalSize = const Size(1600, 1000);
|
||||
tester.view.devicePixelRatio = 1;
|
||||
addTearDown(tester.view.reset);
|
||||
final app = AppState(b);
|
||||
await tester.pumpWidget(
|
||||
AppScope(
|
||||
state: app,
|
||||
child: MaterialApp(
|
||||
theme: buildTheme(Brightness.light),
|
||||
home: const Scaffold(body: GraphView()),
|
||||
),
|
||||
),
|
||||
);
|
||||
await settle(tester);
|
||||
return app;
|
||||
}
|
||||
|
||||
Future<void> settle(WidgetTester tester) async {
|
||||
for (var i = 0; i < 6; i++) {
|
||||
await tester.pump(const Duration(milliseconds: 50));
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> mode(WidgetTester tester, String label) async {
|
||||
await tester.tap(find.text(label));
|
||||
await settle(tester);
|
||||
}
|
||||
|
||||
NetworkCanvasState canvas(WidgetTester tester) =>
|
||||
tester.state<NetworkCanvasState>(find.byType(NetworkCanvas));
|
||||
|
||||
void main() {
|
||||
testWidgets('network mode shows pages and filters orphans', (tester) async {
|
||||
await pumpGraph(tester, demo());
|
||||
// Alpha, Beta, proj/one, topic, Lonely.
|
||||
expect(canvas(tester).nodeCount, 5);
|
||||
expect(find.textContaining('5 pages'), findsOneWidget);
|
||||
await tester.tap(find.text('Orphans'));
|
||||
await settle(tester);
|
||||
expect(canvas(tester).nodeCount, 4);
|
||||
await tester.tap(find.text('Orphans'));
|
||||
await settle(tester);
|
||||
expect(canvas(tester).nodeCount, 5);
|
||||
});
|
||||
|
||||
testWidgets('a filter change while the layout runs starts the new layout', (
|
||||
tester,
|
||||
) async {
|
||||
final b = demo()..layoutSteps = 6;
|
||||
tester.view.physicalSize = const Size(1600, 1000);
|
||||
tester.view.devicePixelRatio = 1;
|
||||
addTearDown(tester.view.reset);
|
||||
await tester.pumpWidget(
|
||||
AppScope(
|
||||
state: AppState(b),
|
||||
child: MaterialApp(
|
||||
theme: buildTheme(Brightness.light),
|
||||
home: const Scaffold(body: GraphView()),
|
||||
),
|
||||
),
|
||||
);
|
||||
// Let the first layout start, but not settle.
|
||||
await tester.pump(const Duration(milliseconds: 20));
|
||||
await tester.pump(const Duration(milliseconds: 20));
|
||||
expect(b.layouts, hasLength(1));
|
||||
expect(b.layouts.first.steps, lessThan(6));
|
||||
await tester.tap(find.text('Orphans'));
|
||||
await settle(tester);
|
||||
await settle(tester);
|
||||
expect(b.layouts, hasLength(2));
|
||||
expect(b.layouts.first.disposed, isTrue);
|
||||
expect(b.layouts.last.steps, greaterThanOrEqualTo(6));
|
||||
expect(canvas(tester).settled, isTrue);
|
||||
});
|
||||
|
||||
testWidgets('switches between every mode', (tester) async {
|
||||
await pumpGraph(tester, demo());
|
||||
|
||||
await mode(tester, 'Local');
|
||||
expect(find.byKey(const ValueKey('depth')), findsOneWidget);
|
||||
expect(find.byType(NetworkCanvas), findsOneWidget);
|
||||
|
||||
await mode(tester, 'Synapses');
|
||||
expect(find.text('Pulse'), findsOneWidget);
|
||||
expect(find.byType(NetworkCanvas), findsOneWidget);
|
||||
await tester.pump(const Duration(seconds: 2));
|
||||
|
||||
await mode(tester, 'Clusters');
|
||||
expect(find.byType(NetworkCanvas), findsOneWidget);
|
||||
|
||||
await mode(tester, 'Namespaces');
|
||||
expect(find.byType(TreeCanvas), findsOneWidget);
|
||||
expect(find.byType(NetworkCanvas), findsNothing);
|
||||
|
||||
await mode(tester, 'Timeline');
|
||||
expect(find.byType(TimelineView), findsOneWidget);
|
||||
|
||||
await mode(tester, 'Network');
|
||||
expect(find.byType(NetworkCanvas), findsOneWidget);
|
||||
await tester.pump(const Duration(seconds: 1));
|
||||
});
|
||||
|
||||
testWidgets('local mode follows the depth slider', (tester) async {
|
||||
final b = demo();
|
||||
// Chain Alpha – Beta – Gamma – Delta.
|
||||
final g = b.createPage('Gamma');
|
||||
b.seed(g.id, [(0, '[[Beta]] [[Delta]]')]);
|
||||
await pumpGraph(tester, b);
|
||||
await mode(tester, 'Local');
|
||||
// Focus is the highest-degree page until the user picks one; pick Delta.
|
||||
await tester.enterText(find.byType(TextField), 'Delta');
|
||||
await tester.testTextInput.receiveAction(TextInputAction.done);
|
||||
await settle(tester);
|
||||
expect(
|
||||
canvas(tester).nodeCount,
|
||||
3,
|
||||
reason: 'Delta, Gamma, Beta at depth 2',
|
||||
);
|
||||
final slider = tester.widget<Slider>(find.byKey(const ValueKey('depth')));
|
||||
slider.onChanged!(1);
|
||||
await settle(tester);
|
||||
expect(canvas(tester).nodeCount, 2);
|
||||
slider.onChanged!(3);
|
||||
await settle(tester);
|
||||
expect(canvas(tester).nodeCount, 5, reason: 'adds Alpha and topic');
|
||||
});
|
||||
|
||||
test('namespace tree groups a/b titles and tags', () async {
|
||||
final model = GraphModel(await demo().graphData());
|
||||
final root = buildNamespaceTree(model);
|
||||
final labels = root.children.map((c) => c.label).toList();
|
||||
expect(labels, ['Namespaces', 'Tags']);
|
||||
expect(root.children[0].children.single.label, 'proj');
|
||||
expect(root.children[0].children.single.children.single.label, 'one');
|
||||
final topic = root.children[1].children.single;
|
||||
expect(topic.label, '#topic');
|
||||
expect(topic.children.map((c) => c.label).toSet(), {'Alpha', 'Beta'});
|
||||
});
|
||||
|
||||
test('filter by tag, query and min degree', () async {
|
||||
final model = GraphModel(await demo().graphData());
|
||||
String t(int i) => model.node(i).title;
|
||||
final topic = model.indexOf(
|
||||
model.data.nodes.firstWhere((n) => n.title == 'topic').id,
|
||||
)!;
|
||||
expect(GraphFilter(tag: topic).apply(model).map(t).toSet(), {
|
||||
'Alpha',
|
||||
'Beta',
|
||||
'topic',
|
||||
});
|
||||
expect(const GraphFilter(query: 'alp').apply(model).map(t), ['Alpha']);
|
||||
expect(const GraphFilter(minDegree: 3).apply(model).map(t).toSet(), {
|
||||
'Alpha',
|
||||
});
|
||||
});
|
||||
|
||||
test('orphans are judged among the pages that are shown', () async {
|
||||
final b = demo();
|
||||
final model = GraphModel(await b.graphData());
|
||||
String t(int i) => model.node(i).title;
|
||||
// Only Alpha matches the query; its neighbours are filtered out, so with orphans
|
||||
// hidden nothing is left.
|
||||
expect(
|
||||
const GraphFilter(query: 'alpha', orphans: false).apply(model).map(t),
|
||||
isEmpty,
|
||||
);
|
||||
expect(
|
||||
const GraphFilter(query: 'a', orphans: false).apply(model).map(t).toSet(),
|
||||
{'Alpha', 'Beta'},
|
||||
);
|
||||
});
|
||||
|
||||
test('hull core drops stray members', () {
|
||||
final pts = [
|
||||
for (var i = 0; i < 10; i++) Offset(i.toDouble(), (i % 3).toDouble()),
|
||||
const Offset(500, 500),
|
||||
];
|
||||
expect(corePoints(pts), hasLength(10));
|
||||
});
|
||||
|
||||
test('convex hull keeps only the outline', () {
|
||||
final hull = convexHull(const [
|
||||
Offset(0, 0),
|
||||
Offset(10, 0),
|
||||
Offset(10, 10),
|
||||
Offset(0, 10),
|
||||
Offset(5, 5),
|
||||
]);
|
||||
expect(hull.length, 4);
|
||||
expect(hull.contains(const Offset(5, 5)), isFalse);
|
||||
});
|
||||
}
|
||||
@@ -1,4 +1,8 @@
|
||||
import 'dart:math' as math;
|
||||
import 'dart:typed_data';
|
||||
|
||||
import 'package:synapse/src/backend/graph_backend.dart';
|
||||
import 'package:synapse/src/graph/graph_model.dart';
|
||||
import 'package:synapse/src/state/outline_ops.dart';
|
||||
|
||||
/// In-memory [GraphBackend] for widget tests. Outline semantics reuse [OutlineOps], which
|
||||
@@ -275,4 +279,118 @@ class MemoryBackend implements GraphBackend {
|
||||
@override
|
||||
Future<AssetDto> putAssetFile(String path, {String? mime}) =>
|
||||
throw UnimplementedError();
|
||||
|
||||
/// Links (`[[x]]`) and tags (`#x`) between pages, built like the Rust side but simpler.
|
||||
@override
|
||||
Future<GraphData> graphData() async {
|
||||
final ids = pages.keys.toList();
|
||||
final index = {for (var i = 0; i < ids.length; i++) ids[i]: i};
|
||||
final s = <int>[], t = <int>[], k = <int>[];
|
||||
final link = RegExp(r'\[\[([^\]]+)\]\]');
|
||||
final tag = RegExp(r'(?:^|\s)#(\w+)');
|
||||
final degree = List.filled(ids.length, 0, growable: true);
|
||||
for (final id in List.of(ids)) {
|
||||
for (final n in outlines[id]!) {
|
||||
void add(String title, EdgeKind kind) {
|
||||
final p = _byTitle(title) ?? createPageForGraph(title, index, ids);
|
||||
s.add(index[id]!);
|
||||
t.add(index[p.id]!);
|
||||
k.add(kind.index);
|
||||
}
|
||||
|
||||
for (final m in link.allMatches(n.content)) {
|
||||
add(m.group(1)!, EdgeKind.link);
|
||||
}
|
||||
for (final m in tag.allMatches(n.content)) {
|
||||
add(m.group(1)!, EdgeKind.tag);
|
||||
}
|
||||
}
|
||||
}
|
||||
while (degree.length < ids.length) {
|
||||
degree.add(0);
|
||||
}
|
||||
for (var e = 0; e < s.length; e++) {
|
||||
degree[s[e]]++;
|
||||
degree[t[e]]++;
|
||||
}
|
||||
return GraphData(
|
||||
nodes: [
|
||||
for (var i = 0; i < ids.length; i++)
|
||||
GraphNode(
|
||||
id: ids[i],
|
||||
title: pages[ids[i]]!.title,
|
||||
journalDate: pages[ids[i]]!.journalDate,
|
||||
createdAt: 0,
|
||||
degree: degree[i],
|
||||
backlinks: 0,
|
||||
cluster: 0,
|
||||
),
|
||||
],
|
||||
sources: Uint32List.fromList(s),
|
||||
targets: Uint32List.fromList(t),
|
||||
kinds: Uint8List.fromList(k),
|
||||
weights: Float32List.fromList(List.filled(s.length, 1)),
|
||||
seq: 0,
|
||||
);
|
||||
}
|
||||
|
||||
PageDto createPageForGraph(
|
||||
String title,
|
||||
Map<String, int> index,
|
||||
List<String> ids,
|
||||
) {
|
||||
final p = createPage(title);
|
||||
index[p.id] = ids.length;
|
||||
ids.add(p.id);
|
||||
return p;
|
||||
}
|
||||
|
||||
final layouts = <FakeLayout>[];
|
||||
|
||||
/// Steps each fake layout needs before it reports settled.
|
||||
int layoutSteps = 1;
|
||||
|
||||
@override
|
||||
LayoutEngine createLayout(
|
||||
int nodeCount,
|
||||
Uint32List sources,
|
||||
Uint32List targets,
|
||||
Float32List weights, {
|
||||
Float32List? initial,
|
||||
}) {
|
||||
final l = FakeLayout(nodeCount, settleAfter: layoutSteps);
|
||||
layouts.add(l);
|
||||
return l;
|
||||
}
|
||||
}
|
||||
|
||||
/// Places nodes on a circle and is settled after `settleAfter` steps.
|
||||
class FakeLayout implements LayoutEngine {
|
||||
FakeLayout(this.n, {this.settleAfter = 1});
|
||||
final int n;
|
||||
final int settleAfter;
|
||||
int steps = 0;
|
||||
bool disposed = false;
|
||||
final pins = <int>[];
|
||||
|
||||
@override
|
||||
Future<(Float32List, double)> step(int iterations) async {
|
||||
steps++;
|
||||
final p = Float32List(2 * n);
|
||||
for (var i = 0; i < n; i++) {
|
||||
final a = 2 * math.pi * i / math.max(n, 1);
|
||||
p[2 * i] = 200 * math.cos(a);
|
||||
p[2 * i + 1] = 200 * math.sin(a);
|
||||
}
|
||||
return (p, steps >= settleAfter ? 0.0 : 0.5);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> pin(int index, double x, double y) async => pins.add(index);
|
||||
@override
|
||||
Future<void> unpin(int index) async {}
|
||||
@override
|
||||
Future<void> reheat(double alpha) async {}
|
||||
@override
|
||||
void dispose() => disposed = true;
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
import 'package:integration_test/integration_test_driver.dart';
|
||||
|
||||
Future<void> main() => integrationDriver();
|
||||
@@ -0,0 +1,56 @@
|
||||
//! Prints the page-level graph's size by edge kind and times extraction and layout.
|
||||
//! `cargo run --release -p synapse-ffi --example graph_stats -- /path/to/graph`
|
||||
|
||||
use synapse_ffi::api::graph::SynapseGraph;
|
||||
use synapse_ffi::api::layout::ForceLayout;
|
||||
|
||||
fn main() -> anyhow::Result<()> {
|
||||
let dir = std::env::args()
|
||||
.nth(1)
|
||||
.ok_or_else(|| anyhow::anyhow!("usage: graph_stats <graph dir>"))?;
|
||||
let g = SynapseGraph::open(dir)?;
|
||||
let t = std::time::Instant::now();
|
||||
let d = g.graph_data()?;
|
||||
let built = t.elapsed();
|
||||
let t = std::time::Instant::now();
|
||||
g.graph_data()?;
|
||||
let cached = t.elapsed();
|
||||
let mut by_kind = [0usize; 7];
|
||||
for &k in &d.kinds {
|
||||
by_kind[k as usize] += 1;
|
||||
}
|
||||
let journals = d.nodes.iter().filter(|n| n.journal_date.is_some()).count();
|
||||
let clusters = d.nodes.iter().map(|n| n.cluster).max().map_or(0, |c| c + 1);
|
||||
println!(
|
||||
"nodes {} ({journals} journals), edges {}, clusters {clusters}",
|
||||
d.nodes.len(),
|
||||
d.kinds.len()
|
||||
);
|
||||
let names = [
|
||||
"link",
|
||||
"tag",
|
||||
"property",
|
||||
"block_ref",
|
||||
"embed",
|
||||
"mention",
|
||||
"synapse",
|
||||
];
|
||||
for (n, c) in names.iter().zip(by_kind) {
|
||||
println!(" {n:<10} {c}");
|
||||
}
|
||||
println!("build {built:?}, cached {cached:?}");
|
||||
let mut l = ForceLayout::new(
|
||||
d.nodes.len() as u32,
|
||||
d.sources.clone(),
|
||||
d.targets.clone(),
|
||||
d.weights.clone(),
|
||||
None,
|
||||
);
|
||||
let t = std::time::Instant::now();
|
||||
let mut ticks = 0;
|
||||
while l.step(10).alpha > 0.0 {
|
||||
ticks += 10;
|
||||
}
|
||||
println!("layout settled after ~{ticks} ticks in {:?}", t.elapsed());
|
||||
Ok(())
|
||||
}
|
||||
@@ -169,3 +169,57 @@ pub struct BlockHit {
|
||||
pub content: String,
|
||||
pub page_title: String,
|
||||
}
|
||||
|
||||
/// Kind codes of [`GraphData::kinds`].
|
||||
pub mod edge_kind {
|
||||
pub const LINK: u8 = 0;
|
||||
pub const TAG: u8 = 1;
|
||||
pub const PROPERTY: u8 = 2;
|
||||
pub const BLOCK_REF: u8 = 3;
|
||||
pub const EMBED: u8 = 4;
|
||||
/// Unlinked reference: the target's title appears in the source's text.
|
||||
pub const MENTION: u8 = 5;
|
||||
/// Hebbian association (undirected), weight = decayed synapse strength.
|
||||
pub const SYNAPSE: u8 = 6;
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct GraphNode {
|
||||
pub id: String,
|
||||
pub title: String,
|
||||
pub journal_date: Option<String>,
|
||||
pub origin_journal: Option<String>,
|
||||
pub created_at: i64,
|
||||
/// Distinct neighbours over structural edges (links, tags, properties, block refs).
|
||||
pub degree: u32,
|
||||
/// Distinct pages referencing this one.
|
||||
pub backlinks: u32,
|
||||
/// Community (Louvain), numbered by size: 0 is the largest.
|
||||
pub cluster: u32,
|
||||
/// Node index of the tag this page uses most, if any.
|
||||
pub primary_tag: Option<u32>,
|
||||
}
|
||||
|
||||
/// 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`).
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct GraphData {
|
||||
pub nodes: Vec<GraphNode>,
|
||||
pub sources: Vec<u32>,
|
||||
pub targets: Vec<u32>,
|
||||
/// See [`edge_kind`].
|
||||
pub kinds: Vec<u8>,
|
||||
/// Number of references (structural edges) or synapse strength.
|
||||
pub weights: Vec<f32>,
|
||||
/// Op-log sequence the data was built at.
|
||||
pub seq: i64,
|
||||
}
|
||||
|
||||
/// One batch of layout iterations.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct LayoutFrame {
|
||||
/// `x0, y0, x1, y1, ...`
|
||||
pub positions: Vec<f32>,
|
||||
/// Remaining "temperature"; the layout is settled when it reaches 0.
|
||||
pub alpha: f32,
|
||||
}
|
||||
@@ -16,6 +16,8 @@ use uuid::Uuid;
|
||||
/// same shape `synapse-sync`'s `SyncClient` takes, so a sync client can share it.
|
||||
pub struct SynapseGraph {
|
||||
graph: Arc<Mutex<Graph>>,
|
||||
/// Page-level graph for the graph views, keyed by what invalidates it.
|
||||
pub(crate) graph_cache: Mutex<Option<(super::graph_view::CacheKey, Arc<GraphData>)>>,
|
||||
}
|
||||
|
||||
impl SynapseGraph {
|
||||
@@ -24,6 +26,7 @@ impl SynapseGraph {
|
||||
let graph = Graph::open(&dir).with_context(|| format!("opening graph at {dir}"))?;
|
||||
Ok(SynapseGraph {
|
||||
graph: Arc::new(Mutex::new(graph)),
|
||||
graph_cache: Mutex::new(None),
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,613 @@
|
||||
//! The page-level graph behind the graph views: every page as a node and every relation
|
||||
//! between pages as an edge (links, tags, property refs, block refs and embeds aggregated per
|
||||
//! page, unlinked mentions and synapses), plus degree, backlinks, clusters and primary tags.
|
||||
//!
|
||||
//! Built with a few read-only queries over the core tables and cached; the cache key is the
|
||||
//! op-log sequence plus the synapse table's state (visits fire synapses without logging ops).
|
||||
|
||||
use super::dto::{GraphData, GraphNode, edge_kind};
|
||||
use super::graph::SynapseGraph;
|
||||
use anyhow::Result;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::sync::Arc;
|
||||
use synapse_core::synapse::HALF_LIFE_MS;
|
||||
use synapse_core::{Graph, title_key};
|
||||
|
||||
/// What invalidates the cached graph.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct CacheKey {
|
||||
seq: i64,
|
||||
synapses: i64,
|
||||
synapse_last: i64,
|
||||
/// Synapse weights decay with time: rebuild at least hourly.
|
||||
hour: i64,
|
||||
}
|
||||
|
||||
/// Synapses weaker than this are not drawn.
|
||||
const MIN_SYNAPSE: f32 = 0.05;
|
||||
/// Titles shorter than this are too ambiguous to detect as mentions.
|
||||
const MIN_MENTION_LEN: usize = 3;
|
||||
|
||||
impl SynapseGraph {
|
||||
/// The whole page-level graph (journals included; the UI filters). Cached until the
|
||||
/// graph changes.
|
||||
pub fn graph_data(&self) -> Result<GraphData> {
|
||||
let g = self.lock();
|
||||
let key = cache_key(&g)?;
|
||||
let mut cache = self.graph_cache.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if let Some((k, data)) = cache.as_ref()
|
||||
&& *k == key
|
||||
{
|
||||
return Ok(GraphData::clone(data));
|
||||
}
|
||||
let data = Arc::new(build(&g, key.seq)?);
|
||||
*cache = Some((key, Arc::clone(&data)));
|
||||
Ok(GraphData::clone(&data))
|
||||
}
|
||||
}
|
||||
|
||||
fn cache_key(g: &Graph) -> Result<CacheKey> {
|
||||
let (synapses, synapse_last) = g.conn().query_row(
|
||||
"SELECT count(*), coalesce(max(last_fired), 0) FROM synapses",
|
||||
[],
|
||||
|r| Ok((r.get::<_, i64>(0)?, r.get::<_, i64>(1)?)),
|
||||
)?;
|
||||
Ok(CacheKey {
|
||||
seq: g.last_seq()?,
|
||||
synapses,
|
||||
synapse_last,
|
||||
hour: g.now_ms() / 3_600_000,
|
||||
})
|
||||
}
|
||||
|
||||
struct Builder {
|
||||
edges: HashMap<(u32, u32, u8), f32>,
|
||||
}
|
||||
|
||||
impl Builder {
|
||||
fn add(&mut self, s: u32, t: u32, kind: u8, w: f32) {
|
||||
if s != t {
|
||||
*self.edges.entry((s, t, kind)).or_default() += w;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn build(g: &Graph, seq: i64) -> Result<GraphData> {
|
||||
let conn = g.conn();
|
||||
|
||||
// Nodes.
|
||||
let mut nodes = Vec::new();
|
||||
let mut index: HashMap<String, u32> = HashMap::new();
|
||||
{
|
||||
let mut st = conn.prepare(
|
||||
"SELECT id, title, journal_date, origin_journal, created_at FROM pages
|
||||
ORDER BY journal_date IS NOT NULL, created_at",
|
||||
)?;
|
||||
let rows = st.query_map([], |r| {
|
||||
Ok((
|
||||
r.get::<_, String>(0)?,
|
||||
r.get::<_, String>(1)?,
|
||||
r.get::<_, Option<String>>(2)?,
|
||||
r.get::<_, Option<String>>(3)?,
|
||||
r.get::<_, i64>(4)?,
|
||||
))
|
||||
})?;
|
||||
for row in rows {
|
||||
let (id, title, journal_date, origin_journal, created_at) = row?;
|
||||
index.insert(id.clone(), nodes.len() as u32);
|
||||
nodes.push(GraphNode {
|
||||
id,
|
||||
title,
|
||||
journal_date,
|
||||
origin_journal,
|
||||
created_at,
|
||||
degree: 0,
|
||||
backlinks: 0,
|
||||
cluster: 0,
|
||||
primary_tag: None,
|
||||
});
|
||||
}
|
||||
}
|
||||
// Title and alias keys resolve page refs (refs are stored by normalised title).
|
||||
let mut by_key: HashMap<String, u32> = HashMap::new();
|
||||
for (t, id) in g.all_titles()? {
|
||||
if let Some(&i) = index.get(&id.to_string()) {
|
||||
by_key.entry(title_key(&t)).or_insert(i);
|
||||
}
|
||||
}
|
||||
|
||||
let mut b = Builder {
|
||||
edges: HashMap::new(),
|
||||
};
|
||||
|
||||
// Page refs: links, tags, property refs.
|
||||
{
|
||||
let mut st = conn.prepare(
|
||||
"SELECT b.page_id, r.target_key, r.kind FROM refs r JOIN blocks b ON b.id = r.block_id",
|
||||
)?;
|
||||
let rows = st.query_map([], |r| {
|
||||
Ok((
|
||||
r.get::<_, String>(0)?,
|
||||
r.get::<_, String>(1)?,
|
||||
r.get::<_, String>(2)?,
|
||||
))
|
||||
})?;
|
||||
for row in rows {
|
||||
let (page, key, kind) = row?;
|
||||
let (Some(&s), Some(&t)) = (index.get(&page), by_key.get(&key)) else {
|
||||
continue;
|
||||
};
|
||||
let kind = match kind.as_str() {
|
||||
"tag" => edge_kind::TAG,
|
||||
"property" => edge_kind::PROPERTY,
|
||||
_ => edge_kind::LINK,
|
||||
};
|
||||
b.add(s, t, kind, 1.0);
|
||||
}
|
||||
}
|
||||
|
||||
// Block refs and embeds, aggregated to the pages of both blocks.
|
||||
{
|
||||
let mut st = conn.prepare(
|
||||
"SELECT src.page_id, dst.page_id, r.embed FROM block_refs r
|
||||
JOIN blocks src ON src.id = r.block_id JOIN blocks dst ON dst.id = r.target_block",
|
||||
)?;
|
||||
let rows = st.query_map([], |r| {
|
||||
Ok((
|
||||
r.get::<_, String>(0)?,
|
||||
r.get::<_, String>(1)?,
|
||||
r.get::<_, bool>(2)?,
|
||||
))
|
||||
})?;
|
||||
for row in rows {
|
||||
let (sp, tp, embed) = row?;
|
||||
if let (Some(&s), Some(&t)) = (index.get(&sp), index.get(&tp)) {
|
||||
let kind = if embed {
|
||||
edge_kind::EMBED
|
||||
} else {
|
||||
edge_kind::BLOCK_REF
|
||||
};
|
||||
b.add(s, t, kind, 1.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Explicitly related pairs (any direction), so mentions only add new information.
|
||||
let linked: HashSet<(u32, u32)> = b
|
||||
.edges
|
||||
.keys()
|
||||
.flat_map(|&(s, t, _)| [(s, t), (t, s)])
|
||||
.collect();
|
||||
mentions(g, &nodes, &index, &linked, &mut b)?;
|
||||
|
||||
// Synapses (undirected), decayed to now.
|
||||
{
|
||||
let now = g.now_ms();
|
||||
let mut st = conn.prepare("SELECT a, b, weight, last_fired FROM synapses")?;
|
||||
let rows = st.query_map([], |r| {
|
||||
Ok((
|
||||
r.get::<_, String>(0)?,
|
||||
r.get::<_, String>(1)?,
|
||||
r.get::<_, f64>(2)?,
|
||||
r.get::<_, i64>(3)?,
|
||||
))
|
||||
})?;
|
||||
for row in rows {
|
||||
let (a, bb, w, last) = row?;
|
||||
let w = (w * 0.5f64.powf((now - last).max(0) as f64 / HALF_LIFE_MS)) as f32;
|
||||
if let (Some(&x), Some(&y)) = (index.get(&a), index.get(&bb))
|
||||
&& w >= MIN_SYNAPSE
|
||||
{
|
||||
b.add(x.min(y), x.max(y), edge_kind::SYNAPSE, w);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Stable edge order (sources, then targets, then kind).
|
||||
let mut edges: Vec<((u32, u32, u8), f32)> = b.edges.into_iter().collect();
|
||||
edges.sort_by_key(|&(k, _)| k);
|
||||
|
||||
// Degree, backlinks and primary tags over structural edges.
|
||||
let n = nodes.len();
|
||||
let mut neigh: Vec<HashSet<u32>> = vec![HashSet::new(); n];
|
||||
let mut referrers: Vec<HashSet<u32>> = vec![HashSet::new(); n];
|
||||
let mut tag_use: Vec<HashMap<u32, f32>> = vec![HashMap::new(); n];
|
||||
for &((s, t, k), w) in &edges {
|
||||
if k == edge_kind::MENTION || k == edge_kind::SYNAPSE {
|
||||
continue;
|
||||
}
|
||||
neigh[s as usize].insert(t);
|
||||
neigh[t as usize].insert(s);
|
||||
referrers[t as usize].insert(s);
|
||||
if k == edge_kind::TAG {
|
||||
*tag_use[s as usize].entry(t).or_default() += w;
|
||||
}
|
||||
}
|
||||
let clusters = communities(&neigh);
|
||||
for (i, node) in nodes.iter_mut().enumerate() {
|
||||
node.degree = neigh[i].len() as u32;
|
||||
node.backlinks = referrers[i].len() as u32;
|
||||
node.cluster = clusters[i];
|
||||
node.primary_tag = tag_use[i]
|
||||
.iter()
|
||||
.max_by(|a, b| a.1.total_cmp(b.1).then(b.0.cmp(a.0)))
|
||||
.map(|(&t, _)| t);
|
||||
}
|
||||
|
||||
let mut out = GraphData {
|
||||
nodes,
|
||||
sources: Vec::with_capacity(edges.len()),
|
||||
targets: Vec::with_capacity(edges.len()),
|
||||
kinds: Vec::with_capacity(edges.len()),
|
||||
weights: Vec::with_capacity(edges.len()),
|
||||
seq,
|
||||
};
|
||||
for ((s, t, k), w) in edges {
|
||||
out.sources.push(s);
|
||||
out.targets.push(t);
|
||||
out.kinds.push(k);
|
||||
out.weights.push(w);
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Unlinked references: a non-journal page title (or alias) appearing as whole words in a
|
||||
/// block of another page that does not already reference it. Titles are indexed by their
|
||||
/// first word so each block is scanned once.
|
||||
fn mentions(
|
||||
g: &Graph,
|
||||
nodes: &[GraphNode],
|
||||
index: &HashMap<String, u32>,
|
||||
linked: &HashSet<(u32, u32)>,
|
||||
b: &mut Builder,
|
||||
) -> Result<()> {
|
||||
let mut by_first: HashMap<String, Vec<(String, u32)>> = HashMap::new();
|
||||
for (t, id) in g.all_titles()? {
|
||||
let Some(&i) = index.get(&id.to_string()) else {
|
||||
continue;
|
||||
};
|
||||
if nodes[i as usize].journal_date.is_some() {
|
||||
continue;
|
||||
}
|
||||
let key = title_key(&t);
|
||||
if key.chars().count() < MIN_MENTION_LEN {
|
||||
continue;
|
||||
}
|
||||
let first = key
|
||||
.split(|c: char| !c.is_alphanumeric())
|
||||
.next()
|
||||
.unwrap_or("");
|
||||
if first.is_empty() {
|
||||
continue;
|
||||
}
|
||||
by_first
|
||||
.entry(first.to_string())
|
||||
.or_default()
|
||||
.push((key, i));
|
||||
}
|
||||
if by_first.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let mut st = g.conn().prepare("SELECT page_id, content FROM blocks")?;
|
||||
let rows = st.query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?)))?;
|
||||
let mut found: HashSet<(u32, u32)> = HashSet::new();
|
||||
for row in rows {
|
||||
let (page, content) = row?;
|
||||
let Some(&s) = index.get(&page) else { continue };
|
||||
let text = strip_markup(&content.to_lowercase());
|
||||
let bytes = text.as_bytes();
|
||||
let mut i = 0;
|
||||
while i < text.len() {
|
||||
let start_ok = i == 0 || !is_word(text[..i].chars().next_back().unwrap());
|
||||
if start_ok && text.is_char_boundary(i) {
|
||||
let rest = &text[i..];
|
||||
let word_end = rest
|
||||
.find(|c: char| !c.is_alphanumeric())
|
||||
.unwrap_or(rest.len());
|
||||
if word_end > 0
|
||||
&& let Some(cands) = by_first.get(&rest[..word_end])
|
||||
{
|
||||
for (key, t) in cands {
|
||||
if *t == s || !rest.starts_with(key.as_str()) {
|
||||
continue;
|
||||
}
|
||||
let after = rest[key.len()..].chars().next();
|
||||
if after.is_some_and(is_word) {
|
||||
continue;
|
||||
}
|
||||
if !linked.contains(&(s, *t)) && found.insert((s, *t)) {
|
||||
b.add(s, *t, edge_kind::MENTION, 1.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Next char boundary.
|
||||
i += 1;
|
||||
while i < bytes.len() && !text.is_char_boundary(i) {
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn is_word(c: char) -> bool {
|
||||
c.is_alphanumeric()
|
||||
}
|
||||
|
||||
/// Blanks out explicit references (`[[..]]`, `#tag`, `((..))`, code) so their text is not
|
||||
/// counted again as a mention. Keeps byte offsets irrelevant: output is only scanned.
|
||||
fn strip_markup(s: &str) -> String {
|
||||
let mut out = String::with_capacity(s.len());
|
||||
let mut rest = s;
|
||||
while !rest.is_empty() {
|
||||
if let Some(r) = rest.strip_prefix("#[[") {
|
||||
let end = r.find("]]").map(|e| e + 2).unwrap_or(r.len());
|
||||
rest = &r[end..];
|
||||
out.push(' ');
|
||||
} else if let Some(r) = rest.strip_prefix("[[") {
|
||||
let end = r.find("]]").map(|e| e + 2).unwrap_or(r.len());
|
||||
rest = &r[end..];
|
||||
out.push(' ');
|
||||
} else if let Some(r) = rest.strip_prefix("((") {
|
||||
let end = r.find("))").map(|e| e + 2).unwrap_or(r.len());
|
||||
rest = &r[end..];
|
||||
out.push(' ');
|
||||
} else if let Some(r) = rest.strip_prefix('`') {
|
||||
let end = r.find('`').map(|e| e + 1).unwrap_or(r.len());
|
||||
rest = &r[end..];
|
||||
out.push(' ');
|
||||
} else if rest.starts_with('#') && out.chars().next_back().is_none_or(|c| c.is_whitespace())
|
||||
{
|
||||
let end = rest.find(|c: char| c.is_whitespace()).unwrap_or(rest.len());
|
||||
rest = &rest[end..];
|
||||
out.push(' ');
|
||||
} else {
|
||||
let c = rest.chars().next().unwrap();
|
||||
out.push(c);
|
||||
rest = &rest[c.len_utf8()..];
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Communities by Louvain modularity optimisation (local moving + aggregation, in node
|
||||
/// index order, so results are deterministic). Clusters are renumbered by size, largest
|
||||
/// first; isolated pages are singleton clusters.
|
||||
fn communities(neigh: &[HashSet<u32>]) -> Vec<u32> {
|
||||
let n = neigh.len();
|
||||
// Current level graph: weighted adjacency (no self loops) and node strength.
|
||||
let mut adj: Vec<HashMap<u32, f64>> = neigh
|
||||
.iter()
|
||||
.map(|s| s.iter().map(|&j| (j, 1.0)).collect())
|
||||
.collect();
|
||||
let mut strength: Vec<f64> = adj.iter().map(|a| a.values().sum()).collect();
|
||||
let m2: f64 = strength.iter().sum();
|
||||
// Community of each original node.
|
||||
let mut member: Vec<u32> = (0..n as u32).collect();
|
||||
if m2 == 0.0 {
|
||||
return rank_by_size(&member);
|
||||
}
|
||||
loop {
|
||||
let size = adj.len();
|
||||
let mut comm: Vec<u32> = (0..size as u32).collect();
|
||||
let mut tot: Vec<f64> = strength.clone();
|
||||
let mut moved_any = false;
|
||||
for _ in 0..20 {
|
||||
let mut moved = false;
|
||||
for i in 0..size {
|
||||
let ki = strength[i];
|
||||
let old = comm[i];
|
||||
tot[old as usize] -= ki;
|
||||
let mut links: HashMap<u32, f64> = HashMap::new();
|
||||
for (&j, &w) in &adj[i] {
|
||||
*links.entry(comm[j as usize]).or_default() += w;
|
||||
}
|
||||
let gain = |c: u32, kin: f64| kin - tot[c as usize] * ki / m2;
|
||||
let mut best = old;
|
||||
let mut best_gain = gain(old, links.get(&old).copied().unwrap_or(0.0));
|
||||
let mut cands: Vec<(u32, f64)> = links.into_iter().collect();
|
||||
cands.sort_by_key(|&(c, _)| c);
|
||||
for (c, kin) in cands {
|
||||
let g = gain(c, kin);
|
||||
if g > best_gain + 1e-12 {
|
||||
best = c;
|
||||
best_gain = g;
|
||||
}
|
||||
}
|
||||
comm[i] = best;
|
||||
tot[best as usize] += ki;
|
||||
if best != old {
|
||||
moved = true;
|
||||
moved_any = true;
|
||||
}
|
||||
}
|
||||
if !moved {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if !moved_any {
|
||||
break;
|
||||
}
|
||||
// Aggregate communities into nodes.
|
||||
let mut renum: HashMap<u32, u32> = HashMap::new();
|
||||
for &c in &comm {
|
||||
let next = renum.len() as u32;
|
||||
renum.entry(c).or_insert(next);
|
||||
}
|
||||
let k = renum.len();
|
||||
let mut next_adj: Vec<HashMap<u32, f64>> = vec![HashMap::new(); k];
|
||||
let mut next_strength = vec![0.0; k];
|
||||
for i in 0..size {
|
||||
let ci = renum[&comm[i]];
|
||||
next_strength[ci as usize] += strength[i];
|
||||
for (&j, &w) in &adj[i] {
|
||||
let cj = renum[&comm[j as usize]];
|
||||
if ci != cj {
|
||||
*next_adj[ci as usize].entry(cj).or_default() += w;
|
||||
}
|
||||
}
|
||||
}
|
||||
for m in member.iter_mut() {
|
||||
*m = renum[&comm[*m as usize]];
|
||||
}
|
||||
if k == size {
|
||||
break;
|
||||
}
|
||||
adj = next_adj;
|
||||
strength = next_strength;
|
||||
}
|
||||
rank_by_size(&member)
|
||||
}
|
||||
|
||||
fn rank_by_size(label: &[u32]) -> Vec<u32> {
|
||||
let mut size: HashMap<u32, u32> = HashMap::new();
|
||||
for &l in label {
|
||||
*size.entry(l).or_default() += 1;
|
||||
}
|
||||
let mut order: Vec<(u32, u32)> = size.into_iter().collect();
|
||||
order.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(&b.0)));
|
||||
let rank: HashMap<u32, u32> = order
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(r, &(l, _))| (l, r as u32))
|
||||
.collect();
|
||||
label.iter().map(|l| rank[l]).collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::api::dto::{Place, PlaceKind};
|
||||
|
||||
fn open() -> (tempfile::TempDir, SynapseGraph) {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let g = SynapseGraph::open(dir.path().to_string_lossy().into_owned()).unwrap();
|
||||
(dir, g)
|
||||
}
|
||||
|
||||
fn add(g: &SynapseGraph, page: &str, content: &str) -> String {
|
||||
let p = g.open_page(page.into()).unwrap().page.id;
|
||||
let place = Place {
|
||||
kind: PlaceKind::LastChildOf,
|
||||
anchor: None,
|
||||
};
|
||||
g.insert_block(p, place, content.into()).unwrap().id
|
||||
}
|
||||
|
||||
fn edges(d: &GraphData) -> Vec<(String, String, u8)> {
|
||||
let t = |i: u32| d.nodes[i as usize].title.clone();
|
||||
let mut v: Vec<_> = (0..d.kinds.len())
|
||||
.map(|e| (t(d.sources[e]), t(d.targets[e]), d.kinds[e]))
|
||||
.collect();
|
||||
v.sort();
|
||||
v
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extracts_every_relation_kind_at_page_level() {
|
||||
let (_d, g) = open();
|
||||
let target = add(&g, "Rust", "a systems language");
|
||||
add(&g, "Notes", "learning [[Rust]] and #lang");
|
||||
add(&g, "Notes", "type:: [[Book]]");
|
||||
add(&g, "Notes", &format!("see (({target}))"));
|
||||
add(&g, "Notes", &format!("{{{{embed (({target}))}}}}"));
|
||||
add(&g, "Diary", "talked about rust and lang today");
|
||||
let d = g.graph_data().unwrap();
|
||||
let e = edges(&d);
|
||||
let has = |s: &str, t: &str, k: u8| e.contains(&(s.into(), t.into(), k));
|
||||
assert!(has("Notes", "Rust", edge_kind::LINK));
|
||||
assert!(has("Notes", "lang", edge_kind::TAG));
|
||||
assert!(has("Notes", "Book", edge_kind::PROPERTY));
|
||||
assert!(has("Notes", "Rust", edge_kind::BLOCK_REF));
|
||||
assert!(has("Notes", "Rust", edge_kind::EMBED));
|
||||
assert!(has("Diary", "Rust", edge_kind::MENTION));
|
||||
assert!(has("Diary", "lang", edge_kind::MENTION));
|
||||
// Explicit links are not repeated as mentions; titles do not mention themselves.
|
||||
assert!(!has("Notes", "Rust", edge_kind::MENTION));
|
||||
assert!(!has("Rust", "Rust", edge_kind::MENTION));
|
||||
|
||||
let node = |t: &str| d.nodes.iter().find(|n| n.title == t).unwrap();
|
||||
assert_eq!(node("Rust").backlinks, 1);
|
||||
assert_eq!(node("Notes").degree, 3);
|
||||
let lang = d.nodes.iter().position(|n| n.title == "lang").unwrap() as u32;
|
||||
assert_eq!(node("Notes").primary_tag, Some(lang));
|
||||
assert!(node("Notes").journal_date.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mentions_need_whole_words_and_skip_code_and_links() {
|
||||
let (_d, g) = open();
|
||||
add(&g, "Go", "language");
|
||||
add(&g, "Gopher", "");
|
||||
add(&g, "A", "going to `gopher` and [[x gopher y]] gopherish");
|
||||
let d = g.graph_data().unwrap();
|
||||
assert!(
|
||||
!edges(&d)
|
||||
.iter()
|
||||
.any(|(s, _, k)| s == "A" && *k == edge_kind::MENTION)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mentions_skip_reverse_links_and_multiword_tags() {
|
||||
let (_d, g) = open();
|
||||
add(&g, "Alpha", "about beta things");
|
||||
add(&g, "Beta", "back to [[Alpha]]");
|
||||
add(&g, "Gamma Ray", "");
|
||||
add(&g, "Delta", "#[[Gamma Ray]] burst");
|
||||
add(&g, "Ray", "");
|
||||
let d = g.graph_data().unwrap();
|
||||
let e = edges(&d);
|
||||
let mention = |s: &str, t: &str| e.contains(&(s.into(), t.into(), edge_kind::MENTION));
|
||||
assert!(!mention("Alpha", "Beta"), "already linked the other way");
|
||||
assert!(!mention("Delta", "Ray"), "tag text is not a mention");
|
||||
assert!(!mention("Delta", "Gamma Ray"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cache_is_invalidated_by_edits_and_visits() {
|
||||
let (_d, g) = open();
|
||||
add(&g, "A", "[[B]]");
|
||||
let d1 = g.graph_data().unwrap();
|
||||
assert_eq!(g.graph_data().unwrap(), d1, "cached");
|
||||
add(&g, "A", "[[C]]");
|
||||
let d2 = g.graph_data().unwrap();
|
||||
assert!(d2.seq > d1.seq);
|
||||
assert!(d2.nodes.iter().any(|n| n.title == "C"));
|
||||
|
||||
let a = g.page_by_title("A".into()).unwrap().unwrap().page.id;
|
||||
let c = g.page_by_title("C".into()).unwrap().unwrap().page.id;
|
||||
let syn = |d: &GraphData| {
|
||||
(0..d.kinds.len())
|
||||
.filter(|&e| d.kinds[e] == edge_kind::SYNAPSE)
|
||||
.map(|e| d.weights[e])
|
||||
.sum::<f32>()
|
||||
};
|
||||
let before = syn(&d2);
|
||||
g.record_visit(Some(a), c).unwrap();
|
||||
let d3 = g.graph_data().unwrap();
|
||||
assert!(syn(&d3) > before, "visits strengthen synapses");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clusters_follow_communities() {
|
||||
let (_d, g) = open();
|
||||
for (p, links) in [
|
||||
("a1", "[[a2]] [[a3]]"),
|
||||
("a2", "[[a3]]"),
|
||||
("b1", "[[b2]] [[b3]] [[b4]]"),
|
||||
("b2", "[[b3]] [[b4]]"),
|
||||
("b3", "[[b4]]"),
|
||||
] {
|
||||
add(&g, p, links);
|
||||
}
|
||||
let d = g.graph_data().unwrap();
|
||||
let c = |t: &str| d.nodes.iter().find(|n| n.title == t).unwrap().cluster;
|
||||
assert_eq!(c("a1"), c("a2"));
|
||||
assert_eq!(c("a2"), c("a3"));
|
||||
assert_eq!(c("b1"), c("b4"));
|
||||
assert_ne!(c("a1"), c("b1"));
|
||||
assert_eq!(c("b1"), 0, "largest community first");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,403 @@
|
||||
//! Force-directed layout (d3-force style): many-body repulsion approximated with a Barnes-Hut
|
||||
//! quadtree (O(n log n)), springs on edges, a weak pull to the origin and velocity damping
|
||||
//! with a cooling `alpha`. Dart owns one [`ForceLayout`] per view and calls [`ForceLayout::step`]
|
||||
//! repeatedly; each call runs on a Rust worker thread, so the UI never blocks.
|
||||
|
||||
use super::dto::LayoutFrame;
|
||||
use flutter_rust_bridge::frb;
|
||||
|
||||
const THETA2: f32 = 0.81; // Barnes-Hut opening criterion θ = 0.9, squared.
|
||||
const ALPHA_MIN: f32 = 0.001;
|
||||
const ALPHA_DECAY: f32 = 0.0228; // ≈ 300 iterations from 1 to ALPHA_MIN.
|
||||
const VELOCITY_DECAY: f32 = 0.4;
|
||||
const CENTER_STRENGTH: f32 = 0.02;
|
||||
const MAX_LEAF_DEPTH: u32 = 24;
|
||||
|
||||
#[frb(opaque)]
|
||||
pub struct ForceLayout {
|
||||
pos: Vec<[f32; 2]>,
|
||||
vel: Vec<[f32; 2]>,
|
||||
pinned: Vec<Option<[f32; 2]>>,
|
||||
/// (source, target, rest length, strength, bias)
|
||||
links: Vec<(u32, u32, f32, f32, f32)>,
|
||||
charge: f32,
|
||||
alpha: f32,
|
||||
alpha_target: f32,
|
||||
tree: Vec<Cell>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
struct Cell {
|
||||
x0: f32,
|
||||
y0: f32,
|
||||
size: f32,
|
||||
/// Centre of mass and mass (number of bodies).
|
||||
cx: f32,
|
||||
cy: f32,
|
||||
mass: f32,
|
||||
/// Index of the first of four children, or 0 for a leaf.
|
||||
child: u32,
|
||||
/// Body stored in a leaf (`u32::MAX` when empty or internal).
|
||||
body: u32,
|
||||
}
|
||||
|
||||
impl Cell {
|
||||
fn new(x0: f32, y0: f32, size: f32) -> Self {
|
||||
Cell {
|
||||
x0,
|
||||
y0,
|
||||
size,
|
||||
cx: 0.0,
|
||||
cy: 0.0,
|
||||
mass: 0.0,
|
||||
child: 0,
|
||||
body: u32::MAX,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ForceLayout {
|
||||
/// 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.
|
||||
#[frb(sync)]
|
||||
pub fn new(
|
||||
node_count: u32,
|
||||
sources: Vec<u32>,
|
||||
targets: Vec<u32>,
|
||||
weights: Vec<f32>,
|
||||
initial: Option<Vec<f32>>,
|
||||
) -> ForceLayout {
|
||||
let n = node_count as usize;
|
||||
let mut pos = Vec::with_capacity(n);
|
||||
for i in 0..n {
|
||||
match initial.as_ref() {
|
||||
Some(p) if p.len() >= 2 * n && p[2 * i].is_finite() && p[2 * i + 1].is_finite() => {
|
||||
pos.push([p[2 * i], p[2 * i + 1]])
|
||||
}
|
||||
_ => {
|
||||
// d3's phyllotaxis arrangement: even density, deterministic.
|
||||
let r = 10.0 * (0.5 + i as f32).sqrt();
|
||||
let a = i as f32 * std::f32::consts::PI * (3.0 - 5f32.sqrt());
|
||||
pos.push([r * a.cos(), r * a.sin()]);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut degree = vec![0u32; n];
|
||||
let edges: Vec<(u32, u32, f32)> = sources
|
||||
.iter()
|
||||
.zip(&targets)
|
||||
.enumerate()
|
||||
.filter(|(_, (s, t))| (**s as usize) < n && (**t as usize) < n && s != t)
|
||||
.map(|(e, (&s, &t))| (s, t, weights.get(e).copied().unwrap_or(1.0)))
|
||||
.collect();
|
||||
for &(s, t, _) in &edges {
|
||||
degree[s as usize] += 1;
|
||||
degree[t as usize] += 1;
|
||||
}
|
||||
let links = edges
|
||||
.iter()
|
||||
.map(|&(s, t, w)| {
|
||||
let (ds, dt) = (degree[s as usize] as f32, degree[t as usize] as f32);
|
||||
let strength = w.clamp(0.2, 3.0) / ds.min(dt).max(1.0);
|
||||
(s, t, 34.0, strength, ds / (ds + dt))
|
||||
})
|
||||
.collect();
|
||||
ForceLayout {
|
||||
pos,
|
||||
vel: vec![[0.0; 2]; n],
|
||||
pinned: vec![None; n],
|
||||
links,
|
||||
charge: -45.0,
|
||||
alpha: if initial.is_some() { 0.3 } else { 1.0 },
|
||||
alpha_target: 0.0,
|
||||
tree: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs up to `iterations` ticks (stops early once settled).
|
||||
pub fn step(&mut self, iterations: u32) -> LayoutFrame {
|
||||
for _ in 0..iterations {
|
||||
if self.alpha < ALPHA_MIN && self.alpha_target == 0.0 {
|
||||
break;
|
||||
}
|
||||
self.tick();
|
||||
}
|
||||
LayoutFrame {
|
||||
positions: self.pos.iter().flat_map(|p| [p[0], p[1]]).collect(),
|
||||
alpha: if self.alpha < ALPHA_MIN {
|
||||
0.0
|
||||
} else {
|
||||
self.alpha
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Holds node `index` at `(x, y)` (while dragging) and keeps the layout warm.
|
||||
pub fn pin(&mut self, index: u32, x: f32, y: f32) {
|
||||
if let Some(p) = self.pinned.get_mut(index as usize) {
|
||||
*p = Some([x, y]);
|
||||
self.pos[index as usize] = [x, y];
|
||||
self.alpha_target = 0.3;
|
||||
self.alpha = self.alpha.max(0.3);
|
||||
}
|
||||
}
|
||||
|
||||
/// Releases a pinned node and lets the layout cool down again.
|
||||
pub fn unpin(&mut self, index: u32) {
|
||||
if let Some(p) = self.pinned.get_mut(index as usize) {
|
||||
*p = None;
|
||||
}
|
||||
self.alpha_target = 0.0;
|
||||
}
|
||||
|
||||
/// Restarts the simulation at temperature `alpha` (0..1).
|
||||
pub fn reheat(&mut self, alpha: f32) {
|
||||
self.alpha = alpha.clamp(0.0, 1.0);
|
||||
}
|
||||
|
||||
fn tick(&mut self) {
|
||||
self.alpha += (self.alpha_target - self.alpha) * ALPHA_DECAY;
|
||||
let alpha = self.alpha;
|
||||
// Springs.
|
||||
for &(s, t, len, strength, bias) in &self.links {
|
||||
let (s, t) = (s as usize, t as usize);
|
||||
let mut dx = self.pos[t][0] + self.vel[t][0] - self.pos[s][0] - self.vel[s][0];
|
||||
let mut dy = self.pos[t][1] + self.vel[t][1] - self.pos[s][1] - self.vel[s][1];
|
||||
if dx == 0.0 && dy == 0.0 {
|
||||
dx = 1e-3 * (s as f32 - t as f32).signum();
|
||||
dy = 1e-3;
|
||||
}
|
||||
let l = (dx * dx + dy * dy).sqrt();
|
||||
let k = (l - len) / l * alpha * strength;
|
||||
dx *= k;
|
||||
dy *= k;
|
||||
self.vel[t][0] -= dx * bias;
|
||||
self.vel[t][1] -= dy * bias;
|
||||
self.vel[s][0] += dx * (1.0 - bias);
|
||||
self.vel[s][1] += dy * (1.0 - bias);
|
||||
}
|
||||
// Many-body repulsion (Barnes-Hut).
|
||||
self.build_tree();
|
||||
for i in 0..self.pos.len() {
|
||||
let (fx, fy) = self.repulsion(i);
|
||||
self.vel[i][0] += fx * alpha;
|
||||
self.vel[i][1] += fy * alpha;
|
||||
}
|
||||
// Centre pull, damping, integration, pins.
|
||||
for i in 0..self.pos.len() {
|
||||
self.vel[i][0] -= self.pos[i][0] * CENTER_STRENGTH * alpha;
|
||||
self.vel[i][1] -= self.pos[i][1] * CENTER_STRENGTH * alpha;
|
||||
if let Some(p) = self.pinned[i] {
|
||||
self.pos[i] = p;
|
||||
self.vel[i] = [0.0; 2];
|
||||
continue;
|
||||
}
|
||||
self.vel[i][0] *= 1.0 - VELOCITY_DECAY;
|
||||
self.vel[i][1] *= 1.0 - VELOCITY_DECAY;
|
||||
self.pos[i][0] += self.vel[i][0];
|
||||
self.pos[i][1] += self.vel[i][1];
|
||||
}
|
||||
}
|
||||
|
||||
fn build_tree(&mut self) {
|
||||
self.tree.clear();
|
||||
if self.pos.is_empty() {
|
||||
return;
|
||||
}
|
||||
let (mut x0, mut y0, mut x1, mut y1) = (f32::MAX, f32::MAX, f32::MIN, f32::MIN);
|
||||
for p in &self.pos {
|
||||
x0 = x0.min(p[0]);
|
||||
y0 = y0.min(p[1]);
|
||||
x1 = x1.max(p[0]);
|
||||
y1 = y1.max(p[1]);
|
||||
}
|
||||
let size = (x1 - x0).max(y1 - y0).max(1.0) * 1.0001;
|
||||
self.tree.push(Cell::new(x0, y0, size));
|
||||
for i in 0..self.pos.len() {
|
||||
self.insert(0, i as u32, 0);
|
||||
}
|
||||
self.accumulate(0);
|
||||
}
|
||||
|
||||
fn quadrant(c: &Cell, p: [f32; 2]) -> u32 {
|
||||
let h = c.size / 2.0;
|
||||
(if p[0] >= c.x0 + h { 1 } else { 0 }) + (if p[1] >= c.y0 + h { 2 } else { 0 })
|
||||
}
|
||||
|
||||
fn split(&mut self, cell: usize) {
|
||||
let c = self.tree[cell];
|
||||
let h = c.size / 2.0;
|
||||
let first = self.tree.len() as u32;
|
||||
for q in 0..4 {
|
||||
let x = c.x0 + if q & 1 == 1 { h } else { 0.0 };
|
||||
let y = c.y0 + if q & 2 == 2 { h } else { 0.0 };
|
||||
self.tree.push(Cell::new(x, y, h));
|
||||
}
|
||||
self.tree[cell].child = first;
|
||||
}
|
||||
|
||||
fn insert(&mut self, cell: usize, body: u32, depth: u32) {
|
||||
let c = self.tree[cell];
|
||||
if c.child == 0 {
|
||||
if c.body == u32::MAX && c.mass == 0.0 {
|
||||
self.tree[cell].body = body;
|
||||
self.tree[cell].mass = 1.0;
|
||||
return;
|
||||
}
|
||||
if depth >= MAX_LEAF_DEPTH {
|
||||
// Coincident points: keep them in one leaf, they are handled by mass.
|
||||
self.tree[cell].mass += 1.0;
|
||||
return;
|
||||
}
|
||||
let old = c.body;
|
||||
self.tree[cell].body = u32::MAX;
|
||||
self.tree[cell].mass = 0.0;
|
||||
self.split(cell);
|
||||
if old != u32::MAX {
|
||||
let q = Self::quadrant(&self.tree[cell], self.pos[old as usize]);
|
||||
let child = (self.tree[cell].child + q) as usize;
|
||||
self.insert(child, old, depth + 1);
|
||||
}
|
||||
}
|
||||
let q = Self::quadrant(&self.tree[cell], self.pos[body as usize]);
|
||||
let child = (self.tree[cell].child + q) as usize;
|
||||
self.insert(child, body, depth + 1);
|
||||
}
|
||||
|
||||
fn accumulate(&mut self, cell: usize) {
|
||||
let c = self.tree[cell];
|
||||
if c.child == 0 {
|
||||
if c.body != u32::MAX {
|
||||
let p = self.pos[c.body as usize];
|
||||
self.tree[cell].cx = p[0];
|
||||
self.tree[cell].cy = p[1];
|
||||
}
|
||||
return;
|
||||
}
|
||||
let (mut m, mut x, mut y) = (0.0, 0.0, 0.0);
|
||||
for q in 0..4 {
|
||||
let k = (c.child + q) as usize;
|
||||
self.accumulate(k);
|
||||
let ch = self.tree[k];
|
||||
m += ch.mass;
|
||||
x += ch.cx * ch.mass;
|
||||
y += ch.cy * ch.mass;
|
||||
}
|
||||
self.tree[cell].mass = m;
|
||||
if m > 0.0 {
|
||||
self.tree[cell].cx = x / m;
|
||||
self.tree[cell].cy = y / m;
|
||||
}
|
||||
}
|
||||
|
||||
fn repulsion(&self, i: usize) -> (f32, f32) {
|
||||
let p = self.pos[i];
|
||||
let (mut fx, mut fy) = (0.0, 0.0);
|
||||
let mut stack = vec![0usize];
|
||||
while let Some(k) = stack.pop() {
|
||||
let c = &self.tree[k];
|
||||
if c.mass == 0.0 {
|
||||
continue;
|
||||
}
|
||||
let dx = c.cx - p[0];
|
||||
let dy = c.cy - p[1];
|
||||
let mut d2 = dx * dx + dy * dy;
|
||||
let far = c.child != 0 && c.size * c.size < THETA2 * d2;
|
||||
if c.child == 0 || far {
|
||||
if c.child == 0 && c.body == i as u32 && c.mass <= 1.0 {
|
||||
continue;
|
||||
}
|
||||
if d2 < 1.0 {
|
||||
// Jiggle overlapping nodes apart deterministically.
|
||||
d2 = 1.0;
|
||||
}
|
||||
let mass = if c.child == 0 && c.body == i as u32 {
|
||||
c.mass - 1.0
|
||||
} else {
|
||||
c.mass
|
||||
};
|
||||
let w = self.charge * mass / d2;
|
||||
let (dx, dy) = if dx == 0.0 && dy == 0.0 {
|
||||
let a = i as f32 * 2.399_963;
|
||||
(a.cos(), a.sin())
|
||||
} else {
|
||||
(dx, dy)
|
||||
};
|
||||
fx += dx * w;
|
||||
fy += dy * w;
|
||||
} else {
|
||||
for q in 0..4 {
|
||||
stack.push((c.child + q) as usize);
|
||||
}
|
||||
}
|
||||
}
|
||||
(fx, fy)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn dist(p: &[f32], a: usize, b: usize) -> f32 {
|
||||
((p[2 * a] - p[2 * b]).powi(2) + (p[2 * a + 1] - p[2 * b + 1]).powi(2)).sqrt()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn linked_nodes_end_closer_than_unlinked_and_layout_settles() {
|
||||
// Two triangles joined by nothing.
|
||||
let s = vec![0, 1, 2, 3, 4, 5];
|
||||
let t = vec![1, 2, 0, 4, 5, 3];
|
||||
let mut l = ForceLayout::new(6, s, t, vec![1.0; 6], None);
|
||||
let mut f = l.step(50);
|
||||
for _ in 0..20 {
|
||||
if f.alpha == 0.0 {
|
||||
break;
|
||||
}
|
||||
f = l.step(50);
|
||||
}
|
||||
assert_eq!(f.alpha, 0.0, "settles");
|
||||
let p = &f.positions;
|
||||
assert!(p.iter().all(|v| v.is_finite()));
|
||||
assert!(dist(p, 0, 1) < dist(p, 0, 3));
|
||||
assert!(dist(p, 3, 4) < dist(p, 2, 5));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pins_hold_and_coincident_points_separate() {
|
||||
let n = 200;
|
||||
let initial = vec![5.0; 2 * n];
|
||||
let mut l = ForceLayout::new(n as u32, vec![], vec![], vec![], Some(initial));
|
||||
l.pin(7, 100.0, -50.0);
|
||||
let f = l.step(100);
|
||||
assert_eq!((f.positions[14], f.positions[15]), (100.0, -50.0));
|
||||
assert!(f.positions.iter().all(|v| v.is_finite()));
|
||||
let spread = (0..n)
|
||||
.map(|i| dist(&f.positions, i, 0))
|
||||
.fold(0.0f32, f32::max);
|
||||
assert!(spread > 20.0, "repulsion pushes stacked nodes apart");
|
||||
l.unpin(7);
|
||||
l.reheat(0.5);
|
||||
assert!(l.step(1).alpha > 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn handles_five_thousand_nodes_quickly() {
|
||||
let n = 5000u32;
|
||||
let (mut s, mut t) = (Vec::new(), Vec::new());
|
||||
for i in 0..n {
|
||||
for k in [1, 7, 31, 101] {
|
||||
s.push(i);
|
||||
t.push((i * 13 + k) % n);
|
||||
}
|
||||
}
|
||||
let w = vec![1.0; s.len()];
|
||||
let mut l = ForceLayout::new(n, s, t, w, None);
|
||||
let start = std::time::Instant::now();
|
||||
let f = l.step(10);
|
||||
assert!(f.positions.iter().all(|v| v.is_finite()));
|
||||
// Generous bound for debug builds on CI.
|
||||
assert!(start.elapsed().as_secs_f32() < 20.0);
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,8 @@
|
||||
//! - `graph`: the opaque [`graph::SynapseGraph`] handle and read-side queries.
|
||||
//! - `outline`: block editing (insert, update, move, indent/outdent, merge, delete).
|
||||
//! - `search`: title/block lookup (stopgap until `synapse-search` is wired).
|
||||
//! - `graph_view`: the whole page-level graph for the graph views (cached by op seq).
|
||||
//! - `layout`: Barnes-Hut force-directed layout, stepped from Dart off the UI thread.
|
||||
//!
|
||||
//! Extension points for Phase 2 (one module each, methods on `SynapseGraph` or their own
|
||||
//! opaque handles): `ai` (synapse-ai), `history` (synapse-history), `caldav`
|
||||
@@ -11,5 +13,7 @@
|
||||
|
||||
pub mod dto;
|
||||
pub mod graph;
|
||||
pub mod graph_view;
|
||||
pub mod layout;
|
||||
pub mod outline;
|
||||
pub mod search;
|
||||
@@ -28,6 +28,7 @@
|
||||
// Section: imports
|
||||
|
||||
use crate::api::graph::*;
|
||||
use crate::api::layout::*;
|
||||
use flutter_rust_bridge::for_generated::byteorder::{NativeEndian, ReadBytesExt, WriteBytesExt};
|
||||
use flutter_rust_bridge::for_generated::{transform_result_dco, Lifetimeable, Lockable};
|
||||
use flutter_rust_bridge::{Handler, IntoIntoDart};
|
||||
@@ -40,7 +41,7 @@ flutter_rust_bridge::frb_generated_boilerplate!(
|
||||
default_rust_auto_opaque = RustAutoOpaqueMoi,
|
||||
);
|
||||
pub(crate) const FLUTTER_RUST_BRIDGE_CODEGEN_VERSION: &str = "2.13.0";
|
||||
pub(crate) const FLUTTER_RUST_BRIDGE_CODEGEN_CONTENT_HASH: i32 = 1980668428;
|
||||
pub(crate) const FLUTTER_RUST_BRIDGE_CODEGEN_CONTENT_HASH: i32 = -553305025;
|
||||
|
||||
// Section: executor
|
||||
|
||||
@@ -48,6 +49,262 @@ flutter_rust_bridge::frb_generated_default_handler!();
|
||||
|
||||
// Section: wire_funcs
|
||||
|
||||
fn wire__crate__api__layout__ForceLayout_new_impl(
|
||||
ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr,
|
||||
rust_vec_len_: i32,
|
||||
data_len_: i32,
|
||||
) -> flutter_rust_bridge::for_generated::WireSyncRust2DartSse {
|
||||
FLUTTER_RUST_BRIDGE_HANDLER.wrap_sync::<flutter_rust_bridge::for_generated::SseCodec, _>(
|
||||
flutter_rust_bridge::for_generated::TaskInfo {
|
||||
debug_name: "ForceLayout_new",
|
||||
port: None,
|
||||
mode: flutter_rust_bridge::for_generated::FfiCallMode::Sync,
|
||||
},
|
||||
move || {
|
||||
let message = unsafe {
|
||||
flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire(
|
||||
ptr_,
|
||||
rust_vec_len_,
|
||||
data_len_,
|
||||
)
|
||||
};
|
||||
let mut deserializer =
|
||||
flutter_rust_bridge::for_generated::SseDeserializer::new(message);
|
||||
let api_node_count = <u32>::sse_decode(&mut deserializer);
|
||||
let api_sources = <Vec<u32>>::sse_decode(&mut deserializer);
|
||||
let api_targets = <Vec<u32>>::sse_decode(&mut deserializer);
|
||||
let api_weights = <Vec<f32>>::sse_decode(&mut deserializer);
|
||||
let api_initial = <Option<Vec<f32>>>::sse_decode(&mut deserializer);
|
||||
deserializer.end();
|
||||
transform_result_sse::<_, ()>((move || {
|
||||
let output_ok = Ok::<_, ()>(crate::api::layout::ForceLayout::new(
|
||||
api_node_count,
|
||||
api_sources,
|
||||
api_targets,
|
||||
api_weights,
|
||||
api_initial,
|
||||
))?;
|
||||
std::result::Result::Ok(output_ok)
|
||||
})())
|
||||
},
|
||||
)
|
||||
}
|
||||
fn wire__crate__api__layout__ForceLayout_pin_impl(
|
||||
port_: flutter_rust_bridge::for_generated::MessagePort,
|
||||
ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr,
|
||||
rust_vec_len_: i32,
|
||||
data_len_: i32,
|
||||
) {
|
||||
FLUTTER_RUST_BRIDGE_HANDLER.wrap_normal::<flutter_rust_bridge::for_generated::SseCodec, _, _>(
|
||||
flutter_rust_bridge::for_generated::TaskInfo {
|
||||
debug_name: "ForceLayout_pin",
|
||||
port: Some(port_),
|
||||
mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal,
|
||||
},
|
||||
move || {
|
||||
let message = unsafe {
|
||||
flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire(
|
||||
ptr_,
|
||||
rust_vec_len_,
|
||||
data_len_,
|
||||
)
|
||||
};
|
||||
let mut deserializer =
|
||||
flutter_rust_bridge::for_generated::SseDeserializer::new(message);
|
||||
let api_that = <RustOpaqueMoi<
|
||||
flutter_rust_bridge::for_generated::RustAutoOpaqueInner<ForceLayout>,
|
||||
>>::sse_decode(&mut deserializer);
|
||||
let api_index = <u32>::sse_decode(&mut deserializer);
|
||||
let api_x = <f32>::sse_decode(&mut deserializer);
|
||||
let api_y = <f32>::sse_decode(&mut deserializer);
|
||||
deserializer.end();
|
||||
move |context| {
|
||||
transform_result_sse::<_, ()>((move || {
|
||||
let mut api_that_guard = None;
|
||||
let decode_indices_ =
|
||||
flutter_rust_bridge::for_generated::lockable_compute_decode_order(vec![
|
||||
flutter_rust_bridge::for_generated::LockableOrderInfo::new(
|
||||
&api_that, 0, true,
|
||||
),
|
||||
]);
|
||||
for i in decode_indices_ {
|
||||
match i {
|
||||
0 => api_that_guard = Some(api_that.lockable_decode_sync_ref_mut()),
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
let mut api_that_guard = api_that_guard.unwrap();
|
||||
let output_ok = Ok::<_, ()>({
|
||||
crate::api::layout::ForceLayout::pin(
|
||||
&mut *api_that_guard,
|
||||
api_index,
|
||||
api_x,
|
||||
api_y,
|
||||
);
|
||||
})?;
|
||||
std::result::Result::Ok(output_ok)
|
||||
})())
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
fn wire__crate__api__layout__ForceLayout_reheat_impl(
|
||||
port_: flutter_rust_bridge::for_generated::MessagePort,
|
||||
ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr,
|
||||
rust_vec_len_: i32,
|
||||
data_len_: i32,
|
||||
) {
|
||||
FLUTTER_RUST_BRIDGE_HANDLER.wrap_normal::<flutter_rust_bridge::for_generated::SseCodec, _, _>(
|
||||
flutter_rust_bridge::for_generated::TaskInfo {
|
||||
debug_name: "ForceLayout_reheat",
|
||||
port: Some(port_),
|
||||
mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal,
|
||||
},
|
||||
move || {
|
||||
let message = unsafe {
|
||||
flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire(
|
||||
ptr_,
|
||||
rust_vec_len_,
|
||||
data_len_,
|
||||
)
|
||||
};
|
||||
let mut deserializer =
|
||||
flutter_rust_bridge::for_generated::SseDeserializer::new(message);
|
||||
let api_that = <RustOpaqueMoi<
|
||||
flutter_rust_bridge::for_generated::RustAutoOpaqueInner<ForceLayout>,
|
||||
>>::sse_decode(&mut deserializer);
|
||||
let api_alpha = <f32>::sse_decode(&mut deserializer);
|
||||
deserializer.end();
|
||||
move |context| {
|
||||
transform_result_sse::<_, ()>((move || {
|
||||
let mut api_that_guard = None;
|
||||
let decode_indices_ =
|
||||
flutter_rust_bridge::for_generated::lockable_compute_decode_order(vec![
|
||||
flutter_rust_bridge::for_generated::LockableOrderInfo::new(
|
||||
&api_that, 0, true,
|
||||
),
|
||||
]);
|
||||
for i in decode_indices_ {
|
||||
match i {
|
||||
0 => api_that_guard = Some(api_that.lockable_decode_sync_ref_mut()),
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
let mut api_that_guard = api_that_guard.unwrap();
|
||||
let output_ok = Ok::<_, ()>({
|
||||
crate::api::layout::ForceLayout::reheat(&mut *api_that_guard, api_alpha);
|
||||
})?;
|
||||
std::result::Result::Ok(output_ok)
|
||||
})())
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
fn wire__crate__api__layout__ForceLayout_step_impl(
|
||||
port_: flutter_rust_bridge::for_generated::MessagePort,
|
||||
ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr,
|
||||
rust_vec_len_: i32,
|
||||
data_len_: i32,
|
||||
) {
|
||||
FLUTTER_RUST_BRIDGE_HANDLER.wrap_normal::<flutter_rust_bridge::for_generated::SseCodec, _, _>(
|
||||
flutter_rust_bridge::for_generated::TaskInfo {
|
||||
debug_name: "ForceLayout_step",
|
||||
port: Some(port_),
|
||||
mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal,
|
||||
},
|
||||
move || {
|
||||
let message = unsafe {
|
||||
flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire(
|
||||
ptr_,
|
||||
rust_vec_len_,
|
||||
data_len_,
|
||||
)
|
||||
};
|
||||
let mut deserializer =
|
||||
flutter_rust_bridge::for_generated::SseDeserializer::new(message);
|
||||
let api_that = <RustOpaqueMoi<
|
||||
flutter_rust_bridge::for_generated::RustAutoOpaqueInner<ForceLayout>,
|
||||
>>::sse_decode(&mut deserializer);
|
||||
let api_iterations = <u32>::sse_decode(&mut deserializer);
|
||||
deserializer.end();
|
||||
move |context| {
|
||||
transform_result_sse::<_, ()>((move || {
|
||||
let mut api_that_guard = None;
|
||||
let decode_indices_ =
|
||||
flutter_rust_bridge::for_generated::lockable_compute_decode_order(vec![
|
||||
flutter_rust_bridge::for_generated::LockableOrderInfo::new(
|
||||
&api_that, 0, true,
|
||||
),
|
||||
]);
|
||||
for i in decode_indices_ {
|
||||
match i {
|
||||
0 => api_that_guard = Some(api_that.lockable_decode_sync_ref_mut()),
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
let mut api_that_guard = api_that_guard.unwrap();
|
||||
let output_ok = Ok::<_, ()>(crate::api::layout::ForceLayout::step(
|
||||
&mut *api_that_guard,
|
||||
api_iterations,
|
||||
))?;
|
||||
std::result::Result::Ok(output_ok)
|
||||
})())
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
fn wire__crate__api__layout__ForceLayout_unpin_impl(
|
||||
port_: flutter_rust_bridge::for_generated::MessagePort,
|
||||
ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr,
|
||||
rust_vec_len_: i32,
|
||||
data_len_: i32,
|
||||
) {
|
||||
FLUTTER_RUST_BRIDGE_HANDLER.wrap_normal::<flutter_rust_bridge::for_generated::SseCodec, _, _>(
|
||||
flutter_rust_bridge::for_generated::TaskInfo {
|
||||
debug_name: "ForceLayout_unpin",
|
||||
port: Some(port_),
|
||||
mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal,
|
||||
},
|
||||
move || {
|
||||
let message = unsafe {
|
||||
flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire(
|
||||
ptr_,
|
||||
rust_vec_len_,
|
||||
data_len_,
|
||||
)
|
||||
};
|
||||
let mut deserializer =
|
||||
flutter_rust_bridge::for_generated::SseDeserializer::new(message);
|
||||
let api_that = <RustOpaqueMoi<
|
||||
flutter_rust_bridge::for_generated::RustAutoOpaqueInner<ForceLayout>,
|
||||
>>::sse_decode(&mut deserializer);
|
||||
let api_index = <u32>::sse_decode(&mut deserializer);
|
||||
deserializer.end();
|
||||
move |context| {
|
||||
transform_result_sse::<_, ()>((move || {
|
||||
let mut api_that_guard = None;
|
||||
let decode_indices_ =
|
||||
flutter_rust_bridge::for_generated::lockable_compute_decode_order(vec![
|
||||
flutter_rust_bridge::for_generated::LockableOrderInfo::new(
|
||||
&api_that, 0, true,
|
||||
),
|
||||
]);
|
||||
for i in decode_indices_ {
|
||||
match i {
|
||||
0 => api_that_guard = Some(api_that.lockable_decode_sync_ref_mut()),
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
let mut api_that_guard = api_that_guard.unwrap();
|
||||
let output_ok = Ok::<_, ()>({
|
||||
crate::api::layout::ForceLayout::unpin(&mut *api_that_guard, api_index);
|
||||
})?;
|
||||
std::result::Result::Ok(output_ok)
|
||||
})())
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
fn wire__crate__api__graph__SynapseGraph_add_alias_impl(
|
||||
port_: flutter_rust_bridge::for_generated::MessagePort,
|
||||
ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr,
|
||||
@@ -473,6 +730,58 @@ fn wire__crate__api__graph__SynapseGraph_dir_impl(
|
||||
},
|
||||
)
|
||||
}
|
||||
fn wire__crate__api__graph__SynapseGraph_graph_data_impl(
|
||||
port_: flutter_rust_bridge::for_generated::MessagePort,
|
||||
ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr,
|
||||
rust_vec_len_: i32,
|
||||
data_len_: i32,
|
||||
) {
|
||||
FLUTTER_RUST_BRIDGE_HANDLER.wrap_normal::<flutter_rust_bridge::for_generated::SseCodec, _, _>(
|
||||
flutter_rust_bridge::for_generated::TaskInfo {
|
||||
debug_name: "SynapseGraph_graph_data",
|
||||
port: Some(port_),
|
||||
mode: flutter_rust_bridge::for_generated::FfiCallMode::Normal,
|
||||
},
|
||||
move || {
|
||||
let message = unsafe {
|
||||
flutter_rust_bridge::for_generated::Dart2RustMessageSse::from_wire(
|
||||
ptr_,
|
||||
rust_vec_len_,
|
||||
data_len_,
|
||||
)
|
||||
};
|
||||
let mut deserializer =
|
||||
flutter_rust_bridge::for_generated::SseDeserializer::new(message);
|
||||
let api_that = <RustOpaqueMoi<
|
||||
flutter_rust_bridge::for_generated::RustAutoOpaqueInner<SynapseGraph>,
|
||||
>>::sse_decode(&mut deserializer);
|
||||
deserializer.end();
|
||||
move |context| {
|
||||
transform_result_sse::<_, flutter_rust_bridge::for_generated::anyhow::Error>(
|
||||
(move || {
|
||||
let mut api_that_guard = None;
|
||||
let decode_indices_ =
|
||||
flutter_rust_bridge::for_generated::lockable_compute_decode_order(
|
||||
vec![flutter_rust_bridge::for_generated::LockableOrderInfo::new(
|
||||
&api_that, 0, false,
|
||||
)],
|
||||
);
|
||||
for i in decode_indices_ {
|
||||
match i {
|
||||
0 => api_that_guard = Some(api_that.lockable_decode_sync_ref()),
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
let api_that_guard = api_that_guard.unwrap();
|
||||
let output_ok =
|
||||
crate::api::graph::SynapseGraph::graph_data(&*api_that_guard)?;
|
||||
std::result::Result::Ok(output_ok)
|
||||
})(),
|
||||
)
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
fn wire__crate__api__graph__SynapseGraph_indent_block_impl(
|
||||
port_: flutter_rust_bridge::for_generated::MessagePort,
|
||||
ptr_: flutter_rust_bridge::for_generated::PlatformGeneralizedUint8ListPtr,
|
||||
@@ -1912,6 +2221,9 @@ fn wire__crate__api__graph__SynapseGraph_update_block_impl(
|
||||
|
||||
// Section: related_funcs
|
||||
|
||||
flutter_rust_bridge::frb_generated_moi_arc_impl_value!(
|
||||
flutter_rust_bridge::for_generated::RustAutoOpaqueInner<ForceLayout>
|
||||
);
|
||||
flutter_rust_bridge::frb_generated_moi_arc_impl_value!(
|
||||
flutter_rust_bridge::for_generated::RustAutoOpaqueInner<SynapseGraph>
|
||||
);
|
||||
@@ -1926,6 +2238,16 @@ impl SseDecode for flutter_rust_bridge::for_generated::anyhow::Error {
|
||||
}
|
||||
}
|
||||
|
||||
impl SseDecode for ForceLayout {
|
||||
// Codec=Sse (Serialization based), see doc to use other codecs
|
||||
fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self {
|
||||
let mut inner = <RustOpaqueMoi<
|
||||
flutter_rust_bridge::for_generated::RustAutoOpaqueInner<ForceLayout>,
|
||||
>>::sse_decode(deserializer);
|
||||
return flutter_rust_bridge::for_generated::rust_auto_opaque_decode_owned(inner);
|
||||
}
|
||||
}
|
||||
|
||||
impl SseDecode for SynapseGraph {
|
||||
// Codec=Sse (Serialization based), see doc to use other codecs
|
||||
fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self {
|
||||
@@ -1936,6 +2258,16 @@ impl SseDecode for SynapseGraph {
|
||||
}
|
||||
}
|
||||
|
||||
impl SseDecode
|
||||
for RustOpaqueMoi<flutter_rust_bridge::for_generated::RustAutoOpaqueInner<ForceLayout>>
|
||||
{
|
||||
// Codec=Sse (Serialization based), see doc to use other codecs
|
||||
fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self {
|
||||
let mut inner = <usize>::sse_decode(deserializer);
|
||||
return decode_rust_opaque_moi(inner);
|
||||
}
|
||||
}
|
||||
|
||||
impl SseDecode
|
||||
for RustOpaqueMoi<flutter_rust_bridge::for_generated::RustAutoOpaqueInner<SynapseGraph>>
|
||||
{
|
||||
@@ -2062,6 +2394,52 @@ impl SseDecode for f32 {
|
||||
}
|
||||
}
|
||||
|
||||
impl SseDecode for crate::api::dto::GraphData {
|
||||
// Codec=Sse (Serialization based), see doc to use other codecs
|
||||
fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self {
|
||||
let mut var_nodes = <Vec<crate::api::dto::GraphNode>>::sse_decode(deserializer);
|
||||
let mut var_sources = <Vec<u32>>::sse_decode(deserializer);
|
||||
let mut var_targets = <Vec<u32>>::sse_decode(deserializer);
|
||||
let mut var_kinds = <Vec<u8>>::sse_decode(deserializer);
|
||||
let mut var_weights = <Vec<f32>>::sse_decode(deserializer);
|
||||
let mut var_seq = <i64>::sse_decode(deserializer);
|
||||
return crate::api::dto::GraphData {
|
||||
nodes: var_nodes,
|
||||
sources: var_sources,
|
||||
targets: var_targets,
|
||||
kinds: var_kinds,
|
||||
weights: var_weights,
|
||||
seq: var_seq,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
impl SseDecode for crate::api::dto::GraphNode {
|
||||
// Codec=Sse (Serialization based), see doc to use other codecs
|
||||
fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self {
|
||||
let mut var_id = <String>::sse_decode(deserializer);
|
||||
let mut var_title = <String>::sse_decode(deserializer);
|
||||
let mut var_journalDate = <Option<String>>::sse_decode(deserializer);
|
||||
let mut var_originJournal = <Option<String>>::sse_decode(deserializer);
|
||||
let mut var_createdAt = <i64>::sse_decode(deserializer);
|
||||
let mut var_degree = <u32>::sse_decode(deserializer);
|
||||
let mut var_backlinks = <u32>::sse_decode(deserializer);
|
||||
let mut var_cluster = <u32>::sse_decode(deserializer);
|
||||
let mut var_primaryTag = <Option<u32>>::sse_decode(deserializer);
|
||||
return crate::api::dto::GraphNode {
|
||||
id: var_id,
|
||||
title: var_title,
|
||||
journal_date: var_journalDate,
|
||||
origin_journal: var_originJournal,
|
||||
created_at: var_createdAt,
|
||||
degree: var_degree,
|
||||
backlinks: var_backlinks,
|
||||
cluster: var_cluster,
|
||||
primary_tag: var_primaryTag,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
impl SseDecode for i32 {
|
||||
// Codec=Sse (Serialization based), see doc to use other codecs
|
||||
fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self {
|
||||
@@ -2076,6 +2454,18 @@ impl SseDecode for i64 {
|
||||
}
|
||||
}
|
||||
|
||||
impl SseDecode for crate::api::dto::LayoutFrame {
|
||||
// Codec=Sse (Serialization based), see doc to use other codecs
|
||||
fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self {
|
||||
let mut var_positions = <Vec<f32>>::sse_decode(deserializer);
|
||||
let mut var_alpha = <f32>::sse_decode(deserializer);
|
||||
return crate::api::dto::LayoutFrame {
|
||||
positions: var_positions,
|
||||
alpha: var_alpha,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
impl SseDecode for Vec<String> {
|
||||
// Codec=Sse (Serialization based), see doc to use other codecs
|
||||
fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self {
|
||||
@@ -2136,6 +2526,18 @@ impl SseDecode for Vec<crate::api::dto::EditDto> {
|
||||
}
|
||||
}
|
||||
|
||||
impl SseDecode for Vec<crate::api::dto::GraphNode> {
|
||||
// Codec=Sse (Serialization based), see doc to use other codecs
|
||||
fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self {
|
||||
let mut len_ = <i32>::sse_decode(deserializer);
|
||||
let mut ans_ = Vec::with_capacity(len_ as usize);
|
||||
for idx_ in 0..len_ {
|
||||
ans_.push(<crate::api::dto::GraphNode>::sse_decode(deserializer));
|
||||
}
|
||||
return ans_;
|
||||
}
|
||||
}
|
||||
|
||||
impl SseDecode for Vec<crate::api::dto::PageBrief> {
|
||||
// Codec=Sse (Serialization based), see doc to use other codecs
|
||||
fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self {
|
||||
@@ -2172,6 +2574,30 @@ impl SseDecode for Vec<crate::api::dto::PageDto> {
|
||||
}
|
||||
}
|
||||
|
||||
impl SseDecode for Vec<f32> {
|
||||
// Codec=Sse (Serialization based), see doc to use other codecs
|
||||
fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self {
|
||||
let mut len_ = <i32>::sse_decode(deserializer);
|
||||
let mut ans_ = Vec::with_capacity(len_ as usize);
|
||||
for idx_ in 0..len_ {
|
||||
ans_.push(<f32>::sse_decode(deserializer));
|
||||
}
|
||||
return ans_;
|
||||
}
|
||||
}
|
||||
|
||||
impl SseDecode for Vec<u32> {
|
||||
// Codec=Sse (Serialization based), see doc to use other codecs
|
||||
fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self {
|
||||
let mut len_ = <i32>::sse_decode(deserializer);
|
||||
let mut ans_ = Vec::with_capacity(len_ as usize);
|
||||
for idx_ in 0..len_ {
|
||||
ans_.push(<u32>::sse_decode(deserializer));
|
||||
}
|
||||
return ans_;
|
||||
}
|
||||
}
|
||||
|
||||
impl SseDecode for Vec<u8> {
|
||||
// Codec=Sse (Serialization based), see doc to use other codecs
|
||||
fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self {
|
||||
@@ -2253,6 +2679,28 @@ impl SseDecode for Option<crate::api::dto::PageData> {
|
||||
}
|
||||
}
|
||||
|
||||
impl SseDecode for Option<u32> {
|
||||
// Codec=Sse (Serialization based), see doc to use other codecs
|
||||
fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self {
|
||||
if (<bool>::sse_decode(deserializer)) {
|
||||
return Some(<u32>::sse_decode(deserializer));
|
||||
} else {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl SseDecode for Option<Vec<f32>> {
|
||||
// Codec=Sse (Serialization based), see doc to use other codecs
|
||||
fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self {
|
||||
if (<bool>::sse_decode(deserializer)) {
|
||||
return Some(<Vec<f32>>::sse_decode(deserializer));
|
||||
} else {
|
||||
return None;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl SseDecode for crate::api::dto::PageBrief {
|
||||
// Codec=Sse (Serialization based), see doc to use other codecs
|
||||
fn sse_decode(deserializer: &mut flutter_rust_bridge::for_generated::SseDeserializer) -> Self {
|
||||
@@ -2436,133 +2884,140 @@ fn pde_ffi_dispatcher_primary_impl(
|
||||
) {
|
||||
// Codec=Pde (Serialization + dispatch), see doc to use other codecs
|
||||
match func_id {
|
||||
1 => {
|
||||
2 => wire__crate__api__layout__ForceLayout_pin_impl(port, ptr, rust_vec_len, data_len),
|
||||
3 => wire__crate__api__layout__ForceLayout_reheat_impl(port, ptr, rust_vec_len, data_len),
|
||||
4 => wire__crate__api__layout__ForceLayout_step_impl(port, ptr, rust_vec_len, data_len),
|
||||
5 => wire__crate__api__layout__ForceLayout_unpin_impl(port, ptr, rust_vec_len, data_len),
|
||||
6 => {
|
||||
wire__crate__api__graph__SynapseGraph_add_alias_impl(port, ptr, rust_vec_len, data_len)
|
||||
}
|
||||
2 => wire__crate__api__graph__SynapseGraph_aliases_impl(port, ptr, rust_vec_len, data_len),
|
||||
4 => {
|
||||
7 => wire__crate__api__graph__SynapseGraph_aliases_impl(port, ptr, rust_vec_len, data_len),
|
||||
9 => {
|
||||
wire__crate__api__graph__SynapseGraph_backlinks_impl(port, ptr, rust_vec_len, data_len)
|
||||
}
|
||||
5 => {
|
||||
10 => {
|
||||
wire__crate__api__graph__SynapseGraph_block_ref_impl(port, ptr, rust_vec_len, data_len)
|
||||
}
|
||||
6 => wire__crate__api__graph__SynapseGraph_delete_block_impl(
|
||||
11 => wire__crate__api__graph__SynapseGraph_delete_block_impl(
|
||||
port,
|
||||
ptr,
|
||||
rust_vec_len,
|
||||
data_len,
|
||||
),
|
||||
7 => wire__crate__api__graph__SynapseGraph_delete_page_impl(
|
||||
12 => wire__crate__api__graph__SynapseGraph_delete_page_impl(
|
||||
port,
|
||||
ptr,
|
||||
rust_vec_len,
|
||||
data_len,
|
||||
),
|
||||
9 => wire__crate__api__graph__SynapseGraph_indent_block_impl(
|
||||
14 => {
|
||||
wire__crate__api__graph__SynapseGraph_graph_data_impl(port, ptr, rust_vec_len, data_len)
|
||||
}
|
||||
15 => wire__crate__api__graph__SynapseGraph_indent_block_impl(
|
||||
port,
|
||||
ptr,
|
||||
rust_vec_len,
|
||||
data_len,
|
||||
),
|
||||
10 => wire__crate__api__graph__SynapseGraph_insert_block_impl(
|
||||
16 => wire__crate__api__graph__SynapseGraph_insert_block_impl(
|
||||
port,
|
||||
ptr,
|
||||
rust_vec_len,
|
||||
data_len,
|
||||
),
|
||||
11 => wire__crate__api__graph__SynapseGraph_journal_impl(port, ptr, rust_vec_len, data_len),
|
||||
12 => wire__crate__api__graph__SynapseGraph_journal_neighbors_impl(
|
||||
17 => wire__crate__api__graph__SynapseGraph_journal_impl(port, ptr, rust_vec_len, data_len),
|
||||
18 => wire__crate__api__graph__SynapseGraph_journal_neighbors_impl(
|
||||
port,
|
||||
ptr,
|
||||
rust_vec_len,
|
||||
data_len,
|
||||
),
|
||||
13 => {
|
||||
19 => {
|
||||
wire__crate__api__graph__SynapseGraph_journals_impl(port, ptr, rust_vec_len, data_len)
|
||||
}
|
||||
14 => {
|
||||
20 => {
|
||||
wire__crate__api__graph__SynapseGraph_list_pages_impl(port, ptr, rust_vec_len, data_len)
|
||||
}
|
||||
15 => wire__crate__api__graph__SynapseGraph_merge_block_impl(
|
||||
21 => wire__crate__api__graph__SynapseGraph_merge_block_impl(
|
||||
port,
|
||||
ptr,
|
||||
rust_vec_len,
|
||||
data_len,
|
||||
),
|
||||
16 => {
|
||||
22 => {
|
||||
wire__crate__api__graph__SynapseGraph_move_block_impl(port, ptr, rust_vec_len, data_len)
|
||||
}
|
||||
17 => wire__crate__api__graph__SynapseGraph_open_impl(port, ptr, rust_vec_len, data_len),
|
||||
18 => {
|
||||
23 => wire__crate__api__graph__SynapseGraph_open_impl(port, ptr, rust_vec_len, data_len),
|
||||
24 => {
|
||||
wire__crate__api__graph__SynapseGraph_open_page_impl(port, ptr, rust_vec_len, data_len)
|
||||
}
|
||||
19 => wire__crate__api__graph__SynapseGraph_outdent_block_impl(
|
||||
25 => wire__crate__api__graph__SynapseGraph_outdent_block_impl(
|
||||
port,
|
||||
ptr,
|
||||
rust_vec_len,
|
||||
data_len,
|
||||
),
|
||||
20 => wire__crate__api__graph__SynapseGraph_outline_impl(port, ptr, rust_vec_len, data_len),
|
||||
21 => wire__crate__api__graph__SynapseGraph_page_impl(port, ptr, rust_vec_len, data_len),
|
||||
22 => wire__crate__api__graph__SynapseGraph_page_by_title_impl(
|
||||
26 => wire__crate__api__graph__SynapseGraph_outline_impl(port, ptr, rust_vec_len, data_len),
|
||||
27 => wire__crate__api__graph__SynapseGraph_page_impl(port, ptr, rust_vec_len, data_len),
|
||||
28 => wire__crate__api__graph__SynapseGraph_page_by_title_impl(
|
||||
port,
|
||||
ptr,
|
||||
rust_vec_len,
|
||||
data_len,
|
||||
),
|
||||
23 => wire__crate__api__graph__SynapseGraph_put_asset_bytes_impl(
|
||||
29 => wire__crate__api__graph__SynapseGraph_put_asset_bytes_impl(
|
||||
port,
|
||||
ptr,
|
||||
rust_vec_len,
|
||||
data_len,
|
||||
),
|
||||
24 => wire__crate__api__graph__SynapseGraph_put_asset_file_impl(
|
||||
30 => wire__crate__api__graph__SynapseGraph_put_asset_file_impl(
|
||||
port,
|
||||
ptr,
|
||||
rust_vec_len,
|
||||
data_len,
|
||||
),
|
||||
25 => wire__crate__api__graph__SynapseGraph_record_visit_impl(
|
||||
31 => wire__crate__api__graph__SynapseGraph_record_visit_impl(
|
||||
port,
|
||||
ptr,
|
||||
rust_vec_len,
|
||||
data_len,
|
||||
),
|
||||
26 => wire__crate__api__graph__SynapseGraph_related_impl(port, ptr, rust_vec_len, data_len),
|
||||
27 => wire__crate__api__graph__SynapseGraph_remove_alias_impl(
|
||||
32 => wire__crate__api__graph__SynapseGraph_related_impl(port, ptr, rust_vec_len, data_len),
|
||||
33 => wire__crate__api__graph__SynapseGraph_remove_alias_impl(
|
||||
port,
|
||||
ptr,
|
||||
rust_vec_len,
|
||||
data_len,
|
||||
),
|
||||
28 => wire__crate__api__graph__SynapseGraph_rename_page_impl(
|
||||
34 => wire__crate__api__graph__SynapseGraph_rename_page_impl(
|
||||
port,
|
||||
ptr,
|
||||
rust_vec_len,
|
||||
data_len,
|
||||
),
|
||||
29 => wire__crate__api__graph__SynapseGraph_search_blocks_impl(
|
||||
35 => wire__crate__api__graph__SynapseGraph_search_blocks_impl(
|
||||
port,
|
||||
ptr,
|
||||
rust_vec_len,
|
||||
data_len,
|
||||
),
|
||||
30 => wire__crate__api__graph__SynapseGraph_search_titles_impl(
|
||||
36 => wire__crate__api__graph__SynapseGraph_search_titles_impl(
|
||||
port,
|
||||
ptr,
|
||||
rust_vec_len,
|
||||
data_len,
|
||||
),
|
||||
31 => wire__crate__api__graph__SynapseGraph_set_collapsed_impl(
|
||||
37 => wire__crate__api__graph__SynapseGraph_set_collapsed_impl(
|
||||
port,
|
||||
ptr,
|
||||
rust_vec_len,
|
||||
data_len,
|
||||
),
|
||||
32 => {
|
||||
38 => {
|
||||
wire__crate__api__graph__SynapseGraph_timeline_impl(port, ptr, rust_vec_len, data_len)
|
||||
}
|
||||
34 => wire__crate__api__graph__SynapseGraph_update_block_impl(
|
||||
40 => wire__crate__api__graph__SynapseGraph_update_block_impl(
|
||||
port,
|
||||
ptr,
|
||||
rust_vec_len,
|
||||
@@ -2580,15 +3035,31 @@ fn pde_ffi_dispatcher_sync_impl(
|
||||
) -> flutter_rust_bridge::for_generated::WireSyncRust2DartSse {
|
||||
// Codec=Pde (Serialization + dispatch), see doc to use other codecs
|
||||
match func_id {
|
||||
3 => wire__crate__api__graph__SynapseGraph_asset_path_impl(ptr, rust_vec_len, data_len),
|
||||
8 => wire__crate__api__graph__SynapseGraph_dir_impl(ptr, rust_vec_len, data_len),
|
||||
33 => wire__crate__api__graph__SynapseGraph_today_impl(ptr, rust_vec_len, data_len),
|
||||
1 => wire__crate__api__layout__ForceLayout_new_impl(ptr, rust_vec_len, data_len),
|
||||
8 => wire__crate__api__graph__SynapseGraph_asset_path_impl(ptr, rust_vec_len, data_len),
|
||||
13 => wire__crate__api__graph__SynapseGraph_dir_impl(ptr, rust_vec_len, data_len),
|
||||
39 => wire__crate__api__graph__SynapseGraph_today_impl(ptr, rust_vec_len, data_len),
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
|
||||
// Section: rust2dart
|
||||
|
||||
// Codec=Dco (DartCObject based), see doc to use other codecs
|
||||
impl flutter_rust_bridge::IntoDart for FrbWrapper<ForceLayout> {
|
||||
fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi {
|
||||
flutter_rust_bridge::for_generated::rust_auto_opaque_encode::<_, MoiArc<_>>(self.0)
|
||||
.into_dart()
|
||||
}
|
||||
}
|
||||
impl flutter_rust_bridge::for_generated::IntoDartExceptPrimitive for FrbWrapper<ForceLayout> {}
|
||||
|
||||
impl flutter_rust_bridge::IntoIntoDart<FrbWrapper<ForceLayout>> for ForceLayout {
|
||||
fn into_into_dart(self) -> FrbWrapper<ForceLayout> {
|
||||
self.into()
|
||||
}
|
||||
}
|
||||
|
||||
// Codec=Dco (DartCObject based), see doc to use other codecs
|
||||
impl flutter_rust_bridge::IntoDart for FrbWrapper<SynapseGraph> {
|
||||
fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi {
|
||||
@@ -2719,6 +3190,67 @@ impl flutter_rust_bridge::IntoIntoDart<crate::api::dto::EditDto> for crate::api:
|
||||
}
|
||||
}
|
||||
// Codec=Dco (DartCObject based), see doc to use other codecs
|
||||
impl flutter_rust_bridge::IntoDart for crate::api::dto::GraphData {
|
||||
fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi {
|
||||
[
|
||||
self.nodes.into_into_dart().into_dart(),
|
||||
self.sources.into_into_dart().into_dart(),
|
||||
self.targets.into_into_dart().into_dart(),
|
||||
self.kinds.into_into_dart().into_dart(),
|
||||
self.weights.into_into_dart().into_dart(),
|
||||
self.seq.into_into_dart().into_dart(),
|
||||
]
|
||||
.into_dart()
|
||||
}
|
||||
}
|
||||
impl flutter_rust_bridge::for_generated::IntoDartExceptPrimitive for crate::api::dto::GraphData {}
|
||||
impl flutter_rust_bridge::IntoIntoDart<crate::api::dto::GraphData> for crate::api::dto::GraphData {
|
||||
fn into_into_dart(self) -> crate::api::dto::GraphData {
|
||||
self
|
||||
}
|
||||
}
|
||||
// Codec=Dco (DartCObject based), see doc to use other codecs
|
||||
impl flutter_rust_bridge::IntoDart for crate::api::dto::GraphNode {
|
||||
fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi {
|
||||
[
|
||||
self.id.into_into_dart().into_dart(),
|
||||
self.title.into_into_dart().into_dart(),
|
||||
self.journal_date.into_into_dart().into_dart(),
|
||||
self.origin_journal.into_into_dart().into_dart(),
|
||||
self.created_at.into_into_dart().into_dart(),
|
||||
self.degree.into_into_dart().into_dart(),
|
||||
self.backlinks.into_into_dart().into_dart(),
|
||||
self.cluster.into_into_dart().into_dart(),
|
||||
self.primary_tag.into_into_dart().into_dart(),
|
||||
]
|
||||
.into_dart()
|
||||
}
|
||||
}
|
||||
impl flutter_rust_bridge::for_generated::IntoDartExceptPrimitive for crate::api::dto::GraphNode {}
|
||||
impl flutter_rust_bridge::IntoIntoDart<crate::api::dto::GraphNode> for crate::api::dto::GraphNode {
|
||||
fn into_into_dart(self) -> crate::api::dto::GraphNode {
|
||||
self
|
||||
}
|
||||
}
|
||||
// Codec=Dco (DartCObject based), see doc to use other codecs
|
||||
impl flutter_rust_bridge::IntoDart for crate::api::dto::LayoutFrame {
|
||||
fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi {
|
||||
[
|
||||
self.positions.into_into_dart().into_dart(),
|
||||
self.alpha.into_into_dart().into_dart(),
|
||||
]
|
||||
.into_dart()
|
||||
}
|
||||
}
|
||||
impl flutter_rust_bridge::for_generated::IntoDartExceptPrimitive for crate::api::dto::LayoutFrame {}
|
||||
impl flutter_rust_bridge::IntoIntoDart<crate::api::dto::LayoutFrame>
|
||||
for crate::api::dto::LayoutFrame
|
||||
{
|
||||
fn into_into_dart(self) -> crate::api::dto::LayoutFrame {
|
||||
self
|
||||
}
|
||||
}
|
||||
// Codec=Dco (DartCObject based), see doc to use other codecs
|
||||
impl flutter_rust_bridge::IntoDart for crate::api::dto::PageBrief {
|
||||
fn into_dart(self) -> flutter_rust_bridge::for_generated::DartAbi {
|
||||
[
|
||||
@@ -2892,6 +3424,13 @@ impl SseEncode for flutter_rust_bridge::for_generated::anyhow::Error {
|
||||
}
|
||||
}
|
||||
|
||||
impl SseEncode for ForceLayout {
|
||||
// Codec=Sse (Serialization based), see doc to use other codecs
|
||||
fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) {
|
||||
<RustOpaqueMoi<flutter_rust_bridge::for_generated::RustAutoOpaqueInner<ForceLayout>>>::sse_encode(flutter_rust_bridge::for_generated::rust_auto_opaque_encode::<_, MoiArc<_>>(self), serializer);
|
||||
}
|
||||
}
|
||||
|
||||
impl SseEncode for SynapseGraph {
|
||||
// Codec=Sse (Serialization based), see doc to use other codecs
|
||||
fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) {
|
||||
@@ -2899,6 +3438,17 @@ impl SseEncode for SynapseGraph {
|
||||
}
|
||||
}
|
||||
|
||||
impl SseEncode
|
||||
for RustOpaqueMoi<flutter_rust_bridge::for_generated::RustAutoOpaqueInner<ForceLayout>>
|
||||
{
|
||||
// Codec=Sse (Serialization based), see doc to use other codecs
|
||||
fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) {
|
||||
let (ptr, size) = self.sse_encode_raw();
|
||||
<usize>::sse_encode(ptr, serializer);
|
||||
<i32>::sse_encode(size, serializer);
|
||||
}
|
||||
}
|
||||
|
||||
impl SseEncode
|
||||
for RustOpaqueMoi<flutter_rust_bridge::for_generated::RustAutoOpaqueInner<SynapseGraph>>
|
||||
{
|
||||
@@ -2990,6 +3540,33 @@ impl SseEncode for f32 {
|
||||
}
|
||||
}
|
||||
|
||||
impl SseEncode for crate::api::dto::GraphData {
|
||||
// Codec=Sse (Serialization based), see doc to use other codecs
|
||||
fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) {
|
||||
<Vec<crate::api::dto::GraphNode>>::sse_encode(self.nodes, serializer);
|
||||
<Vec<u32>>::sse_encode(self.sources, serializer);
|
||||
<Vec<u32>>::sse_encode(self.targets, serializer);
|
||||
<Vec<u8>>::sse_encode(self.kinds, serializer);
|
||||
<Vec<f32>>::sse_encode(self.weights, serializer);
|
||||
<i64>::sse_encode(self.seq, serializer);
|
||||
}
|
||||
}
|
||||
|
||||
impl SseEncode for crate::api::dto::GraphNode {
|
||||
// Codec=Sse (Serialization based), see doc to use other codecs
|
||||
fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) {
|
||||
<String>::sse_encode(self.id, serializer);
|
||||
<String>::sse_encode(self.title, serializer);
|
||||
<Option<String>>::sse_encode(self.journal_date, serializer);
|
||||
<Option<String>>::sse_encode(self.origin_journal, serializer);
|
||||
<i64>::sse_encode(self.created_at, serializer);
|
||||
<u32>::sse_encode(self.degree, serializer);
|
||||
<u32>::sse_encode(self.backlinks, serializer);
|
||||
<u32>::sse_encode(self.cluster, serializer);
|
||||
<Option<u32>>::sse_encode(self.primary_tag, serializer);
|
||||
}
|
||||
}
|
||||
|
||||
impl SseEncode for i32 {
|
||||
// Codec=Sse (Serialization based), see doc to use other codecs
|
||||
fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) {
|
||||
@@ -3004,6 +3581,14 @@ impl SseEncode for i64 {
|
||||
}
|
||||
}
|
||||
|
||||
impl SseEncode for crate::api::dto::LayoutFrame {
|
||||
// Codec=Sse (Serialization based), see doc to use other codecs
|
||||
fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) {
|
||||
<Vec<f32>>::sse_encode(self.positions, serializer);
|
||||
<f32>::sse_encode(self.alpha, serializer);
|
||||
}
|
||||
}
|
||||
|
||||
impl SseEncode for Vec<String> {
|
||||
// Codec=Sse (Serialization based), see doc to use other codecs
|
||||
fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) {
|
||||
@@ -3054,6 +3639,16 @@ impl SseEncode for Vec<crate::api::dto::EditDto> {
|
||||
}
|
||||
}
|
||||
|
||||
impl SseEncode for Vec<crate::api::dto::GraphNode> {
|
||||
// Codec=Sse (Serialization based), see doc to use other codecs
|
||||
fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) {
|
||||
<i32>::sse_encode(self.len() as _, serializer);
|
||||
for item in self {
|
||||
<crate::api::dto::GraphNode>::sse_encode(item, serializer);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl SseEncode for Vec<crate::api::dto::PageBrief> {
|
||||
// Codec=Sse (Serialization based), see doc to use other codecs
|
||||
fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) {
|
||||
@@ -3084,6 +3679,26 @@ impl SseEncode for Vec<crate::api::dto::PageDto> {
|
||||
}
|
||||
}
|
||||
|
||||
impl SseEncode for Vec<f32> {
|
||||
// Codec=Sse (Serialization based), see doc to use other codecs
|
||||
fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) {
|
||||
<i32>::sse_encode(self.len() as _, serializer);
|
||||
for item in self {
|
||||
<f32>::sse_encode(item, serializer);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl SseEncode for Vec<u32> {
|
||||
// Codec=Sse (Serialization based), see doc to use other codecs
|
||||
fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) {
|
||||
<i32>::sse_encode(self.len() as _, serializer);
|
||||
for item in self {
|
||||
<u32>::sse_encode(item, serializer);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl SseEncode for Vec<u8> {
|
||||
// Codec=Sse (Serialization based), see doc to use other codecs
|
||||
fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) {
|
||||
@@ -3154,6 +3769,26 @@ impl SseEncode for Option<crate::api::dto::PageData> {
|
||||
}
|
||||
}
|
||||
|
||||
impl SseEncode for Option<u32> {
|
||||
// Codec=Sse (Serialization based), see doc to use other codecs
|
||||
fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) {
|
||||
<bool>::sse_encode(self.is_some(), serializer);
|
||||
if let Some(value) = self {
|
||||
<u32>::sse_encode(value, serializer);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl SseEncode for Option<Vec<f32>> {
|
||||
// Codec=Sse (Serialization based), see doc to use other codecs
|
||||
fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) {
|
||||
<bool>::sse_encode(self.is_some(), serializer);
|
||||
if let Some(value) = self {
|
||||
<Vec<f32>>::sse_encode(value, serializer);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl SseEncode for crate::api::dto::PageBrief {
|
||||
// Codec=Sse (Serialization based), see doc to use other codecs
|
||||
fn sse_encode(self, serializer: &mut flutter_rust_bridge::for_generated::SseSerializer) {
|
||||
@@ -3300,6 +3935,7 @@ mod io {
|
||||
|
||||
use super::*;
|
||||
use crate::api::graph::*;
|
||||
use crate::api::layout::*;
|
||||
use flutter_rust_bridge::for_generated::byteorder::{
|
||||
NativeEndian, ReadBytesExt, WriteBytesExt,
|
||||
};
|
||||
@@ -3310,6 +3946,20 @@ mod io {
|
||||
|
||||
flutter_rust_bridge::frb_generated_boilerplate_io!();
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn frbgen_synapse_rust_arc_increment_strong_count_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerForceLayout(
|
||||
ptr: *const std::ffi::c_void,
|
||||
) {
|
||||
MoiArc::<flutter_rust_bridge::for_generated::RustAutoOpaqueInner<ForceLayout>>::increment_strong_count(ptr as _);
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn frbgen_synapse_rust_arc_decrement_strong_count_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerForceLayout(
|
||||
ptr: *const std::ffi::c_void,
|
||||
) {
|
||||
MoiArc::<flutter_rust_bridge::for_generated::RustAutoOpaqueInner<ForceLayout>>::decrement_strong_count(ptr as _);
|
||||
}
|
||||
|
||||
#[unsafe(no_mangle)]
|
||||
pub extern "C" fn frbgen_synapse_rust_arc_increment_strong_count_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph(
|
||||
ptr: *const std::ffi::c_void,
|
||||
@@ -3337,6 +3987,7 @@ mod web {
|
||||
|
||||
use super::*;
|
||||
use crate::api::graph::*;
|
||||
use crate::api::layout::*;
|
||||
use flutter_rust_bridge::for_generated::byteorder::{
|
||||
NativeEndian, ReadBytesExt, WriteBytesExt,
|
||||
};
|
||||
@@ -3349,6 +4000,20 @@ mod web {
|
||||
|
||||
flutter_rust_bridge::frb_generated_boilerplate_web!();
|
||||
|
||||
#[wasm_bindgen]
|
||||
pub fn rust_arc_increment_strong_count_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerForceLayout(
|
||||
ptr: *const std::ffi::c_void,
|
||||
) {
|
||||
MoiArc::<flutter_rust_bridge::for_generated::RustAutoOpaqueInner<ForceLayout>>::increment_strong_count(ptr as _);
|
||||
}
|
||||
|
||||
#[wasm_bindgen]
|
||||
pub fn rust_arc_decrement_strong_count_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerForceLayout(
|
||||
ptr: *const std::ffi::c_void,
|
||||
) {
|
||||
MoiArc::<flutter_rust_bridge::for_generated::RustAutoOpaqueInner<ForceLayout>>::decrement_strong_count(ptr as _);
|
||||
}
|
||||
|
||||
#[wasm_bindgen]
|
||||
pub fn rust_arc_increment_strong_count_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph(
|
||||
ptr: *const std::ffi::c_void,
|
||||
|
||||
+35
@@ -64,3 +64,38 @@ Commit the regenerated `crates/synapse-ffi/src/frb_generated.rs` and `app/lib/sr
|
||||
structure wins if they ever disagree.
|
||||
- App shortcuts: Ctrl+K quick switcher, Ctrl+Shift+J journals, Ctrl+Shift+T timeline,
|
||||
Ctrl+\ sidebar, Alt+←/→ back/forward.
|
||||
|
||||
## Graph view
|
||||
One view (sidebar "Graph", Ctrl+Shift+G) with a mode selector:
|
||||
- **Network**: force-directed graph of pages (journals optional). Edges: links, tags,
|
||||
property refs, block refs/embeds (aggregated per page) and dashed mentions (unlinked
|
||||
references: a page title appearing as whole words in another page's text). Node size by
|
||||
degree + backlinks, colour by cluster or primary tag. Filters: title, tag, created date
|
||||
range, min links, orphans, journals, mentions. Drag nodes, hover highlights neighbours,
|
||||
wheel/pinch zoom, tap opens the page.
|
||||
- **Local**: neighbourhood of a page at depth 1–3 (also a side panel on every page).
|
||||
- **Synapses**: `related()` spreading activation from a focus page; brightness/size =
|
||||
activation, edge thickness = Hebbian synapse weight, a pulse travels outward by hops.
|
||||
- **Clusters**: Louvain communities with soft hulls.
|
||||
- **Namespaces**: radial tree of `a/b/c` titles and of tags with their pages.
|
||||
- **Timeline**: the journal timeline.
|
||||
|
||||
Data and layout live in Rust: `SynapseGraph::graph_data()` returns the whole page-level
|
||||
graph as parallel arrays (cached until the op seq or the synapse table changes);
|
||||
`ForceLayout` (Barnes-Hut, O(n log n)) is stepped from Dart in small batches on a Rust
|
||||
worker thread. The painter batches draws (one call per edge kind and node colour/size),
|
||||
culls to the viewport and limits labels with an occupancy grid.
|
||||
|
||||
```bash
|
||||
# Stats and timings for a graph (release build)
|
||||
cargo run --release -p synapse-ffi --example graph_stats -- /path/to/graph
|
||||
# Real-app smoke test of every graph mode with frame timings (opens a window; use a copy
|
||||
# of the graph, opening it may write today's journal). Profile mode for real numbers:
|
||||
cd app && flutter drive --profile -d linux --driver=test_driver/integration_test.dart \
|
||||
--target=integration_test/graph_smoke_test.dart \
|
||||
--dart-define=GRAPH=/path/to/copy [--dart-define=SHOTS=/dir/for/pngs]
|
||||
```
|
||||
Measured (profile, Linux, Impeller GL): 5 000 pages / 19 000 links settle in ~7 s and pan at
|
||||
build p50 6 ms / raster p50 4 ms per frame; a 360-page graph settles in ~1 s at ~2 ms/frame.
|
||||
Edges are drawn as one triangle mesh (`drawVertices`): stroking 10k+ lines made Impeller
|
||||
tessellate every frame (raster ~40 ms).
|
||||
Reference in new issue
Block a user