fix(app): read views after queued writes, reload on write failure

- Page and journal views read through the write queue after the previous
  view's pending saves, so they never load stale text.
- A failed write reloads the current view and shows a message instead of
  leaving blocks on temporary ids; inserts also trigger reconciliation.
- Completion replaces the query range, not up to the caret, and closes
  when the caret moves away.
- Renaming a page reloads it so rewritten links are not overwritten.
- Dropping below an expanded parent lands as its first child, where the
  indicator is drawn.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
dasemuandClaude Opus 5.5 committed 2026-10-21 04:08:36 +02:00
1 parent fce7526fcf
commit 5e25db3e24
9 files changed
+102 -29

No files matched your search

+11 -7
View File
@@ -165,7 +165,9 @@ class _BlockRowState extends State<BlockRow> {
if (p.dy < box.size.height / 2) {
d = _Drop.before;
} else {
d = p.dx > contentX + 28 ? _Drop.child : _Drop.after;
// Below an expanded parent the gap is above its first child: drop there.
final expandedParent = widget.hasChildren && !n.collapsed;
d = expandedParent || p.dx > contentX + 28 ? _Drop.child : _Drop.after;
}
if (d != _drop) setState(() => _drop = d);
}
@@ -561,12 +563,7 @@ class _BlockEditorState extends State<BlockEditor> {
void _accept(int i) {
final q = _query;
if (q == null || i >= _items.length) return;
final v = applyCompletion(
_text.text,
_text.selection.baseOffset,
q,
_items[i],
);
final v = applyCompletion(_text.text, q, _items[i]);
_closeCompletion();
_text.value = v;
_last = v;
@@ -643,6 +640,13 @@ class _BlockEditorState extends State<BlockEditor> {
_closeCompletion();
return KeyEventResult.handled;
}
// Moving the caret elsewhere ends the completion.
if (key == LogicalKeyboardKey.arrowLeft ||
key == LogicalKeyboardKey.arrowRight ||
key == LogicalKeyboardKey.home ||
key == LogicalKeyboardKey.end) {
_closeCompletion();
}
}
if (key == LogicalKeyboardKey.enter ||
+9 -3
View File
@@ -82,15 +82,21 @@ CompletionQuery? detectCompletion(String text, int caret) {
return best;
}
/// Text after accepting `item` for `q` with the caret at `caret`.
/// Text after accepting `item` for `q` (replacing the query text, wherever the caret is).
TextEditingValue applyCompletion(
String text,
int caret,
CompletionQuery q,
CompletionItem item,
) {
final end = q.start + q.query.length;
if (end > text.length || text.substring(q.start, end) != q.query) {
return TextEditingValue(
text: text,
selection: TextSelection.collapsed(offset: text.length),
);
}
final head = text.substring(0, q.start);
var tail = text.substring(caret);
var tail = text.substring(end);
switch (q.kind) {
case CompletionKind.page:
if (tail.startsWith(']]')) tail = tail.substring(2);
+18 -4
View File
@@ -34,8 +34,10 @@ class PageTarget extends AppRoute {
/// 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);
: refs = BlockRefCache(backend),
queue = queue ?? WriteQueue() {
this.queue.onError = _writeFailed;
}
final GraphBackend backend;
final WriteQueue queue;
@@ -50,15 +52,27 @@ class AppState extends ChangeNotifier {
/// Last page shown (for synapse reinforcement on navigation).
String? _lastPageId;
/// Bumped when an error makes views reload from the core.
/// Bumped to make the current view reload from the core (failed writes, renames).
int generation = 0;
/// Last write error, shown once by the shell.
String? writeError;
AppRoute get route => _route;
bool get canGoBack => _back.isNotEmpty;
bool get canGoForward => _forward.isNotEmpty;
static void _logError(Object e, StackTrace st) {
/// A failed write leaves the optimistic UI out of sync: reload the view from the core.
void _writeFailed(Object e, StackTrace st) {
debugPrint('graph write failed: $e\n$st');
writeError = '$e';
reload();
}
/// Rebuilds the current view from the core (after queued writes have run).
void reload() {
generation++;
notifyListeners();
}
void go(AppRoute r) {
+7 -2
View File
@@ -298,6 +298,7 @@ class OutlineController extends ChangeNotifier {
if (wasFocused) focusedId = b.id;
if (!_disposed) notifyListeners();
});
_scheduleVerify();
}
void _refocus(OutlineNode n, int? caret) {
@@ -308,11 +309,15 @@ class OutlineController extends ChangeNotifier {
}
void _structural(Future<List<BlockDto>> Function() op) {
_structuralEdits++;
final seen = _structuralEdits;
_enqueue(() async {
await op();
});
_scheduleVerify();
}
void _scheduleVerify() {
_structuralEdits++;
final seen = _structuralEdits;
_reconcile?.cancel();
_reconcile = Timer(const Duration(milliseconds: 600), () {
if (seen == _structuralEdits) _verify();
+4 -3
View File
@@ -9,7 +9,7 @@ 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;
void Function(Object error, StackTrace stack)? onError;
final _tasks = Queue<Future<void> Function()>();
bool _running = false;
@@ -23,13 +23,14 @@ class WriteQueue {
return (_idle ??= Completer<void>()).future;
}
Future<T> run<T>(Future<T> Function() task) {
/// Queues `task`. Reads pass `report: false` so their errors do not reach [onError].
Future<T> run<T>(Future<T> Function() task, {bool report = true}) {
final done = Completer<T>();
_tasks.add(() async {
try {
done.complete(await task());
} catch (e, st) {
onError?.call(e, st);
if (report) onError?.call(e, st);
done.completeError(e, st);
}
});
+5 -1
View File
@@ -49,7 +49,11 @@ class _JournalsViewState extends State<JournalsView> {
final app = AppScope.read(context);
try {
final before = _days.isEmpty ? null : _days.last.view.page.journalDate;
final views = await app.backend.journals(before: before, limit: _batch);
if (_days.isEmpty) await WidgetsBinding.instance.endOfFrame;
final views = await app.queue.run(
() => app.backend.journals(before: before, limit: _batch),
report: false,
);
if (!mounted) return;
setState(() {
for (final v in views) {
+11 -6
View File
@@ -41,12 +41,15 @@ class _PageScreenState extends State<PageScreen> {
final app = AppScope.read(context);
try {
final t = widget.target;
PageData? v;
if (t.id != null) {
v = await app.backend.page(t.id!);
} else {
v = await app.backend.openPage(t.title!);
}
// Read after the previous view's pending saves (flushed when it is disposed at the
// end of this frame) have reached the core.
await WidgetsBinding.instance.endOfFrame;
final v = await app.queue.run(
() => t.id != null
? app.backend.page(t.id!)
: app.backend.openPage(t.title!).then<PageData?>((p) => p),
report: false,
);
if (!mounted) return;
if (v == null) {
setState(() => _error = 'This page no longer exists.');
@@ -228,6 +231,8 @@ class _TitleFieldState extends State<_TitleField> {
await app.queue.run(() => app.backend.renamePage(widget.page.id, title));
_committed = title;
app.renamed(widget.page.id, title);
// The core rewrote links in other blocks, possibly on this page: reload them.
app.reload();
} catch (e) {
_text.text = _committed;
messenger.showSnackBar(SnackBar(content: Text('Rename failed: $e')));
+13 -1
View File
@@ -27,6 +27,18 @@ class _ShellState extends State<Shell> {
final app = AppScope.of(context);
final colors = context.colors;
final route = app.route;
final error = app.writeError;
if (error != null) {
app.writeError = null;
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!context.mounted) return;
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Could not save a change; reloaded. ($error)'),
),
);
});
}
return CallbackShortcuts(
bindings: {
const SingleActivator(LogicalKeyboardKey.keyK, control: true): () =>
@@ -96,7 +108,7 @@ class _ShellState extends State<Shell> {
),
Expanded(
child: KeyedSubtree(
key: ValueKey(route),
key: ValueKey((route, app.generation)),
child: switch (route) {
JournalsRoute() => const JournalsView(),
TimelineRoute() => const TimelineView(),