feat(app): Flutter outliner with journals, page view and timeline

Logseq-like outliner (render/edit Markdown per block, Enter/Tab/Shift-Tab,
backspace merge, arrow navigation, drag to reorder, collapse, [[ # ((
autocomplete, TODO/DONE), journals feed with prev/next links, page view with
linked references and related panel, virtualised CustomPainter timeline,
Ctrl+K quick switcher, sidebar with recents, light/dark theme with bundled
Inter, Noto Serif and Source Code Pro. Edits are optimistic and serialised
to the core through one write queue. Cargokit builds synapse-ffi; its build
tool is patched to use the library name (synapse_ffi) of hyphenated crates.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
dasemuandClaude Opus 5.5 committed 2026-10-21 03:59:42 +02:00
1 parent c3d6636606
commit df42d4010f
135 files changed
+17689

No files matched your search

+186
View File
@@ -0,0 +1,186 @@
import 'package:flutter/material.dart';
import '../backend/graph_backend.dart';
import 'write_queue.dart';
sealed class AppRoute {
const AppRoute();
}
class JournalsRoute extends AppRoute {
const JournalsRoute();
}
class TimelineRoute extends AppRoute {
const TimelineRoute();
}
class AllPagesRoute extends AppRoute {
const AllPagesRoute();
}
/// 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);
final String? id;
final String? title;
}
/// App-wide state: the open graph, navigation history, recents and theme.
///
/// State management is plain `ChangeNotifier`s: one for the app, one per open outline
/// (`OutlineController`) and a block-ref cache. The state is small and mostly local to a
/// page, so a framework (Riverpod, Bloc) would add a dependency and indirection without
/// paying for itself; rebuilds are scoped with `ListenableBuilder`.
class AppState extends ChangeNotifier {
AppState(this.backend, {WriteQueue? queue})
: queue = queue ?? WriteQueue(onError: _logError),
refs = BlockRefCache(backend);
final GraphBackend backend;
final WriteQueue queue;
final BlockRefCache refs;
AppRoute _route = const JournalsRoute();
final _back = <AppRoute>[];
final _forward = <AppRoute>[];
ThemeMode themeMode = ThemeMode.system;
final List<PageBrief> recent = [];
/// Last page shown (for synapse reinforcement on navigation).
String? _lastPageId;
/// Bumped when an error makes views reload from the core.
int generation = 0;
AppRoute get route => _route;
bool get canGoBack => _back.isNotEmpty;
bool get canGoForward => _forward.isNotEmpty;
static void _logError(Object e, StackTrace st) {
debugPrint('graph write failed: $e\n$st');
}
void go(AppRoute r) {
_back.add(_route);
if (_back.length > 100) _back.removeAt(0);
_forward.clear();
_route = r;
notifyListeners();
}
void back() {
if (_back.isEmpty) return;
_forward.add(_route);
_route = _back.removeLast();
notifyListeners();
}
void forward() {
if (_forward.isEmpty) return;
_back.add(_route);
_route = _forward.removeLast();
notifyListeners();
}
void openTitle(String title) => go(PageTarget(title: title));
void openId(String id) => go(PageTarget(id: id));
/// Called by the page view once it knows which page it shows.
void pageShown(PageDto page) {
final from = _lastPageId;
_lastPageId = page.id;
if (from != page.id) {
queue.run(() => backend.recordVisit(from, page.id)).ignore();
}
recent.removeWhere((p) => p.id == page.id);
recent.insert(
0,
PageBrief(
id: page.id,
title: page.title,
isJournal: page.journalDate != null,
),
);
if (recent.length > 12) recent.removeLast();
notifyListeners();
}
/// Seeds the recents list with recently edited pages.
Future<void> loadRecent() async {
final pages = await backend.listPages(limit: 8);
for (final p in pages) {
if (!recent.any((r) => r.id == p.id)) {
recent.add(PageBrief(id: p.id, title: p.title, isJournal: false));
}
}
notifyListeners();
}
void renamed(String id, String title) {
final i = recent.indexWhere((p) => p.id == id);
if (i >= 0) {
recent[i] = PageBrief(
id: id,
title: title,
isJournal: recent[i].isJournal,
);
}
notifyListeners();
}
void toggleTheme(Brightness current) {
themeMode = current == Brightness.dark ? ThemeMode.light : ThemeMode.dark;
notifyListeners();
}
}
/// Resolved `((block refs))`, loaded lazily and shared by every rendered block.
class BlockRefCache extends ChangeNotifier {
BlockRefCache(this._backend);
final GraphBackend _backend;
final _cache = <String, BlockRefDto?>{};
final _loading = <String>{};
/// Cached target, or null while loading / when missing ([isMissing] tells them apart).
BlockRefDto? get(String id) {
if (_cache.containsKey(id)) return _cache[id];
if (_loading.add(id)) {
_backend
.blockRef(id)
.then(
(r) {
_cache[id] = r;
_loading.remove(id);
notifyListeners();
},
onError: (Object _) {
_cache[id] = null;
_loading.remove(id);
notifyListeners();
},
);
}
return null;
}
bool isMissing(String id) => _cache.containsKey(id) && _cache[id] == null;
void invalidate(String id) {
if (_cache.remove(id) != null) notifyListeners();
}
}
/// Gives widgets access to the [AppState].
class AppScope extends InheritedNotifier<AppState> {
const AppScope({super.key, required AppState state, required super.child})
: super(notifier: state);
static AppState of(BuildContext context) =>
context.dependOnInheritedWidgetOfExactType<AppScope>()!.notifier!;
/// Access without subscribing to changes.
static AppState read(BuildContext context) =>
context.getInheritedWidgetOfExactType<AppScope>()!.notifier!;
}
+365
View File
@@ -0,0 +1,365 @@
import 'dart:async';
import 'package:flutter/foundation.dart';
import '../backend/graph_backend.dart';
import 'outline_ops.dart';
import 'write_queue.dart';
/// Editing state of one page's outline.
///
/// Edits are applied to [nodes] immediately (optimistic) and sent to the core through the
/// shared [WriteQueue]. Text is saved with a debounce; structural edits flush pending text
/// first. Blocks created locally carry a temporary id until the core assigns the real one;
/// queued tasks read ids from the node objects when they run, so they always see the real id.
/// After structural edits settle, the outline is re-read and adopted if it disagrees.
class OutlineController extends ChangeNotifier {
OutlineController({
required this.backend,
required this.queue,
required this.pageId,
required List<BlockDto> blocks,
this.saveDelay = const Duration(milliseconds: 350),
}) : nodes = blocks.map(OutlineNode.fromDto).toList();
final GraphBackend backend;
final WriteQueue queue;
final String pageId;
final Duration saveDelay;
final List<OutlineNode> nodes;
/// Block being edited, if any.
String? focusedId;
/// Caret requested for the focused block; consumed by the row once applied.
int? pendingCaret;
final _timers = <OutlineNode, Timer>{};
Timer? _reconcile;
int _structuralEdits = 0;
static int _tmpSeq = 0;
bool _disposed = false;
// ------------------------------------------------------------- queries
List<int> get visible => OutlineOps.visible(nodes);
int indexOf(String id) => nodes.indexWhere((n) => n.id == id);
OutlineNode? byId(String id) {
final i = indexOf(id);
return i < 0 ? null : nodes[i];
}
bool hasChildren(OutlineNode n) =>
OutlineOps.hasChildren(nodes, nodes.indexOf(n));
OutlineNode? _visibleNeighbour(OutlineNode n, int step) {
final vis = visible;
final pos = vis.indexOf(nodes.indexOf(n));
final k = pos + step;
return pos < 0 || k < 0 || k >= vis.length ? null : nodes[vis[k]];
}
OutlineNode? previousVisible(OutlineNode n) => _visibleNeighbour(n, -1);
OutlineNode? nextVisible(OutlineNode n) => _visibleNeighbour(n, 1);
// --------------------------------------------------------------- focus
void focus(String id, {int? caret}) {
focusedId = id;
pendingCaret = caret;
notifyListeners();
}
/// Called by a row when it loses focus.
void blurred(String id) {
final n = byId(id);
if (n != null) _flush(n);
if (focusedId == id) {
focusedId = null;
pendingCaret = null;
notifyListeners();
}
}
// ---------------------------------------------------------------- text
/// Text changed while typing (debounced save).
void setText(OutlineNode n, String text) {
if (n.content == text) return;
n.content = text;
_timers[n]?.cancel();
_timers[n] = Timer(saveDelay, () => _flush(n));
}
void _flush(OutlineNode n) {
final t = _timers.remove(n);
if (t == null) return;
t.cancel();
final content = n.content;
_enqueue(() => backend.updateBlock(n.id, content));
}
void flushAll() {
for (final n in _timers.keys.toList()) {
_flush(n);
}
}
/// Replaces a block's text right away (e.g. toggling TODO from a checkbox).
void replaceText(OutlineNode n, String text, {int? caret}) {
setText(n, text);
_flush(n);
if (caret != null && focusedId == n.id) pendingCaret = caret;
notifyListeners();
}
// ----------------------------------------------------------- structure
/// Creates the first block of an empty page and focuses it.
void insertFirst() {
final node = _newNode('');
OutlineOps.insert(nodes, node, PlaceKind.lastChildOf, null);
_sendInsert(node, PlaceKind.lastChildOf, null);
focus(node.id, caret: 0);
}
/// Enter at `caret`: splits the block. At the very start of a non-empty block a new empty
/// block is inserted above and the caret stays put.
void split(OutlineNode n, int caret) {
final text = n.content;
caret = caret.clamp(0, text.length);
final i = nodes.indexOf(n);
if (caret == 0 && text.isNotEmpty) {
final node = _newNode('');
OutlineOps.insert(nodes, node, PlaceKind.before, i);
_sendInsert(node, PlaceKind.before, n);
focus(n.id, caret: 0);
return;
}
final before = text.substring(0, caret);
var after = text.substring(caret);
if (after.isEmpty &&
RegExp(r'^(TODO|DOING|DONE|LATER|NOW) ').hasMatch(before)) {
after = 'TODO ';
}
setText(n, before);
_flush(n);
final intoChildren = !n.collapsed && OutlineOps.hasChildren(nodes, i);
final kind = intoChildren ? PlaceKind.firstChildOf : PlaceKind.after;
final node = _newNode(after);
OutlineOps.insert(nodes, node, kind, i);
_sendInsert(node, kind, n);
focus(node.id, caret: after == 'TODO ' ? after.length : 0);
}
void indent(OutlineNode n, {int? caret}) {
if (!OutlineOps.indent(nodes, nodes.indexOf(n))) return;
flushAll();
_structural(() => backend.indentBlock(n.id));
_refocus(n, caret);
}
void outdent(OutlineNode n, {int? caret}) {
if (!OutlineOps.outdent(nodes, nodes.indexOf(n))) return;
flushAll();
_structural(() => backend.outdentBlock(n.id));
_refocus(n, caret);
}
/// Backspace at the start of a block: merge into the previous visible block.
/// Returns false when there is nothing to merge into.
bool mergeIntoPrevious(OutlineNode n) {
final prev = previousVisible(n);
if (prev == null) return false;
_merge(n, prev);
return true;
}
/// Delete at the end of a block: pull the next visible block into it.
bool mergeNext(OutlineNode n) {
final next = nextVisible(n);
if (next == null) return false;
_merge(next, n);
return true;
}
void _merge(OutlineNode n, OutlineNode into) {
final caret = into.content.length;
flushAll();
OutlineOps.merge(nodes, nodes.indexOf(n), nodes.indexOf(into));
_structural(() => backend.mergeBlock(n.id, into.id));
focus(into.id, caret: caret);
}
/// Alt+Shift+Up/Down: swap with the previous/next sibling.
void moveAmongSiblings(OutlineNode n, {required bool up, int? caret}) {
final i = nodes.indexOf(n);
final s = up
? OutlineOps.prevSibling(nodes, i)
: OutlineOps.nextSibling(nodes, i);
if (s == null) return;
final kind = up ? PlaceKind.before : PlaceKind.after;
moveTo(n, kind, nodes[s], caret: caret);
}
/// Drag and drop (or keyboard move) relative to `anchor`.
void moveTo(
OutlineNode n,
PlaceKind kind,
OutlineNode? anchor, {
int? caret,
}) {
final a = anchor == null ? null : nodes.indexOf(anchor);
if (!OutlineOps.move(nodes, nodes.indexOf(n), kind, a)) return;
flushAll();
final expand =
anchor != null &&
(kind == PlaceKind.firstChildOf || kind == PlaceKind.lastChildOf);
_structural(() async {
if (expand) await backend.setCollapsed(anchor.id, false);
return backend.moveBlock(
n.id,
pageId,
Place(kind: kind, anchor: anchor?.id),
);
});
if (focusedId == n.id) {
_refocus(n, caret);
} else {
notifyListeners();
}
}
void delete(OutlineNode n) {
final prev = previousVisible(n);
flushAll();
OutlineOps.delete(nodes, nodes.indexOf(n));
_structural(() => backend.deleteBlock(n.id));
if (focusedId == n.id && prev != null) {
focus(prev.id, caret: prev.content.length);
} else {
notifyListeners();
}
}
void toggleCollapsed(OutlineNode n) {
if (!hasChildren(n) && !n.collapsed) return;
n.collapsed = !n.collapsed;
final collapsed = n.collapsed;
_enqueue(() => backend.setCollapsed(n.id, collapsed));
if (collapsed && focusedId != null) {
final f = byId(focusedId!);
if (f != null && !visible.contains(nodes.indexOf(f))) focus(n.id);
}
notifyListeners();
}
/// Ctrl+Enter: none → TODO → DONE → none. Returns the caret shift.
int cycleTodo(OutlineNode n) {
final t = n.content;
String next;
int shift;
if (t.startsWith('TODO ') ||
t.startsWith('DOING ') ||
t.startsWith('NOW ') ||
t.startsWith('LATER ')) {
final rest = t.substring(t.indexOf(' ') + 1);
next = 'DONE $rest';
shift = next.length - t.length;
} else if (t.startsWith('DONE ')) {
next = t.substring(5);
shift = -5;
} else {
next = 'TODO $t';
shift = 5;
}
replaceText(n, next);
return shift;
}
// ------------------------------------------------------------ plumbing
OutlineNode _newNode(String content) =>
OutlineNode(id: '_tmp${_tmpSeq++}', depth: 0, content: content);
void _sendInsert(OutlineNode node, PlaceKind kind, OutlineNode? anchor) {
final content = node.content;
_enqueue(() async {
final b = await backend.insertBlock(
pageId,
Place(kind: kind, anchor: anchor?.id),
content,
);
final wasFocused = focusedId == node.id;
node.id = b.id;
OutlineOps.fixParents(nodes);
if (wasFocused) focusedId = b.id;
if (!_disposed) notifyListeners();
});
}
void _refocus(OutlineNode n, int? caret) {
if (focusedId == n.id) {
pendingCaret = caret;
}
notifyListeners();
}
void _structural(Future<List<BlockDto>> Function() op) {
_structuralEdits++;
final seen = _structuralEdits;
_enqueue(() async {
await op();
});
_reconcile?.cancel();
_reconcile = Timer(const Duration(milliseconds: 600), () {
if (seen == _structuralEdits) _verify();
});
}
/// Re-reads the outline and adopts the core's structure if it differs from ours.
void _verify() {
final seen = _structuralEdits;
_enqueue(() async {
final server = await backend.outline(pageId);
if (_disposed || seen != _structuralEdits) return;
if (nodes.any((n) => n.id.startsWith('_tmp'))) return;
final same =
server.length == nodes.length &&
List.generate(server.length, (i) => i).every(
(i) =>
server[i].id == nodes[i].id &&
server[i].depth == nodes[i].depth,
);
if (same) return;
debugPrint('outline: adopting core structure for page $pageId');
final local = {for (final n in nodes) n.id: n};
final adopted = server.map((b) {
final n = local[b.id] ?? OutlineNode.fromDto(b);
n
..depth = b.depth
..parentId = b.parentId
..collapsed = b.collapsed;
return n;
}).toList();
nodes
..clear()
..addAll(adopted);
notifyListeners();
});
}
void _enqueue(Future<void> Function() task) {
queue.run(task).ignore();
}
@override
void dispose() {
flushAll();
_reconcile?.cancel();
_disposed = true;
super.dispose();
}
}
+208
View File
@@ -0,0 +1,208 @@
import '../backend/graph_backend.dart';
/// One outline row held by the editor. Mutable on purpose: the editor applies edits in place
/// and rebuilds only what changed.
class OutlineNode {
OutlineNode({
required this.id,
this.parentId,
required this.depth,
required this.content,
this.collapsed = false,
});
factory OutlineNode.fromDto(BlockDto b) => OutlineNode(
id: b.id,
parentId: b.parentId,
depth: b.depth,
content: b.content,
collapsed: b.collapsed,
);
String id;
String? parentId;
int depth;
String content;
bool collapsed;
OutlineNode copy() => OutlineNode(
id: id,
parentId: parentId,
depth: depth,
content: content,
collapsed: collapsed,
);
@override
String toString() => '$depth:$content';
}
/// Outline algorithms on a pre-order list of nodes. They mirror `synapse-ffi`'s outline
/// module so the editor can apply edits optimistically and agree with the core.
class OutlineOps {
OutlineOps._();
/// Index right after the subtree rooted at `i`.
static int subtreeEnd(List<OutlineNode> l, int i) {
var j = i + 1;
while (j < l.length && l[j].depth > l[i].depth) {
j++;
}
return j;
}
static bool hasChildren(List<OutlineNode> l, int i) =>
i + 1 < l.length && l[i + 1].depth > l[i].depth;
static int? prevSibling(List<OutlineNode> l, int i) {
for (var j = i - 1; j >= 0; j--) {
if (l[j].depth == l[i].depth) return j;
if (l[j].depth < l[i].depth) return null;
}
return null;
}
static int? nextSibling(List<OutlineNode> l, int i) {
final j = subtreeEnd(l, i);
return j < l.length && l[j].depth == l[i].depth ? j : null;
}
static int? parent(List<OutlineNode> l, int i) {
for (var j = i - 1; j >= 0; j--) {
if (l[j].depth < l[i].depth) return j;
}
return null;
}
/// Indices of rows not hidden under a collapsed ancestor.
static List<int> visible(List<OutlineNode> l) {
final out = <int>[];
var i = 0;
while (i < l.length) {
out.add(i);
i = l[i].collapsed ? subtreeEnd(l, i) : i + 1;
}
return out;
}
/// Recomputes `parentId` from depths.
static void fixParents(List<OutlineNode> l) {
final stack = <OutlineNode>[];
for (final n in l) {
while (stack.isNotEmpty && stack.last.depth >= n.depth) {
stack.removeLast();
}
n.parentId = stack.isEmpty ? null : stack.last.id;
stack.add(n);
}
}
static void _shift(List<OutlineNode> l, int from, int to, int by) {
for (var k = from; k < to; k++) {
l[k].depth += by;
}
}
/// Tab. Returns false when there is no previous sibling.
static bool indent(List<OutlineNode> l, int i) {
final p = prevSibling(l, i);
if (p == null) return false;
l[p].collapsed = false;
_shift(l, i, subtreeEnd(l, i), 1);
fixParents(l);
return true;
}
/// Shift-Tab with direct outdenting: following siblings become children of the block.
static bool outdent(List<OutlineNode> l, int i) {
if (l[i].depth == 0) return false;
final end = subtreeEnd(l, i);
final hadFollowing = end < l.length && l[end].depth == l[i].depth;
_shift(l, i, end, -1);
if (hadFollowing) l[i].collapsed = false;
fixParents(l);
return true;
}
/// Merges row `i` into row `into` (its previous visible row).
static void merge(List<OutlineNode> l, int i, int into) {
final target = l[into];
final isParent = parent(l, i) == into;
target.content += l[i].content;
final end = subtreeEnd(l, i);
if (end > i + 1) {
if (isParent) {
_shift(l, i + 1, end, -1);
} else {
target.collapsed = false;
_shift(l, i + 1, end, target.depth - l[i].depth);
}
}
l.removeAt(i);
fixParents(l);
}
/// Deletes row `i` with its subtree.
static void delete(List<OutlineNode> l, int i) {
l.removeRange(i, subtreeEnd(l, i));
fixParents(l);
}
/// Insertion index and depth for a placement, or null when the anchor is unknown.
static (int, int)? slot(List<OutlineNode> l, PlaceKind kind, int? anchor) {
switch (kind) {
case PlaceKind.before:
if (anchor == null) return null;
return (anchor, l[anchor].depth);
case PlaceKind.after:
if (anchor == null) return null;
return (subtreeEnd(l, anchor), l[anchor].depth);
case PlaceKind.firstChildOf:
if (anchor == null) return (0, 0);
return (anchor + 1, l[anchor].depth + 1);
case PlaceKind.lastChildOf:
if (anchor == null) return (l.length, 0);
return (subtreeEnd(l, anchor), l[anchor].depth + 1);
}
}
static int insert(
List<OutlineNode> l,
OutlineNode node,
PlaceKind kind,
int? anchor,
) {
final (at, depth) = slot(l, kind, anchor)!;
if (anchor != null &&
(kind == PlaceKind.firstChildOf || kind == PlaceKind.lastChildOf)) {
l[anchor].collapsed = false;
}
node.depth = depth;
l.insert(at, node);
fixParents(l);
return at;
}
/// Moves row `i` with its subtree. Returns false for moves into its own subtree.
static bool move(List<OutlineNode> l, int i, PlaceKind kind, int? anchor) {
final end = subtreeEnd(l, i);
if (anchor != null && anchor >= i && anchor < end) return false;
final s = slot(l, kind, anchor);
if (s == null) return false;
if (anchor != null &&
(kind == PlaceKind.firstChildOf || kind == PlaceKind.lastChildOf)) {
l[anchor].collapsed = false;
}
var (at, depth) = s;
final moved = l.sublist(i, end);
final delta = depth - moved.first.depth;
for (final n in moved) {
n.depth += delta;
}
l.removeRange(i, end);
if (at > i) at -= moved.length;
l.insertAll(at, moved);
fixParents(l);
return true;
}
}
+54
View File
@@ -0,0 +1,54 @@
import 'dart:async';
import 'dart:collection';
import 'package:flutter/foundation.dart';
/// Runs graph writes one at a time, in submission order. FFI calls are async and run on a
/// Rust thread pool, so without this two quick edits could reach the core out of order.
class WriteQueue {
WriteQueue({this.onError});
/// Called with any error a task throws; the task's own future also completes with it.
final void Function(Object error, StackTrace stack)? onError;
final _tasks = Queue<Future<void> Function()>();
bool _running = false;
Completer<void>? _idle;
bool get isIdle => !_running && _tasks.isEmpty;
/// Completes when every queued task has run.
Future<void> get idle {
if (isIdle) return Future.value();
return (_idle ??= Completer<void>()).future;
}
Future<T> run<T>(Future<T> Function() task) {
final done = Completer<T>();
_tasks.add(() async {
try {
done.complete(await task());
} catch (e, st) {
onError?.call(e, st);
done.completeError(e, st);
}
});
_pump();
return done.future;
}
Future<void> _pump() async {
if (_running) return;
_running = true;
while (_tasks.isNotEmpty) {
await _tasks.removeFirst()();
}
_running = false;
final idle = _idle;
_idle = null;
idle?.complete();
}
@visibleForTesting
int get pending => _tasks.length;
}