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

+42
View File
@@ -0,0 +1,42 @@
import 'package:flutter/material.dart';
import 'backend/graph_backend.dart';
import 'state/app_state.dart';
import 'theme/theme.dart';
import 'views/shell.dart';
class SynapseApp extends StatefulWidget {
const SynapseApp({super.key, required this.backend});
final GraphBackend backend;
@override
State<SynapseApp> createState() => _SynapseAppState();
}
class _SynapseAppState extends State<SynapseApp> {
late final AppState _state = AppState(widget.backend)..loadRecent();
@override
void dispose() {
_state.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return AppScope(
state: _state,
child: ListenableBuilder(
listenable: _state,
builder: (context, _) => MaterialApp(
title: 'Synapse',
debugShowCheckedModeBanner: false,
theme: buildTheme(Brightness.light),
darkTheme: buildTheme(Brightness.dark),
themeMode: _state.themeMode,
home: const Shell(),
),
),
);
}
}
+148
View File
@@ -0,0 +1,148 @@
import '../rust/api/dto.dart';
import '../rust/api/graph.dart';
export '../rust/api/dto.dart';
/// What the UI needs from a graph. [FfiGraphBackend] talks to the Rust core; tests use an
/// in-memory implementation. Keeping the UI on this interface (instead of the generated
/// opaque class) is what makes the editor testable without the native library.
abstract class GraphBackend {
/// Today's date in the graph clock, `YYYY-MM-DD`.
String today();
Future<List<PageData>> journals({String? before, required int limit});
Future<PageData> journal(String date);
Future<PageData?> page(String id);
Future<PageData?> pageByTitle(String title);
/// Page by title or alias, created if missing.
Future<PageData> openPage(String title);
Future<List<PageDto>> listPages({
bool includeJournals = false,
required int limit,
int offset = 0,
});
Future<PageDto> renamePage(String id, String newTitle);
Future<void> deletePage(String id);
Future<void> addAlias(String pageId, String alias);
Future<void> removeAlias(String alias);
Future<BlockDto> insertBlock(String pageId, Place place, String content);
Future<void> updateBlock(String id, String content);
Future<void> setCollapsed(String id, bool collapsed);
Future<List<BlockDto>> deleteBlock(String id);
Future<List<BlockDto>> moveBlock(String id, String pageId, Place place);
Future<List<BlockDto>> indentBlock(String id);
Future<List<BlockDto>> outdentBlock(String id);
Future<List<BlockDto>> mergeBlock(String id, String into);
Future<List<BlockDto>> outline(String pageId);
Future<List<BacklinkGroup>> backlinks(String pageId);
Future<List<RelatedDto>> related(String pageId, {int limit = 12});
Future<void> recordVisit(String? from, String to);
Future<BlockRefDto?> blockRef(String id);
Future<TimelineDto> timeline(String from, String to);
Future<List<TitleHit>> searchTitles(String query, {int limit = 20});
Future<List<BlockHit>> searchBlocks(String query, {int limit = 20});
/// Local path of an `asset://<hash>` blob, if present.
String? assetPath(String hash);
Future<AssetDto> putAssetFile(String path, {String? mime});
}
class FfiGraphBackend implements GraphBackend {
FfiGraphBackend(this._g);
final SynapseGraph _g;
static Future<FfiGraphBackend> open(String dir) async =>
FfiGraphBackend(await SynapseGraph.open(dir: dir));
@override
String today() => _g.today();
@override
Future<List<PageData>> journals({String? before, required int limit}) =>
_g.journals(before: before, limit: limit);
@override
Future<PageData> journal(String date) => _g.journal(date: date);
@override
Future<PageData?> page(String id) => _g.page(id: id);
@override
Future<PageData?> pageByTitle(String title) => _g.pageByTitle(title: title);
@override
Future<PageData> openPage(String title) => _g.openPage(title: title);
@override
Future<List<PageDto>> listPages({
bool includeJournals = false,
required int limit,
int offset = 0,
}) => _g.listPages(
includeJournals: includeJournals,
limit: limit,
offset: offset,
);
@override
Future<PageDto> renamePage(String id, String newTitle) =>
_g.renamePage(id: id, newTitle: newTitle);
@override
Future<void> deletePage(String id) => _g.deletePage(id: id);
@override
Future<void> addAlias(String pageId, String alias) =>
_g.addAlias(pageId: pageId, alias: alias);
@override
Future<void> removeAlias(String alias) => _g.removeAlias(alias: alias);
@override
Future<BlockDto> insertBlock(String pageId, Place place, String content) =>
_g.insertBlock(pageId: pageId, place: place, content: content);
@override
Future<void> updateBlock(String id, String content) =>
_g.updateBlock(id: id, content: content);
@override
Future<void> setCollapsed(String id, bool collapsed) =>
_g.setCollapsed(id: id, collapsed: collapsed);
@override
Future<List<BlockDto>> deleteBlock(String id) => _g.deleteBlock(id: id);
@override
Future<List<BlockDto>> moveBlock(String id, String pageId, Place place) =>
_g.moveBlock(id: id, pageId: pageId, place: place);
@override
Future<List<BlockDto>> indentBlock(String id) => _g.indentBlock(id: id);
@override
Future<List<BlockDto>> outdentBlock(String id) => _g.outdentBlock(id: id);
@override
Future<List<BlockDto>> mergeBlock(String id, String into) =>
_g.mergeBlock(id: id, into: into);
@override
Future<List<BlockDto>> outline(String pageId) => _g.outline(pageId: pageId);
@override
Future<List<BacklinkGroup>> backlinks(String pageId) =>
_g.backlinks(pageId: pageId);
@override
Future<List<RelatedDto>> related(String pageId, {int limit = 12}) =>
_g.related(pageId: pageId, limit: limit);
@override
Future<void> recordVisit(String? from, String to) =>
_g.recordVisit(from: from, to: to);
@override
Future<BlockRefDto?> blockRef(String id) => _g.blockRef(id: id);
@override
Future<TimelineDto> timeline(String from, String to) =>
_g.timeline(from: from, to: to);
@override
Future<List<TitleHit>> searchTitles(String query, {int limit = 20}) =>
_g.searchTitles(query: query, limit: limit);
@override
Future<List<BlockHit>> searchBlocks(String query, {int limit = 20}) =>
_g.searchBlocks(query: query, limit: limit);
@override
String? assetPath(String hash) => _g.assetPath(hash: hash);
@override
Future<AssetDto> putAssetFile(String path, {String? mime}) =>
_g.putAssetFile(path: path, mime: mime);
}
+875
View File
@@ -0,0 +1,875 @@
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import '../backend/graph_backend.dart';
import '../state/app_state.dart';
import '../state/outline_controller.dart';
import '../state/outline_ops.dart';
import '../theme/theme.dart';
import 'completion.dart';
import 'markdown.dart';
const indentWidth = 24.0;
const _gutter = 18.0;
const _bulletBox = 18.0;
/// What a bullet drag carries.
class BlockDrag {
const BlockDrag(this.controller, this.node);
final OutlineController controller;
final OutlineNode node;
}
enum _Drop { before, after, child }
/// One outline row: guides, collapse arrow, bullet (drag handle) and the block itself,
/// rendered when idle and a raw-Markdown editor when focused.
class BlockRow extends StatefulWidget {
const BlockRow({
super.key,
required this.controller,
required this.node,
required this.editing,
required this.hasChildren,
});
final OutlineController controller;
final OutlineNode node;
final bool editing;
final bool hasChildren;
@override
State<BlockRow> createState() => _BlockRowState();
}
class _BlockRowState extends State<BlockRow> {
bool _hover = false;
_Drop? _drop;
OutlineController get c => widget.controller;
OutlineNode get n => widget.node;
@override
Widget build(BuildContext context) {
final colors = context.colors;
final depth = n.depth;
final lineH = blockFontSize * blockLineHeight;
return DragTarget<BlockDrag>(
onWillAcceptWithDetails: (d) =>
d.data.controller == c && d.data.node != n,
onMove: (d) => _updateDrop(d.offset),
onLeave: (_) => setState(() => _drop = null),
onAcceptWithDetails: (d) {
final drop = _drop;
setState(() => _drop = null);
if (drop == null) return;
c.moveTo(d.data.node, switch (drop) {
_Drop.before => PlaceKind.before,
_Drop.after => PlaceKind.after,
_Drop.child => PlaceKind.firstChildOf,
}, n);
},
builder: (context, _, _) => MouseRegion(
onEnter: (_) => setState(() => _hover = true),
onExit: (_) => setState(() => _hover = false),
child: CustomPaint(
painter: _GuidesPainter(depth, colors.line, _drop, colors.accent),
child: Padding(
padding: EdgeInsets.only(left: depth * indentWidth),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(
width: _gutter,
height: lineH + 4,
child: (widget.hasChildren && (_hover || n.collapsed))
? _Arrow(
collapsed: n.collapsed,
onTap: () => c.toggleCollapsed(n),
)
: null,
),
_bullet(colors, lineH),
const SizedBox(width: 6),
Expanded(
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 2),
child: widget.editing
? BlockEditor(
key: ValueKey('edit-${identityHashCode(n)}'),
controller: c,
node: n,
)
: BlockView(controller: c, node: n),
),
),
],
),
),
),
),
);
}
Widget _bullet(SynapseColors colors, double lineH) {
final collapsedWithKids = n.collapsed && widget.hasChildren;
final dot = SizedBox(
width: _bulletBox,
height: lineH + 4,
child: Center(
child: AnimatedContainer(
duration: const Duration(milliseconds: 120),
width: 16,
height: 16,
decoration: BoxDecoration(
shape: BoxShape.circle,
color: collapsedWithKids ? colors.line : Colors.transparent,
),
child: Center(
child: Container(
width: 6,
height: 6,
decoration: BoxDecoration(
shape: BoxShape.circle,
color: _hover ? colors.muted : colors.faint,
),
),
),
),
),
);
return Draggable<BlockDrag>(
data: BlockDrag(c, n),
dragAnchorStrategy: pointerDragAnchorStrategy,
feedback: _DragFeedback(text: n.content),
childWhenDragging: Opacity(opacity: 0.3, child: dot),
child: MouseRegion(
cursor: SystemMouseCursors.grab,
child: GestureDetector(
onTap: widget.hasChildren ? () => c.toggleCollapsed(n) : null,
child: dot,
),
),
);
}
void _updateDrop(Offset global) {
final box = context.findRenderObject() as RenderBox?;
if (box == null) return;
final p = box.globalToLocal(global);
final contentX = n.depth * indentWidth + _gutter + _bulletBox;
final _Drop d;
if (p.dy < box.size.height / 2) {
d = _Drop.before;
} else {
d = p.dx > contentX + 28 ? _Drop.child : _Drop.after;
}
if (d != _drop) setState(() => _drop = d);
}
}
class _Arrow extends StatelessWidget {
const _Arrow({required this.collapsed, required this.onTap});
final bool collapsed;
final VoidCallback onTap;
@override
Widget build(BuildContext context) => MouseRegion(
cursor: SystemMouseCursors.click,
child: GestureDetector(
onTap: onTap,
child: Center(
child: AnimatedRotation(
turns: collapsed ? 0 : 0.25,
duration: const Duration(milliseconds: 140),
child: Icon(
Icons.chevron_right_rounded,
size: 16,
color: context.colors.faint,
),
),
),
),
);
}
class _DragFeedback extends StatelessWidget {
const _DragFeedback({required this.text});
final String text;
@override
Widget build(BuildContext context) {
final colors = context.colors;
return Material(
color: Colors.transparent,
child: Container(
constraints: const BoxConstraints(maxWidth: 320),
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
decoration: BoxDecoration(
color: colors.paper,
borderRadius: BorderRadius.circular(8),
border: Border.all(color: colors.line),
boxShadow: [
BoxShadow(
color: Colors.black.withAlpha(0x22),
blurRadius: 16,
offset: const Offset(0, 6),
),
],
),
child: Text(
text.split('\n').first,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(fontSize: 14, color: colors.ink),
),
),
);
}
}
/// Vertical indent guides plus the drop indicator.
class _GuidesPainter extends CustomPainter {
_GuidesPainter(this.depth, this.color, this.drop, this.accent);
final int depth;
final Color color;
final _Drop? drop;
final Color accent;
@override
void paint(Canvas canvas, Size size) {
final p = Paint()
..color = color
..strokeWidth = 1;
for (var k = 0; k < depth; k++) {
final x = k * indentWidth + _gutter + _bulletBox / 2;
canvas.drawLine(Offset(x, 0), Offset(x, size.height), p);
}
if (drop != null) {
final a = Paint()
..color = accent
..strokeWidth = 2
..strokeCap = StrokeCap.round;
var x = depth * indentWidth + _gutter;
if (drop == _Drop.child) x += indentWidth;
final y = drop == _Drop.before ? 1.0 : size.height - 1;
canvas.drawLine(Offset(x, y), Offset(size.width - 8, y), a);
}
}
@override
bool shouldRepaint(_GuidesPainter old) =>
old.depth != depth ||
old.drop != drop ||
old.color != color ||
old.accent != accent;
}
TextStyle blockTextStyle(BuildContext context) => TextStyle(
fontFamily: uiFont,
fontSize: blockFontSize,
height: blockLineHeight,
color: context.colors.ink,
);
/// Rendered (read) mode of a block. A tap places the caret at the matching source offset.
class BlockView extends StatefulWidget {
const BlockView({super.key, required this.controller, required this.node});
final OutlineController controller;
final OutlineNode node;
@override
State<BlockView> createState() => _BlockViewState();
}
class _BlockViewState extends State<BlockView> {
final _key = GlobalKey();
RenderedBlock? _rendered;
String? _renderedFor;
Object? _renderedTheme;
double _width = 0;
@override
void dispose() {
_rendered?.dispose();
super.dispose();
}
RenderedBlock _render(BuildContext context, double width) {
final content = widget.node.content;
final theme = Theme.of(context);
if (_rendered != null &&
_renderedFor == content &&
_renderedTheme == theme &&
_width == width) {
return _rendered!;
}
_rendered?.dispose();
final app = AppScope.read(context);
final ctx = RenderContext(
colors: context.colors,
base: blockTextStyle(context),
refs: app.refs,
assetPath: app.backend.assetPath,
onPage: app.openTitle,
onBlockRef: (r) => app.openId(r.pageId),
onUrl: openUrl,
onToggleTodo: () => widget.controller.cycleTodo(widget.node),
maxWidth: width,
);
_renderedFor = content;
_renderedTheme = theme;
_width = width;
return _rendered = BlockRenderer(ctx).render(content);
}
void _tap(TapUpDetails d) {
final rp = _key.currentContext?.findRenderObject();
var caret = widget.node.content.length;
if (rp is RenderParagraph && _rendered != null) {
final local = rp.globalToLocal(d.globalPosition);
if (local.dy <= rp.size.height) {
caret = _rendered!.toSource(rp.getPositionForOffset(local).offset);
}
}
widget.controller.focus(widget.node.id, caret: caret);
}
@override
Widget build(BuildContext context) {
final app = AppScope.read(context);
final hasRef = widget.node.content.contains('((');
Widget build(double width) {
final r = _render(context, width);
return Text.rich(r.span, key: _key);
}
return LayoutBuilder(
builder: (context, box) => MouseRegion(
cursor: SystemMouseCursors.text,
child: GestureDetector(
behavior: HitTestBehavior.opaque,
onTapUp: _tap,
child: ConstrainedBox(
constraints: const BoxConstraints(
minHeight: blockFontSize * blockLineHeight,
),
child: hasRef
? ListenableBuilder(
listenable: app.refs,
builder: (context, _) {
_renderedFor = null;
return build(box.maxWidth);
},
)
: build(box.maxWidth),
),
),
),
);
}
}
/// Opens an external link. Replaced at startup with a platform launcher.
void Function(String url) openUrl = (url) {};
/// Edit mode of a block: raw Markdown with outliner key handling and autocomplete.
class BlockEditor extends StatefulWidget {
const BlockEditor({super.key, required this.controller, required this.node});
final OutlineController controller;
final OutlineNode node;
@override
State<BlockEditor> createState() => _BlockEditorState();
}
class _BlockEditorState extends State<BlockEditor> {
late final TextEditingController _text;
late final FocusNode _focus;
final _fieldKey = GlobalKey();
final _link = LayerLink();
final _portal = OverlayPortalController();
TextEditingValue _last = TextEditingValue.empty;
bool _allowNewline = false;
CompletionQuery? _query;
List<CompletionItem> _items = const [];
int _selected = 0;
int _searchSeq = 0;
OutlineController get c => widget.controller;
OutlineNode get n => widget.node;
@override
void initState() {
super.initState();
final caret = (c.pendingCaret ?? n.content.length).clamp(
0,
n.content.length,
);
c.pendingCaret = null;
_text = TextEditingController.fromValue(
TextEditingValue(
text: n.content,
selection: TextSelection.collapsed(offset: caret),
),
);
_last = _text.value;
_focus = FocusNode(debugLabel: 'block', onKeyEvent: _onKey);
_focus.addListener(_focusChanged);
c.addListener(_controllerChanged);
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted) _focus.requestFocus();
});
}
@override
void dispose() {
c.removeListener(_controllerChanged);
_focus.removeListener(_focusChanged);
_focus.dispose();
_text.dispose();
super.dispose();
}
void _focusChanged() {
if (!_focus.hasFocus) {
_closeCompletion();
// Defer: focus may be moving to another block of the same outline.
scheduleMicrotask(() {
if (mounted && !_focus.hasFocus) c.blurred(n.id);
});
}
}
/// Applies caret requests and external content changes (merges, todo toggles).
void _controllerChanged() {
if (!mounted || c.focusedId != n.id) return;
final caret = c.pendingCaret;
if (n.content != _text.text || caret != null) {
c.pendingCaret = null;
final off = (caret ?? _text.selection.extentOffset).clamp(
0,
n.content.length,
);
_text.value = TextEditingValue(
text: n.content,
selection: TextSelection.collapsed(offset: off),
);
_last = _text.value;
}
if (!_focus.hasFocus) {
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted && c.focusedId == n.id) _focus.requestFocus();
});
}
}
void _onChanged(String _) {
var v = _text.value;
// A newline that did not come from Shift+Enter (soft keyboards send Enter as text):
// split the block instead.
if (!_allowNewline &&
v.text.length == _last.text.length + 1 &&
v.selection.isCollapsed &&
v.selection.baseOffset > 0 &&
v.text[v.selection.baseOffset - 1] == '\n') {
final at = v.selection.baseOffset - 1;
final restored = v.text.substring(0, at) + v.text.substring(at + 1);
c.setText(n, restored);
c.split(n, at);
return;
}
_allowNewline = false;
final paired = autoPair(_last, v);
if (paired != null) {
_text.value = paired;
v = paired;
}
_last = v;
c.setText(n, v.text);
_updateCompletion();
}
// -------------------------------------------------------- completion
void _updateCompletion() {
final sel = _text.selection;
final q = sel.isCollapsed
? detectCompletion(_text.text, sel.baseOffset)
: null;
if (q == null || (q.kind == CompletionKind.tag && q.query.isEmpty)) {
_closeCompletion();
return;
}
if (q == _query) return;
_query = q;
final seq = ++_searchSeq;
final backend = c.backend;
Future<List<CompletionItem>> search() async {
if (q.kind == CompletionKind.block) {
final hits = await backend.searchBlocks(q.query, limit: 8);
return [
for (final h in hits)
if (h.id != n.id)
CompletionItem(
h.content.split('\n').first,
h.id,
detail: h.pageTitle,
),
];
}
final hits = await backend.searchTitles(q.query, limit: 8);
final items = [
for (final h in hits)
CompletionItem(h.title, h.title, detail: h.isAlias ? 'alias' : null),
];
final query = q.query.trim();
if (query.isNotEmpty &&
!items.any((i) => i.value.toLowerCase() == query.toLowerCase())) {
items.add(CompletionItem(query, query, isNew: true));
}
return items;
}
search().then((items) {
if (!mounted || seq != _searchSeq) return;
setState(() {
_items = items;
_selected = 0;
});
if (items.isEmpty) {
_portal.hide();
} else {
_portal.show();
}
}, onError: (Object _) {});
}
void _closeCompletion() {
_searchSeq++;
_query = null;
if (_items.isNotEmpty && mounted) setState(() => _items = const []);
if (_portal.isShowing) _portal.hide();
}
bool get _completing => _query != null && _items.isNotEmpty;
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],
);
_closeCompletion();
_text.value = v;
_last = v;
c.setText(n, v.text);
}
// -------------------------------------------------------------- keys
RenderEditable? _editable() {
RenderEditable? found;
void visit(RenderObject o) {
if (found != null) return;
if (o is RenderEditable) {
found = o;
return;
}
o.visitChildren(visit);
}
final ro = _fieldKey.currentContext?.findRenderObject();
if (ro != null) visit(ro);
return found;
}
/// Whether the caret is on the first (or last) visual line, wrapping included.
bool _onEdgeLine({required bool top}) {
final re = _editable();
if (re == null || !re.hasSize) return true;
final caret = _text.selection.extentOffset;
final rect = re.getLocalRectForCaret(TextPosition(offset: caret));
final lh = re.preferredLineHeight;
return top ? rect.top < lh * 0.5 : rect.bottom > re.size.height - lh * 0.5;
}
int get _column {
final caret = _text.selection.extentOffset;
final lineStart =
_text.text.lastIndexOf('\n', caret == 0 ? 0 : caret - 1) + 1;
return caret - lineStart;
}
KeyEventResult _onKey(FocusNode _, KeyEvent e) {
if (e is! KeyDownEvent && e is! KeyRepeatEvent) {
return KeyEventResult.ignored;
}
final kb = HardwareKeyboard.instance;
final shift = kb.isShiftPressed;
final ctrl = kb.isControlPressed || kb.isMetaPressed;
final alt = kb.isAltPressed;
final key = e.logicalKey;
final sel = _text.selection;
final collapsed = sel.isValid && sel.isCollapsed;
final caret = sel.isValid ? sel.extentOffset : _text.text.length;
final len = _text.text.length;
if (_completing) {
if (key == LogicalKeyboardKey.arrowDown) {
setState(() => _selected = (_selected + 1) % _items.length);
return KeyEventResult.handled;
}
if (key == LogicalKeyboardKey.arrowUp) {
setState(
() => _selected = (_selected - 1 + _items.length) % _items.length,
);
return KeyEventResult.handled;
}
if (key == LogicalKeyboardKey.enter ||
key == LogicalKeyboardKey.numpadEnter ||
key == LogicalKeyboardKey.tab) {
_accept(_selected);
return KeyEventResult.handled;
}
if (key == LogicalKeyboardKey.escape) {
_closeCompletion();
return KeyEventResult.handled;
}
}
if (key == LogicalKeyboardKey.enter ||
key == LogicalKeyboardKey.numpadEnter) {
if (shift) {
_allowNewline = true;
return KeyEventResult.ignored;
}
if (ctrl) {
final shiftBy = c.cycleTodo(n);
c.pendingCaret = (caret + shiftBy).clamp(0, n.content.length);
_controllerChanged();
return KeyEventResult.handled;
}
if (sel.isValid && !collapsed) {
c.setText(n, _text.text.replaceRange(sel.start, sel.end, ''));
}
c.split(n, sel.isValid ? sel.start : len);
return KeyEventResult.handled;
}
if (key == LogicalKeyboardKey.tab) {
if (shift) {
c.outdent(n, caret: caret);
} else {
c.indent(n, caret: caret);
}
return KeyEventResult.handled;
}
if (key == LogicalKeyboardKey.backspace &&
collapsed &&
caret == 0 &&
!ctrl) {
return c.mergeIntoPrevious(n)
? KeyEventResult.handled
: KeyEventResult.ignored;
}
if (key == LogicalKeyboardKey.delete &&
collapsed &&
caret == len &&
!ctrl) {
return c.mergeNext(n) ? KeyEventResult.handled : KeyEventResult.ignored;
}
if (key == LogicalKeyboardKey.arrowUp ||
key == LogicalKeyboardKey.arrowDown) {
final up = key == LogicalKeyboardKey.arrowUp;
if (alt && shift) {
c.moveAmongSiblings(n, up: up, caret: caret);
return KeyEventResult.handled;
}
if (ctrl && !shift && !alt) {
if (up != n.collapsed && c.hasChildren(n)) c.toggleCollapsed(n);
return KeyEventResult.handled;
}
if (shift || alt || ctrl) return KeyEventResult.ignored;
if (!_onEdgeLine(top: up)) return KeyEventResult.ignored;
final other = up ? c.previousVisible(n) : c.nextVisible(n);
if (other == null) return KeyEventResult.ignored;
final col = _column;
final t = other.content;
final int target;
if (up) {
final ls = t.lastIndexOf('\n') + 1;
target = ls + col.clamp(0, t.length - ls);
} else {
final le = t.indexOf('\n');
target = col.clamp(0, le < 0 ? t.length : le);
}
c.focus(other.id, caret: target);
return KeyEventResult.handled;
}
if (!shift && !ctrl && !alt && collapsed) {
if (key == LogicalKeyboardKey.arrowLeft && caret == 0) {
final prev = c.previousVisible(n);
if (prev != null) {
c.focus(prev.id, caret: prev.content.length);
return KeyEventResult.handled;
}
}
if (key == LogicalKeyboardKey.arrowRight && caret == len) {
final next = c.nextVisible(n);
if (next != null) {
c.focus(next.id, caret: 0);
return KeyEventResult.handled;
}
}
}
if (key == LogicalKeyboardKey.escape) {
_focus.unfocus();
return KeyEventResult.handled;
}
return KeyEventResult.ignored;
}
@override
Widget build(BuildContext context) {
final colors = context.colors;
return CompositedTransformTarget(
link: _link,
child: OverlayPortal(
controller: _portal,
overlayChildBuilder: (context) => CompositedTransformFollower(
link: _link,
targetAnchor: Alignment.bottomLeft,
offset: const Offset(0, 4),
child: Align(
alignment: Alignment.topLeft,
child: TextFieldTapRegion(
child: CompletionPopup(
items: _items,
selected: _selected,
kind: _query?.kind ?? CompletionKind.page,
onSelect: _accept,
),
),
),
),
child: TextField(
key: _fieldKey,
controller: _text,
focusNode: _focus,
onChanged: _onChanged,
maxLines: null,
keyboardType: TextInputType.multiline,
textInputAction: TextInputAction.newline,
style: blockTextStyle(context).copyWith(fontFamily: uiFont),
cursorColor: colors.accent,
cursorWidth: 1.6,
decoration: const InputDecoration.collapsed(hintText: null),
),
),
);
}
}
class CompletionPopup extends StatelessWidget {
const CompletionPopup({
super.key,
required this.items,
required this.selected,
required this.kind,
required this.onSelect,
});
final List<CompletionItem> items;
final int selected;
final CompletionKind kind;
final void Function(int) onSelect;
@override
Widget build(BuildContext context) {
final colors = context.colors;
return Material(
color: colors.paper,
elevation: 0,
borderRadius: BorderRadius.circular(10),
child: Container(
width: 340,
padding: const EdgeInsets.all(4),
decoration: BoxDecoration(
color: colors.paper,
borderRadius: BorderRadius.circular(10),
border: Border.all(color: colors.line),
boxShadow: [
BoxShadow(
color: Colors.black.withAlpha(0x1F),
blurRadius: 24,
offset: const Offset(0, 8),
),
],
),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
for (var i = 0; i < items.length; i++)
MouseRegion(
cursor: SystemMouseCursors.click,
child: GestureDetector(
onTap: () => onSelect(i),
child: Container(
padding: const EdgeInsets.symmetric(
horizontal: 10,
vertical: 7,
),
decoration: BoxDecoration(
color: i == selected ? colors.accentSoft : null,
borderRadius: BorderRadius.circular(7),
),
child: Row(
children: [
Icon(
items[i].isNew
? Icons.add_rounded
: kind == CompletionKind.block
? Icons.notes_rounded
: kind == CompletionKind.tag
? Icons.tag_rounded
: Icons.description_outlined,
size: 15,
color: i == selected ? colors.accent : colors.muted,
),
const SizedBox(width: 8),
Expanded(
child: Text(
items[i].isNew
? 'New page “${items[i].label}”'
: items[i].label,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(fontSize: 13.5, color: colors.ink),
),
),
if (items[i].detail != null) ...[
const SizedBox(width: 8),
Text(
items[i].detail!,
style: TextStyle(fontSize: 12, color: colors.faint),
),
],
],
),
),
),
),
],
),
),
);
}
}
+141
View File
@@ -0,0 +1,141 @@
import 'package:flutter/services.dart';
enum CompletionKind { page, tag, block }
/// An autocomplete trigger under the caret: `[[query`, `#query` or `((query`.
class CompletionQuery {
const CompletionQuery(this.kind, this.start, this.query);
final CompletionKind kind;
/// Index where the query text starts (right after the trigger).
final int start;
final String query;
@override
bool operator ==(Object other) =>
other is CompletionQuery &&
other.kind == kind &&
other.start == start &&
other.query == query;
@override
int get hashCode => Object.hash(kind, start, query);
}
/// One suggestion. `value` is the page title or the block id to insert.
class CompletionItem {
const CompletionItem(
this.label,
this.value, {
this.detail,
this.isNew = false,
});
final String label;
final String value;
final String? detail;
final bool isNew;
}
bool _ws(String c) => c.trim().isEmpty;
/// Finds the autocomplete trigger that the caret is in, if any.
CompletionQuery? detectCompletion(String text, int caret) {
if (caret < 0 || caret > text.length) return null;
final lineStart = text.lastIndexOf('\n', caret == 0 ? 0 : caret - 1) + 1;
final before = text.substring(lineStart, caret);
CompletionQuery? best;
void consider(CompletionQuery q) {
if (best == null || q.start > best!.start) best = q;
}
final link = before.lastIndexOf('[[');
if (link >= 0 && !before.substring(link + 2).contains(']]')) {
consider(
CompletionQuery(
CompletionKind.page,
lineStart + link + 2,
before.substring(link + 2),
),
);
}
final ref = before.lastIndexOf('((');
if (ref >= 0 && !before.substring(ref + 2).contains('))')) {
consider(
CompletionQuery(
CompletionKind.block,
lineStart + ref + 2,
before.substring(ref + 2),
),
);
}
final hash = before.lastIndexOf('#');
if (hash >= 0 && (hash == 0 || _ws(before[hash - 1]))) {
final q = before.substring(hash + 1);
if (!q.startsWith('[') &&
!q.contains(RegExp(r'\s')) &&
!q.startsWith('#')) {
// A bare `#` followed by a space is a heading, not a tag.
consider(CompletionQuery(CompletionKind.tag, lineStart + hash + 1, q));
}
}
return best;
}
/// Text after accepting `item` for `q` with the caret at `caret`.
TextEditingValue applyCompletion(
String text,
int caret,
CompletionQuery q,
CompletionItem item,
) {
final head = text.substring(0, q.start);
var tail = text.substring(caret);
switch (q.kind) {
case CompletionKind.page:
if (tail.startsWith(']]')) tail = tail.substring(2);
final t = '$head${item.value}]]';
return TextEditingValue(
text: t + tail,
selection: TextSelection.collapsed(offset: t.length),
);
case CompletionKind.block:
if (tail.startsWith('))')) tail = tail.substring(2);
final t = '$head${item.value}))';
return TextEditingValue(
text: t + tail,
selection: TextSelection.collapsed(offset: t.length),
);
case CompletionKind.tag:
final v = item.value.contains(RegExp(r'\s'))
? '[[${item.value}]]'
: item.value;
final sep = tail.startsWith(' ') ? '' : ' ';
final t = '$head$v$sep';
return TextEditingValue(
text: t + tail,
selection: TextSelection.collapsed(offset: t.length),
);
}
}
/// Auto-pairs `[[` → `[[]]` and `((` → `(())` right after the second bracket is typed.
TextEditingValue? autoPair(TextEditingValue old, TextEditingValue now) {
if (now.text.length != old.text.length + 1 || !now.selection.isCollapsed) {
return null;
}
final c = now.selection.baseOffset;
if (c < 2) return null;
final typed = now.text[c - 1];
final close = switch (typed) {
'[' => ']]',
'(' => '))',
_ => null,
};
if (close == null || now.text[c - 2] != typed) return null;
if (now.text.substring(c).startsWith(close[0])) return null;
return TextEditingValue(
text: now.text.substring(0, c) + close + now.text.substring(c),
selection: TextSelection.collapsed(offset: c),
);
}
+638
View File
@@ -0,0 +1,638 @@
import 'dart:io';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import '../state/app_state.dart';
import '../theme/theme.dart';
/// Maps a run of rendered text back to its Markdown source, so a tap on rendered text can
/// place the caret at the matching spot of the raw text.
class SourceRun {
const SourceRun(
this.r0,
this.rLen,
this.s0,
this.sLen, {
this.atomic = false,
});
final int r0;
final int rLen;
final int s0;
final int sLen;
/// Rendered differently from the source (widgets, resolved refs): maps to its end.
final bool atomic;
}
/// A rendered block: its span tree, the source mapping and the recognizers to dispose.
class RenderedBlock {
RenderedBlock(this.span, this.runs, this.recognizers);
final InlineSpan span;
final List<SourceRun> runs;
final List<GestureRecognizer> recognizers;
/// Source offset for a rendered text offset.
int toSource(int rendered) {
SourceRun? best;
for (final r in runs) {
if (rendered < r.r0) break;
best = r;
if (rendered < r.r0 + r.rLen) break;
}
if (best == null) return 0;
if (best.atomic) return best.s0 + best.sLen;
final d = (rendered - best.r0).clamp(0, best.sLen);
return best.s0 + d;
}
void dispose() {
for (final r in recognizers) {
r.dispose();
}
}
}
/// Callbacks and context for rendering.
class RenderContext {
const RenderContext({
required this.colors,
required this.base,
required this.refs,
required this.assetPath,
required this.onPage,
required this.onBlockRef,
required this.onUrl,
this.onToggleTodo,
this.maxWidth = 600,
});
final SynapseColors colors;
final TextStyle base;
final BlockRefCache refs;
final String? Function(String hash) assetPath;
final void Function(String title) onPage;
final void Function(BlockRefDtoLike ref) onBlockRef;
final void Function(String url) onUrl;
final VoidCallback? onToggleTodo;
final double maxWidth;
}
/// The bits of a block ref the renderer needs (keeps this file free of FFI types).
class BlockRefDtoLike {
const BlockRefDtoLike(this.id, this.pageId);
final String id;
final String pageId;
}
final _marker = RegExp(r'^(TODO|DOING|NOW|LATER|DONE|CANCELED|CANCELLED) ');
final _heading = RegExp(r'^(#{1,6}) ');
final _uuid = RegExp(
r'^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$',
);
final _property = RegExp(r'^([A-Za-z0-9_\-]+):: ?(.*)$');
/// Renders Logseq-flavoured Markdown of one block into a single [InlineSpan] tree.
class BlockRenderer {
BlockRenderer(this.ctx);
final RenderContext ctx;
final _spans = <InlineSpan>[];
final _runs = <SourceRun>[];
final _recognizers = <GestureRecognizer>[];
int _r = 0;
RenderedBlock render(String src) {
final lines = src.split('\n');
var off = 0;
var fenceStart = -1;
final fence = StringBuffer();
for (var li = 0; li < lines.length; li++) {
final line = lines[li];
final lineStart = off;
off += line.length + 1;
if (fenceStart >= 0) {
if (line.trimLeft().startsWith('```')) {
_codeBlock(fence.toString(), fenceStart, off - 1 - fenceStart);
fenceStart = -1;
fence.clear();
} else {
if (fence.isNotEmpty) fence.write('\n');
fence.write(line);
}
continue;
}
if (li > 0) _text('\n', lineStart - 1, ctx.base);
if (line.trimLeft().startsWith('```')) {
fenceStart = lineStart;
continue;
}
_line(line, lineStart, first: li == 0);
}
if (fenceStart >= 0) {
_codeBlock(fence.toString(), fenceStart, src.length - fenceStart);
}
return RenderedBlock(
TextSpan(style: ctx.base, children: List.of(_spans)),
List.of(_runs),
List.of(_recognizers),
);
}
void _line(String line, int off, {required bool first}) {
var style = ctx.base;
var i = 0;
if (first) {
final m = _marker.firstMatch(line);
if (m != null) {
final done = m.group(1) == 'DONE';
final canceled = m.group(1)!.startsWith('CANCEL');
_atomic(_checkbox(done || canceled), 1, off, m.end);
if (done || canceled) {
style = style.copyWith(
color: ctx.colors.muted,
decoration: TextDecoration.lineThrough,
decorationColor: ctx.colors.faint,
);
} else if (m.group(1) != 'TODO' && m.group(1) != 'LATER') {
_text(
'${m.group(1)} ',
off,
style.copyWith(
color: ctx.colors.accent,
fontSize: 12,
fontWeight: FontWeight.w600,
),
);
}
i = m.end;
}
}
final rest = line.substring(i);
final h = _heading.firstMatch(rest);
if (h != null) {
final level = h.group(1)!.length;
const sizes = [26.0, 22.0, 19.0, 17.0, 16.0, 15.0];
style = style.copyWith(
fontSize: sizes[level - 1],
fontWeight: level <= 2 ? FontWeight.w700 : FontWeight.w600,
height: 1.35,
letterSpacing: level <= 2 ? -0.2 : 0,
);
_inline(rest.substring(h.end), off + i + h.end, style);
return;
}
final p = _property.firstMatch(rest);
if (p != null) {
final small = style.copyWith(fontSize: 13, color: ctx.colors.muted);
_text(
'${p.group(1)}: ',
off + i,
small.copyWith(fontWeight: FontWeight.w600),
);
_inline(p.group(2)!, off + i + rest.length - p.group(2)!.length, small);
return;
}
if (rest.startsWith('> ')) {
_atomic(
WidgetSpan(
alignment: PlaceholderAlignment.middle,
child: Container(
width: 3,
height: 18,
margin: const EdgeInsets.only(right: 8),
color: ctx.colors.line,
),
),
1,
off + i,
2,
);
_inline(
rest.substring(2),
off + i + 2,
style.copyWith(color: ctx.colors.muted, fontStyle: FontStyle.italic),
);
return;
}
final list = RegExp(r'^(\s*)([-*+]|\d+\.) ').firstMatch(rest);
if (list != null) {
final bullet = list.group(2)!.endsWith('.') ? list.group(2)! : '•';
_atomic(
TextSpan(
text: '${list.group(1)}$bullet ',
style: style.copyWith(color: ctx.colors.muted),
),
list.group(1)!.length + bullet.length + 1,
off + i,
list.end,
);
_inline(rest.substring(list.end), off + i + list.end, style);
return;
}
_inline(rest, off + i, style);
}
void _inline(String s, int off, TextStyle style) {
var i = 0;
var plain = 0;
void flush(int to) {
if (to > plain) _text(s.substring(plain, to), off + plain, style);
}
bool ws(int k) => k < 0 || k >= s.length || s[k].trim().isEmpty;
while (i < s.length) {
final c = s[i];
// `code`
if (c == '`') {
final j = s.indexOf('`', i + 1);
if (j > i + 1) {
flush(i);
_text(
s.substring(i + 1, j),
off + i + 1,
style.copyWith(
fontFamily: monoFont,
fontSize: (style.fontSize ?? blockFontSize) - 1.5,
backgroundColor: ctx.colors.codeBg,
color: ctx.colors.ink,
),
);
i = plain = j + 1;
continue;
}
}
// ![alt](src)
if (s.startsWith('![', i)) {
final link = _mdLink(s, i + 1);
if (link != null) {
flush(i);
_atomic(_image(link.$2, link.$1), 1, off + i, link.$3 - i);
i = plain = link.$3;
continue;
}
}
// [[Page]]
if (s.startsWith('[[', i)) {
final close = _findClose(s, i + 2);
if (close != null && close > i + 2) {
flush(i);
final title = s.substring(i + 2, close);
_text(
title,
off + i + 2,
style.copyWith(
color: ctx.colors.accent,
fontWeight: FontWeight.w500,
),
onTap: () => ctx.onPage(title),
);
i = plain = close + 2;
continue;
}
}
// ((block ref))
if (s.startsWith('((', i)) {
final j = s.indexOf('))', i + 2);
if (j > 0 && _uuid.hasMatch(s.substring(i + 2, j))) {
flush(i);
_blockRef(s.substring(i + 2, j), off + i, j + 2 - i, style);
i = plain = j + 2;
continue;
}
}
// #tag, #[[tag]]
if (c == '#' && ws(i - 1) && i + 1 < s.length) {
String? tag;
var end = i;
if (s.startsWith('#[[', i)) {
final close = _findClose(s, i + 3);
if (close != null && close > i + 3) {
tag = s.substring(i + 3, close);
end = close + 2;
}
} else {
var j = i + 1;
while (j < s.length && !_tagStop(s[j])) {
j++;
}
// Trailing punctuation is not part of the tag.
while (j > i + 1 && '.!?;:'.contains(s[j - 1])) {
j--;
}
if (j > i + 1) {
tag = s.substring(i + 1, j);
end = j;
}
}
if (tag != null) {
flush(i);
final t = tag;
final tagStyle = style.copyWith(
color: ctx.colors.accent.withAlpha(0xCC),
);
if (end - i == t.length + 1) {
_text('#$t', off + i, tagStyle, onTap: () => ctx.onPage(t));
} else {
_text('#', off + i, tagStyle, onTap: () => ctx.onPage(t));
_text(t, off + i + 3, tagStyle, onTap: () => ctx.onPage(t));
}
i = plain = end;
continue;
}
}
// **bold**, __bold__, ~~strike~~, ==highlight==
final pair = s.length > i + 1 ? s.substring(i, i + 2) : '';
if (pair == '**' || pair == '__' || pair == '~~' || pair == '==') {
final j = s.indexOf(pair, i + 2);
if (j > i + 2) {
flush(i);
final inner = switch (pair) {
'~~' => style.copyWith(
decoration: TextDecoration.lineThrough,
color: ctx.colors.muted,
),
'==' => style.copyWith(backgroundColor: ctx.colors.highlight),
_ => style.copyWith(fontWeight: FontWeight.w700),
};
_inline(s.substring(i + 2, j), off + i + 2, inner);
i = plain = j + 2;
continue;
}
}
// *italic*, _italic_
if ((c == '*' || (c == '_' && ws(i - 1))) &&
i + 1 < s.length &&
!ws(i + 1)) {
var j = s.indexOf(c, i + 1);
while (j > 0 && (ws(j - 1) || (c == '_' && !ws(j + 1)))) {
j = s.indexOf(c, j + 1);
}
if (j > i + 1) {
flush(i);
_inline(
s.substring(i + 1, j),
off + i + 1,
style.copyWith(fontStyle: FontStyle.italic),
);
i = plain = j + 1;
continue;
}
}
// [label](url)
if (c == '[') {
final link = _mdLink(s, i);
if (link != null) {
flush(i);
final url = link.$2;
_text(
link.$1,
off + i + 1,
style.copyWith(
color: ctx.colors.accent,
decoration: TextDecoration.underline,
decorationColor: ctx.colors.accent.withAlpha(0x66),
),
onTap: () => ctx.onUrl(url),
);
i = plain = link.$3;
continue;
}
}
// bare URL
if ((s.startsWith('https://', i) || s.startsWith('http://', i)) &&
ws(i - 1)) {
var j = i;
while (j < s.length && !ws(j)) {
j++;
}
while (j > i && '.,;:!?)'.contains(s[j - 1])) {
j--;
}
flush(i);
final url = s.substring(i, j);
_text(
url,
off + i,
style.copyWith(
color: ctx.colors.accent,
decoration: TextDecoration.underline,
decorationColor: ctx.colors.accent.withAlpha(0x66),
),
onTap: () => ctx.onUrl(url),
);
i = plain = j;
continue;
}
i++;
}
flush(s.length);
}
static bool _tagStop(String ch) =>
ch.trim().isEmpty || ',()[]{}"\'`#'.contains(ch);
/// `[label](target)` starting at `i` (the `[`): (label, target, end).
static (String, String, int)? _mdLink(String s, int i) {
if (i >= s.length || s[i] != '[') return null;
final close = s.indexOf('](', i + 1);
if (close < 0 || s.substring(i + 1, close).contains('\n')) return null;
final end = s.indexOf(')', close + 2);
if (end < 0) return null;
final target = s.substring(close + 2, end).trim();
if (target.isEmpty || target.contains(' ')) return null;
return (s.substring(i + 1, close), target, end + 1);
}
/// Index of the `]]` closing a `[[` whose content starts at `from` (nesting aware).
static int? _findClose(String s, int from) {
var depth = 1;
var i = from;
while (i < s.length - 1) {
if (s.startsWith('[[', i)) {
depth++;
i += 2;
} else if (s.startsWith(']]', i)) {
depth--;
if (depth == 0) return i;
i += 2;
} else {
if (s[i] == '\n') return null;
i++;
}
}
return null;
}
void _text(String t, int s0, TextStyle style, {VoidCallback? onTap}) {
if (t.isEmpty) return;
TapGestureRecognizer? rec;
if (onTap != null) {
rec = TapGestureRecognizer()..onTap = onTap;
_recognizers.add(rec);
}
_spans.add(
TextSpan(
text: t,
style: style,
recognizer: rec,
mouseCursor: rec == null ? null : SystemMouseCursors.click,
),
);
_runs.add(SourceRun(_r, t.length, s0, t.length));
_r += t.length;
}
void _atomic(InlineSpan span, int rLen, int s0, int sLen) {
_spans.add(span);
_runs.add(SourceRun(_r, rLen, s0, sLen, atomic: true));
_r += rLen;
}
void _blockRef(String id, int s0, int sLen, TextStyle style) {
final ref = ctx.refs.get(id);
final String text;
if (ref != null) {
final first = ref.content.split('\n').first.replaceFirst(_marker, '');
text = first.isEmpty ? '(empty block)' : first;
} else {
text = ctx.refs.isMissing(id) ? '((missing block))' : '…';
}
TapGestureRecognizer? rec;
if (ref != null) {
rec = TapGestureRecognizer()
..onTap = () => ctx.onBlockRef(BlockRefDtoLike(ref.id, ref.pageId));
_recognizers.add(rec);
}
_spans.add(
TextSpan(
text: text,
recognizer: rec,
mouseCursor: rec == null ? null : SystemMouseCursors.click,
style: style.copyWith(
decoration: TextDecoration.underline,
decorationStyle: TextDecorationStyle.dotted,
decorationColor: ctx.colors.ref,
color: ref == null ? ctx.colors.faint : null,
),
),
);
_runs.add(SourceRun(_r, text.length, s0, sLen, atomic: true));
_r += text.length;
}
InlineSpan _checkbox(bool checked) {
final c = ctx.colors;
return WidgetSpan(
alignment: PlaceholderAlignment.middle,
child: Padding(
padding: const EdgeInsets.only(right: 7),
child: MouseRegion(
cursor: SystemMouseCursors.click,
child: GestureDetector(
onTap: ctx.onToggleTodo,
child: AnimatedContainer(
duration: const Duration(milliseconds: 140),
width: 15,
height: 15,
decoration: BoxDecoration(
color: checked ? c.done : Colors.transparent,
borderRadius: BorderRadius.circular(4),
border: Border.all(
color: checked ? c.done : c.faint,
width: 1.5,
),
),
child: checked
? Icon(Icons.check_rounded, size: 12, color: c.paper)
: null,
),
),
),
),
);
}
InlineSpan _image(String src, String alt) {
Widget img;
if (src.startsWith('asset://')) {
final path = ctx.assetPath(src.substring(8));
img = path == null
? _missing(alt.isEmpty ? 'missing asset' : alt)
: Image.file(
File(path),
fit: BoxFit.contain,
cacheWidth: (ctx.maxWidth * 2).round(),
errorBuilder: (_, _, _) => _missing(alt),
);
} else if (src.startsWith('http://') || src.startsWith('https://')) {
img = Image.network(
src,
fit: BoxFit.contain,
errorBuilder: (_, _, _) => _missing(alt),
);
} else {
img = _missing(alt.isEmpty ? src : alt);
}
return WidgetSpan(
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 4),
child: ConstrainedBox(
constraints: BoxConstraints(maxHeight: 360, maxWidth: ctx.maxWidth),
child: ClipRRect(borderRadius: BorderRadius.circular(8), child: img),
),
),
);
}
Widget _missing(String label) => Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
decoration: BoxDecoration(
color: ctx.colors.surface,
borderRadius: BorderRadius.circular(6),
border: Border.all(color: ctx.colors.line),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(
Icons.image_not_supported_outlined,
size: 14,
color: ctx.colors.muted,
),
const SizedBox(width: 6),
Text(label, style: TextStyle(fontSize: 12, color: ctx.colors.muted)),
],
),
);
void _codeBlock(String code, int s0, int sLen) {
_atomic(
WidgetSpan(
child: Container(
width: ctx.maxWidth,
margin: const EdgeInsets.symmetric(vertical: 2),
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
decoration: BoxDecoration(
color: ctx.colors.codeBg,
borderRadius: BorderRadius.circular(8),
),
child: Text(
code,
style: TextStyle(
fontFamily: monoFont,
fontSize: 13,
height: 1.5,
color: ctx.colors.ink,
),
),
),
),
1,
s0,
sLen,
);
}
}
+91
View File
@@ -0,0 +1,91 @@
import 'package:flutter/material.dart';
import '../state/outline_controller.dart';
import '../state/outline_ops.dart';
import '../theme/theme.dart';
import 'block_row.dart';
/// The outline of one page as a lazily built sliver (only visible rows are built).
class OutlineSliver extends StatelessWidget {
const OutlineSliver({super.key, required this.controller});
final OutlineController controller;
@override
Widget build(BuildContext context) {
return ListenableBuilder(
listenable: controller,
builder: (context, _) {
final nodes = controller.nodes;
if (nodes.isEmpty) {
return SliverToBoxAdapter(
child: _EmptyOutline(onTap: controller.insertFirst),
);
}
final vis = controller.visible;
final keys = <Object, int>{
for (var k = 0; k < vis.length; k++) nodes[vis[k]]: k,
};
return SliverList.builder(
itemCount: vis.length,
findChildIndexCallback: (key) =>
key is ObjectKey ? keys[key.value] : null,
itemBuilder: (context, k) {
final i = vis[k];
final n = nodes[i];
return BlockRow(
key: ObjectKey(n),
controller: controller,
node: n,
editing: controller.focusedId == n.id,
hasChildren: OutlineOps.hasChildren(nodes, i),
);
},
);
},
);
}
}
class _EmptyOutline extends StatelessWidget {
const _EmptyOutline({required this.onTap});
final VoidCallback onTap;
@override
Widget build(BuildContext context) {
final colors = context.colors;
return MouseRegion(
cursor: SystemMouseCursors.text,
child: GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: onTap,
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 2),
child: Row(
children: [
const SizedBox(width: 18),
SizedBox(
width: 18,
child: Center(
child: Container(
width: 6,
height: 6,
decoration: BoxDecoration(
shape: BoxShape.circle,
color: colors.line,
),
),
),
),
const SizedBox(width: 6),
Text(
'Click to start writing…',
style: blockTextStyle(context).copyWith(color: colors.faint),
),
],
),
),
),
);
}
}
+415
View File
@@ -0,0 +1,415 @@
// 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 '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`
class AssetDto {
final String hash;
final BigInt size;
final String? mime;
final String? originalName;
const AssetDto({
required this.hash,
required this.size,
this.mime,
this.originalName,
});
@override
int get hashCode =>
hash.hashCode ^ size.hashCode ^ mime.hashCode ^ originalName.hashCode;
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is AssetDto &&
runtimeType == other.runtimeType &&
hash == other.hash &&
size == other.size &&
mime == other.mime &&
originalName == other.originalName;
}
/// Blocks of one page referencing the queried page.
class BacklinkGroup {
final String pageId;
final String pageTitle;
final bool isJournal;
final List<BlockDto> blocks;
const BacklinkGroup({
required this.pageId,
required this.pageTitle,
required this.isJournal,
required this.blocks,
});
@override
int get hashCode =>
pageId.hashCode ^
pageTitle.hashCode ^
isJournal.hashCode ^
blocks.hashCode;
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is BacklinkGroup &&
runtimeType == other.runtimeType &&
pageId == other.pageId &&
pageTitle == other.pageTitle &&
isJournal == other.isJournal &&
blocks == other.blocks;
}
/// One row of the outline, in pre-order.
class BlockDto {
final String id;
final String? parentId;
final int depth;
final String content;
final bool collapsed;
final bool hasChildren;
const BlockDto({
required this.id,
this.parentId,
required this.depth,
required this.content,
required this.collapsed,
required this.hasChildren,
});
@override
int get hashCode =>
id.hashCode ^
parentId.hashCode ^
depth.hashCode ^
content.hashCode ^
collapsed.hashCode ^
hasChildren.hashCode;
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is BlockDto &&
runtimeType == other.runtimeType &&
id == other.id &&
parentId == other.parentId &&
depth == other.depth &&
content == other.content &&
collapsed == other.collapsed &&
hasChildren == other.hasChildren;
}
/// `((` autocomplete hit.
class BlockHit {
final String id;
final String content;
final String pageTitle;
const BlockHit({
required this.id,
required this.content,
required this.pageTitle,
});
@override
int get hashCode => id.hashCode ^ content.hashCode ^ pageTitle.hashCode;
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is BlockHit &&
runtimeType == other.runtimeType &&
id == other.id &&
content == other.content &&
pageTitle == other.pageTitle;
}
/// Target of a `((block ref))`.
class BlockRefDto {
final String id;
final String content;
final String pageId;
final String pageTitle;
const BlockRefDto({
required this.id,
required this.content,
required this.pageId,
required this.pageTitle,
});
@override
int get hashCode =>
id.hashCode ^ content.hashCode ^ pageId.hashCode ^ pageTitle.hashCode;
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is BlockRefDto &&
runtimeType == other.runtimeType &&
id == other.id &&
content == other.content &&
pageId == other.pageId &&
pageTitle == other.pageTitle;
}
class EditDto {
final String pageId;
final int edits;
const EditDto({required this.pageId, required this.edits});
@override
int get hashCode => pageId.hashCode ^ edits.hashCode;
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is EditDto &&
runtimeType == other.runtimeType &&
pageId == other.pageId &&
edits == other.edits;
}
class PageBrief {
final String id;
final String title;
final bool isJournal;
const PageBrief({
required this.id,
required this.title,
required this.isJournal,
});
@override
int get hashCode => id.hashCode ^ title.hashCode ^ isJournal.hashCode;
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is PageBrief &&
runtimeType == other.runtimeType &&
id == other.id &&
title == other.title &&
isJournal == other.isJournal;
}
/// Everything the page view needs in one call.
class PageData {
final PageDto page;
final List<BlockDto> blocks;
final List<String> aliases;
/// Previous/next existing journal (journal pages only).
final String? prevJournal;
final String? nextJournal;
const PageData({
required this.page,
required this.blocks,
required this.aliases,
this.prevJournal,
this.nextJournal,
});
@override
int get hashCode =>
page.hashCode ^
blocks.hashCode ^
aliases.hashCode ^
prevJournal.hashCode ^
nextJournal.hashCode;
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is PageData &&
runtimeType == other.runtimeType &&
page == other.page &&
blocks == other.blocks &&
aliases == other.aliases &&
prevJournal == other.prevJournal &&
nextJournal == other.nextJournal;
}
/// Page header data.
class PageDto {
final String id;
final String title;
/// Set for journal pages.
final String? journalDate;
/// Journal day the page was born in.
final String? originJournal;
final PlatformInt64 createdAt;
final PlatformInt64 updatedAt;
const PageDto({
required this.id,
required this.title,
this.journalDate,
this.originJournal,
required this.createdAt,
required this.updatedAt,
});
@override
int get hashCode =>
id.hashCode ^
title.hashCode ^
journalDate.hashCode ^
originJournal.hashCode ^
createdAt.hashCode ^
updatedAt.hashCode;
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is PageDto &&
runtimeType == other.runtimeType &&
id == other.id &&
title == other.title &&
journalDate == other.journalDate &&
originJournal == other.originJournal &&
createdAt == other.createdAt &&
updatedAt == other.updatedAt;
}
class Place {
final PlaceKind kind;
final String? anchor;
const Place({required this.kind, this.anchor});
@override
int get hashCode => kind.hashCode ^ anchor.hashCode;
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is Place &&
runtimeType == other.runtimeType &&
kind == other.kind &&
anchor == other.anchor;
}
/// Where a block goes, relative to `anchor`.
enum PlaceKind {
after,
before,
/// Last child of `anchor`, or last root block when `anchor` is `None`.
lastChildOf,
/// First child of `anchor`, or first root block when `anchor` is `None`.
firstChildOf,
}
class RelatedDto {
final PageBrief page;
final double score;
const RelatedDto({required this.page, required this.score});
@override
int get hashCode => page.hashCode ^ score.hashCode;
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is RelatedDto &&
runtimeType == other.runtimeType &&
page == other.page &&
score == other.score;
}
class TimelineDayDto {
final String date;
final String? journalId;
/// Pages born on this day.
final List<String> created;
/// Pages edited on this day.
final List<EditDto> edited;
const TimelineDayDto({
required this.date,
this.journalId,
required this.created,
required this.edited,
});
@override
int get hashCode =>
date.hashCode ^ journalId.hashCode ^ created.hashCode ^ edited.hashCode;
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is TimelineDayDto &&
runtimeType == other.runtimeType &&
date == other.date &&
journalId == other.journalId &&
created == other.created &&
edited == other.edited;
}
/// Timeline slice plus the titles of every page it mentions.
class TimelineDto {
final List<TimelineDayDto> days;
final List<PageBrief> pages;
const TimelineDto({required this.days, required this.pages});
@override
int get hashCode => days.hashCode ^ pages.hashCode;
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is TimelineDto &&
runtimeType == other.runtimeType &&
days == other.days &&
pages == other.pages;
}
/// Quick switcher / `[[` autocomplete hit.
class TitleHit {
final String pageId;
/// The matched title or alias.
final String title;
final bool isAlias;
const TitleHit({
required this.pageId,
required this.title,
required this.isAlias,
});
@override
int get hashCode => pageId.hashCode ^ title.hashCode ^ isAlias.hashCode;
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is TitleHit &&
runtimeType == other.runtimeType &&
pageId == other.pageId &&
title == other.title &&
isAlias == other.isAlias;
}
+139
View File
@@ -0,0 +1,139 @@
// 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`: `asset_dto`, `lock`, `outline`, `page_view`, `parse_date`, `parse_day`, `parse_id`
// Rust type: RustOpaqueMoi<flutter_rust_bridge::for_generated::RustAutoOpaqueInner<SynapseGraph>>
abstract class SynapseGraph implements RustOpaqueInterface {
Future<void> addAlias({required String pageId, required String alias});
Future<List<String>> aliases({required String pageId});
/// Local file path of an asset (for `asset://<hash>` images), if present.
String? assetPath({required String hash});
/// Linked references grouped by page (most recently edited first).
Future<List<BacklinkGroup>> backlinks({required String pageId});
/// Target of a `((block ref))`.
Future<BlockRefDto?> blockRef({required String id});
/// Deletes a block and its subtree.
Future<List<BlockDto>> deleteBlock({required String id});
Future<void> deletePage({required String id});
/// Graph directory.
String dir();
/// Tab: the block becomes the last child of its previous sibling (no-op for a first child).
Future<List<BlockDto>> indentBlock({required String id});
Future<BlockDto> insertBlock({
required String pageId,
required Place place,
required String content,
});
/// The journal of `date` (created if missing).
Future<PageData> journal({required String date});
Future<(String?, String?)> journalNeighbors({required String date});
/// Journals feed, newest first. With `before = None` it starts at today (creating today's
/// journal); otherwise at the newest journal strictly before `before`.
Future<List<PageData>> journals({String? before, required int limit});
/// Pages ordered by last update, most recent first.
Future<List<PageDto>> listPages({
required bool includeJournals,
required int limit,
required int offset,
});
/// Backspace at the start of `id`: its text is appended to `into` (the previous visible
/// block) and the block is deleted. Its children keep their visual place: they take the
/// block's slot when `into` is its parent, otherwise they become last children of `into`.
Future<List<BlockDto>> mergeBlock({required String id, required String into});
/// Moves a block with its subtree (drag and drop), possibly to another page.
Future<List<BlockDto>> moveBlock({
required String id,
required String pageId,
required Place place,
});
/// Opens (or creates) the graph stored in `dir`.
static Future<SynapseGraph> open({required String dir}) =>
RustLib.instance.api.crateApiGraphSynapseGraphOpen(dir: dir);
/// Page by title or alias, created if missing (following a `[[link]]`). Date titles open
/// the journal of that day.
Future<PageData> openPage({required String title});
/// Shift-Tab: the block moves right after its parent, adopting its following siblings as
/// children so it keeps its visual place (Logseq's default outdenting).
Future<List<BlockDto>> outdentBlock({required String id});
/// Current outline of a page.
Future<List<BlockDto>> outline({required String pageId});
Future<PageData?> page({required String id});
/// Page by title or alias, without creating it.
Future<PageData?> pageByTitle({required String title});
/// Stores in-memory bytes (clipboard, Android content URIs).
Future<AssetDto> putAssetBytes({
required List<int> bytes,
String? name,
String? mime,
});
/// Copies a file into the blob store (streamed).
Future<AssetDto> putAssetFile({required String path, String? mime});
/// Records navigation between pages (strengthens their synapse).
Future<void> recordVisit({String? from, required String to});
/// Notes related to `page_id` by spreading activation.
Future<List<RelatedDto>> related({
required String pageId,
required int limit,
});
Future<void> removeAlias({required String alias});
Future<PageDto> renamePage({required String id, required String newTitle});
/// Blocks whose text contains `query` (for `((` autocomplete), most recent first.
Future<List<BlockHit>> searchBlocks({
required String query,
required int limit,
});
/// Page titles and aliases matching `query`: exact, then prefix, then word-prefix, then
/// substring; shorter titles first within a tier. Empty query returns recent pages.
Future<List<TitleHit>> searchTitles({
required String query,
required int limit,
});
Future<void> setCollapsed({required String id, required bool collapsed});
/// Timeline data for `[from, to]` (oldest first) with titles of every page it mentions.
Future<TimelineDto> timeline({required String from, required String to});
/// Today's date (graph clock) as `YYYY-MM-DD`.
String today();
/// Replaces a block's Markdown (the debounced save while typing).
Future<void> updateBlock({required String id, required String content});
}
File diff suppressed because it is too large. Load diff
+594
View File
@@ -0,0 +1,594 @@
// This file is automatically generated, so please do not edit it.
// @generated by `flutter_rust_bridge`@ 2.13.0.
// ignore_for_file: unused_import, unused_element, unnecessary_import, duplicate_ignore, invalid_use_of_internal_member, annotate_overrides, non_constant_identifier_names, curly_braces_in_flow_control_structures, prefer_const_literals_to_create_immutables, unused_field
import 'api/dto.dart';
import 'api/graph.dart';
import 'dart:async';
import 'dart:convert';
import 'dart:ffi' as ffi;
import 'frb_generated.dart';
import 'package:flutter_rust_bridge/flutter_rust_bridge_for_generated_io.dart';
abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
RustLibApiImplPlatform({
required super.handler,
required super.wire,
required super.generalizedFrbRustBinding,
required super.portManager,
});
CrossPlatformFinalizerArg
get rust_arc_decrement_strong_count_SynapseGraphPtr => wire
._rust_arc_decrement_strong_count_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraphPtr;
@protected
AnyhowException dco_decode_AnyhowException(dynamic raw);
@protected
SynapseGraph
dco_decode_Auto_Owned_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph(
dynamic raw,
);
@protected
SynapseGraph
dco_decode_Auto_Ref_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph(
dynamic raw,
);
@protected
SynapseGraph
dco_decode_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph(
dynamic raw,
);
@protected
String dco_decode_String(dynamic raw);
@protected
AssetDto dco_decode_asset_dto(dynamic raw);
@protected
BacklinkGroup dco_decode_backlink_group(dynamic raw);
@protected
BlockDto dco_decode_block_dto(dynamic raw);
@protected
BlockHit dco_decode_block_hit(dynamic raw);
@protected
BlockRefDto dco_decode_block_ref_dto(dynamic raw);
@protected
bool dco_decode_bool(dynamic raw);
@protected
BlockRefDto dco_decode_box_autoadd_block_ref_dto(dynamic raw);
@protected
PageData dco_decode_box_autoadd_page_data(dynamic raw);
@protected
Place dco_decode_box_autoadd_place(dynamic raw);
@protected
EditDto dco_decode_edit_dto(dynamic raw);
@protected
double dco_decode_f_32(dynamic raw);
@protected
int dco_decode_i_32(dynamic raw);
@protected
PlatformInt64 dco_decode_i_64(dynamic raw);
@protected
List<String> dco_decode_list_String(dynamic raw);
@protected
List<BacklinkGroup> dco_decode_list_backlink_group(dynamic raw);
@protected
List<BlockDto> dco_decode_list_block_dto(dynamic raw);
@protected
List<BlockHit> dco_decode_list_block_hit(dynamic raw);
@protected
List<EditDto> dco_decode_list_edit_dto(dynamic raw);
@protected
List<PageBrief> dco_decode_list_page_brief(dynamic raw);
@protected
List<PageData> dco_decode_list_page_data(dynamic raw);
@protected
List<PageDto> dco_decode_list_page_dto(dynamic raw);
@protected
List<int> dco_decode_list_prim_u_8_loose(dynamic raw);
@protected
Uint8List dco_decode_list_prim_u_8_strict(dynamic raw);
@protected
List<RelatedDto> dco_decode_list_related_dto(dynamic raw);
@protected
List<TimelineDayDto> dco_decode_list_timeline_day_dto(dynamic raw);
@protected
List<TitleHit> dco_decode_list_title_hit(dynamic raw);
@protected
String? dco_decode_opt_String(dynamic raw);
@protected
BlockRefDto? dco_decode_opt_box_autoadd_block_ref_dto(dynamic raw);
@protected
PageData? dco_decode_opt_box_autoadd_page_data(dynamic raw);
@protected
PageBrief dco_decode_page_brief(dynamic raw);
@protected
PageData dco_decode_page_data(dynamic raw);
@protected
PageDto dco_decode_page_dto(dynamic raw);
@protected
Place dco_decode_place(dynamic raw);
@protected
PlaceKind dco_decode_place_kind(dynamic raw);
@protected
(String?, String?) dco_decode_record_opt_string_opt_string(dynamic raw);
@protected
RelatedDto dco_decode_related_dto(dynamic raw);
@protected
TimelineDayDto dco_decode_timeline_day_dto(dynamic raw);
@protected
TimelineDto dco_decode_timeline_dto(dynamic raw);
@protected
TitleHit dco_decode_title_hit(dynamic raw);
@protected
int dco_decode_u_32(dynamic raw);
@protected
BigInt dco_decode_u_64(dynamic raw);
@protected
int dco_decode_u_8(dynamic raw);
@protected
void dco_decode_unit(dynamic raw);
@protected
BigInt dco_decode_usize(dynamic raw);
@protected
AnyhowException sse_decode_AnyhowException(SseDeserializer deserializer);
@protected
SynapseGraph
sse_decode_Auto_Owned_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph(
SseDeserializer deserializer,
);
@protected
SynapseGraph
sse_decode_Auto_Ref_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph(
SseDeserializer deserializer,
);
@protected
SynapseGraph
sse_decode_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph(
SseDeserializer deserializer,
);
@protected
String sse_decode_String(SseDeserializer deserializer);
@protected
AssetDto sse_decode_asset_dto(SseDeserializer deserializer);
@protected
BacklinkGroup sse_decode_backlink_group(SseDeserializer deserializer);
@protected
BlockDto sse_decode_block_dto(SseDeserializer deserializer);
@protected
BlockHit sse_decode_block_hit(SseDeserializer deserializer);
@protected
BlockRefDto sse_decode_block_ref_dto(SseDeserializer deserializer);
@protected
bool sse_decode_bool(SseDeserializer deserializer);
@protected
BlockRefDto sse_decode_box_autoadd_block_ref_dto(
SseDeserializer deserializer,
);
@protected
PageData sse_decode_box_autoadd_page_data(SseDeserializer deserializer);
@protected
Place sse_decode_box_autoadd_place(SseDeserializer deserializer);
@protected
EditDto sse_decode_edit_dto(SseDeserializer deserializer);
@protected
double sse_decode_f_32(SseDeserializer deserializer);
@protected
int sse_decode_i_32(SseDeserializer deserializer);
@protected
PlatformInt64 sse_decode_i_64(SseDeserializer deserializer);
@protected
List<String> sse_decode_list_String(SseDeserializer deserializer);
@protected
List<BacklinkGroup> sse_decode_list_backlink_group(
SseDeserializer deserializer,
);
@protected
List<BlockDto> sse_decode_list_block_dto(SseDeserializer deserializer);
@protected
List<BlockHit> sse_decode_list_block_hit(SseDeserializer deserializer);
@protected
List<EditDto> sse_decode_list_edit_dto(SseDeserializer deserializer);
@protected
List<PageBrief> sse_decode_list_page_brief(SseDeserializer deserializer);
@protected
List<PageData> sse_decode_list_page_data(SseDeserializer deserializer);
@protected
List<PageDto> sse_decode_list_page_dto(SseDeserializer deserializer);
@protected
List<int> sse_decode_list_prim_u_8_loose(SseDeserializer deserializer);
@protected
Uint8List sse_decode_list_prim_u_8_strict(SseDeserializer deserializer);
@protected
List<RelatedDto> sse_decode_list_related_dto(SseDeserializer deserializer);
@protected
List<TimelineDayDto> sse_decode_list_timeline_day_dto(
SseDeserializer deserializer,
);
@protected
List<TitleHit> sse_decode_list_title_hit(SseDeserializer deserializer);
@protected
String? sse_decode_opt_String(SseDeserializer deserializer);
@protected
BlockRefDto? sse_decode_opt_box_autoadd_block_ref_dto(
SseDeserializer deserializer,
);
@protected
PageData? sse_decode_opt_box_autoadd_page_data(SseDeserializer deserializer);
@protected
PageBrief sse_decode_page_brief(SseDeserializer deserializer);
@protected
PageData sse_decode_page_data(SseDeserializer deserializer);
@protected
PageDto sse_decode_page_dto(SseDeserializer deserializer);
@protected
Place sse_decode_place(SseDeserializer deserializer);
@protected
PlaceKind sse_decode_place_kind(SseDeserializer deserializer);
@protected
(String?, String?) sse_decode_record_opt_string_opt_string(
SseDeserializer deserializer,
);
@protected
RelatedDto sse_decode_related_dto(SseDeserializer deserializer);
@protected
TimelineDayDto sse_decode_timeline_day_dto(SseDeserializer deserializer);
@protected
TimelineDto sse_decode_timeline_dto(SseDeserializer deserializer);
@protected
TitleHit sse_decode_title_hit(SseDeserializer deserializer);
@protected
int sse_decode_u_32(SseDeserializer deserializer);
@protected
BigInt sse_decode_u_64(SseDeserializer deserializer);
@protected
int sse_decode_u_8(SseDeserializer deserializer);
@protected
void sse_decode_unit(SseDeserializer deserializer);
@protected
BigInt sse_decode_usize(SseDeserializer deserializer);
@protected
void sse_encode_AnyhowException(
AnyhowException self,
SseSerializer serializer,
);
@protected
void
sse_encode_Auto_Owned_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph(
SynapseGraph self,
SseSerializer serializer,
);
@protected
void
sse_encode_Auto_Ref_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph(
SynapseGraph self,
SseSerializer serializer,
);
@protected
void
sse_encode_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph(
SynapseGraph self,
SseSerializer serializer,
);
@protected
void sse_encode_String(String self, SseSerializer serializer);
@protected
void sse_encode_asset_dto(AssetDto self, SseSerializer serializer);
@protected
void sse_encode_backlink_group(BacklinkGroup self, SseSerializer serializer);
@protected
void sse_encode_block_dto(BlockDto self, SseSerializer serializer);
@protected
void sse_encode_block_hit(BlockHit self, SseSerializer serializer);
@protected
void sse_encode_block_ref_dto(BlockRefDto self, SseSerializer serializer);
@protected
void sse_encode_bool(bool self, SseSerializer serializer);
@protected
void sse_encode_box_autoadd_block_ref_dto(
BlockRefDto self,
SseSerializer serializer,
);
@protected
void sse_encode_box_autoadd_page_data(
PageData self,
SseSerializer serializer,
);
@protected
void sse_encode_box_autoadd_place(Place 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_i_32(int self, SseSerializer serializer);
@protected
void sse_encode_i_64(PlatformInt64 self, SseSerializer serializer);
@protected
void sse_encode_list_String(List<String> self, SseSerializer serializer);
@protected
void sse_encode_list_backlink_group(
List<BacklinkGroup> self,
SseSerializer serializer,
);
@protected
void sse_encode_list_block_dto(List<BlockDto> self, SseSerializer serializer);
@protected
void sse_encode_list_block_hit(List<BlockHit> self, SseSerializer serializer);
@protected
void sse_encode_list_edit_dto(List<EditDto> self, SseSerializer serializer);
@protected
void sse_encode_list_page_brief(
List<PageBrief> self,
SseSerializer serializer,
);
@protected
void sse_encode_list_page_data(List<PageData> self, SseSerializer serializer);
@protected
void sse_encode_list_page_dto(List<PageDto> self, SseSerializer serializer);
@protected
void sse_encode_list_prim_u_8_loose(List<int> self, SseSerializer serializer);
@protected
void sse_encode_list_prim_u_8_strict(
Uint8List self,
SseSerializer serializer,
);
@protected
void sse_encode_list_related_dto(
List<RelatedDto> self,
SseSerializer serializer,
);
@protected
void sse_encode_list_timeline_day_dto(
List<TimelineDayDto> self,
SseSerializer serializer,
);
@protected
void sse_encode_list_title_hit(List<TitleHit> self, SseSerializer serializer);
@protected
void sse_encode_opt_String(String? self, SseSerializer serializer);
@protected
void sse_encode_opt_box_autoadd_block_ref_dto(
BlockRefDto? self,
SseSerializer serializer,
);
@protected
void sse_encode_opt_box_autoadd_page_data(
PageData? self,
SseSerializer serializer,
);
@protected
void sse_encode_page_brief(PageBrief self, SseSerializer serializer);
@protected
void sse_encode_page_data(PageData self, SseSerializer serializer);
@protected
void sse_encode_page_dto(PageDto self, SseSerializer serializer);
@protected
void sse_encode_place(Place self, SseSerializer serializer);
@protected
void sse_encode_place_kind(PlaceKind self, SseSerializer serializer);
@protected
void sse_encode_record_opt_string_opt_string(
(String?, String?) self,
SseSerializer serializer,
);
@protected
void sse_encode_related_dto(RelatedDto self, SseSerializer serializer);
@protected
void sse_encode_timeline_day_dto(
TimelineDayDto self,
SseSerializer serializer,
);
@protected
void sse_encode_timeline_dto(TimelineDto self, SseSerializer serializer);
@protected
void sse_encode_title_hit(TitleHit self, SseSerializer serializer);
@protected
void sse_encode_u_32(int self, SseSerializer serializer);
@protected
void sse_encode_u_64(BigInt self, SseSerializer serializer);
@protected
void sse_encode_u_8(int self, SseSerializer serializer);
@protected
void sse_encode_unit(void self, SseSerializer serializer);
@protected
void sse_encode_usize(BigInt self, SseSerializer serializer);
}
// Section: wire_class
class RustLibWire implements BaseWire {
factory RustLibWire.fromExternalLibrary(ExternalLibrary lib) =>
RustLibWire(lib.ffiDynamicLibrary);
/// Holds the symbol lookup function.
final ffi.Pointer<T> Function<T extends ffi.NativeType>(String symbolName)
_lookup;
/// The symbols are looked up in [dynamicLibrary].
RustLibWire(ffi.DynamicLibrary dynamicLibrary)
: _lookup = dynamicLibrary.lookup;
void
rust_arc_increment_strong_count_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph(
ffi.Pointer<ffi.Void> ptr,
) {
return _rust_arc_increment_strong_count_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph(
ptr,
);
}
late final _rust_arc_increment_strong_count_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraphPtr =
_lookup<ffi.NativeFunction<ffi.Void Function(ffi.Pointer<ffi.Void>)>>(
'frbgen_synapse_rust_arc_increment_strong_count_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph',
);
late final _rust_arc_increment_strong_count_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph =
_rust_arc_increment_strong_count_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraphPtr
.asFunction<void Function(ffi.Pointer<ffi.Void>)>();
void
rust_arc_decrement_strong_count_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph(
ffi.Pointer<ffi.Void> ptr,
) {
return _rust_arc_decrement_strong_count_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph(
ptr,
);
}
late final _rust_arc_decrement_strong_count_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraphPtr =
_lookup<ffi.NativeFunction<ffi.Void Function(ffi.Pointer<ffi.Void>)>>(
'frbgen_synapse_rust_arc_decrement_strong_count_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph',
);
late final _rust_arc_decrement_strong_count_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph =
_rust_arc_decrement_strong_count_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraphPtr
.asFunction<void Function(ffi.Pointer<ffi.Void>)>();
}
+586
View File
@@ -0,0 +1,586 @@
// This file is automatically generated, so please do not edit it.
// @generated by `flutter_rust_bridge`@ 2.13.0.
// ignore_for_file: unused_import, unused_element, unnecessary_import, duplicate_ignore, invalid_use_of_internal_member, annotate_overrides, non_constant_identifier_names, curly_braces_in_flow_control_structures, prefer_const_literals_to_create_immutables, unused_field
// Static analysis wrongly picks the IO variant, thus ignore this
// ignore_for_file: argument_type_not_assignable
import 'api/dto.dart';
import 'api/graph.dart';
import 'dart:async';
import 'dart:convert';
import 'frb_generated.dart';
import 'package:flutter_rust_bridge/flutter_rust_bridge_for_generated_web.dart';
abstract class RustLibApiImplPlatform extends BaseApiImpl<RustLibWire> {
RustLibApiImplPlatform({
required super.handler,
required super.wire,
required super.generalizedFrbRustBinding,
required super.portManager,
});
CrossPlatformFinalizerArg
get rust_arc_decrement_strong_count_SynapseGraphPtr => wire
.rust_arc_decrement_strong_count_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph;
@protected
AnyhowException dco_decode_AnyhowException(dynamic raw);
@protected
SynapseGraph
dco_decode_Auto_Owned_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph(
dynamic raw,
);
@protected
SynapseGraph
dco_decode_Auto_Ref_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph(
dynamic raw,
);
@protected
SynapseGraph
dco_decode_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph(
dynamic raw,
);
@protected
String dco_decode_String(dynamic raw);
@protected
AssetDto dco_decode_asset_dto(dynamic raw);
@protected
BacklinkGroup dco_decode_backlink_group(dynamic raw);
@protected
BlockDto dco_decode_block_dto(dynamic raw);
@protected
BlockHit dco_decode_block_hit(dynamic raw);
@protected
BlockRefDto dco_decode_block_ref_dto(dynamic raw);
@protected
bool dco_decode_bool(dynamic raw);
@protected
BlockRefDto dco_decode_box_autoadd_block_ref_dto(dynamic raw);
@protected
PageData dco_decode_box_autoadd_page_data(dynamic raw);
@protected
Place dco_decode_box_autoadd_place(dynamic raw);
@protected
EditDto dco_decode_edit_dto(dynamic raw);
@protected
double dco_decode_f_32(dynamic raw);
@protected
int dco_decode_i_32(dynamic raw);
@protected
PlatformInt64 dco_decode_i_64(dynamic raw);
@protected
List<String> dco_decode_list_String(dynamic raw);
@protected
List<BacklinkGroup> dco_decode_list_backlink_group(dynamic raw);
@protected
List<BlockDto> dco_decode_list_block_dto(dynamic raw);
@protected
List<BlockHit> dco_decode_list_block_hit(dynamic raw);
@protected
List<EditDto> dco_decode_list_edit_dto(dynamic raw);
@protected
List<PageBrief> dco_decode_list_page_brief(dynamic raw);
@protected
List<PageData> dco_decode_list_page_data(dynamic raw);
@protected
List<PageDto> dco_decode_list_page_dto(dynamic raw);
@protected
List<int> dco_decode_list_prim_u_8_loose(dynamic raw);
@protected
Uint8List dco_decode_list_prim_u_8_strict(dynamic raw);
@protected
List<RelatedDto> dco_decode_list_related_dto(dynamic raw);
@protected
List<TimelineDayDto> dco_decode_list_timeline_day_dto(dynamic raw);
@protected
List<TitleHit> dco_decode_list_title_hit(dynamic raw);
@protected
String? dco_decode_opt_String(dynamic raw);
@protected
BlockRefDto? dco_decode_opt_box_autoadd_block_ref_dto(dynamic raw);
@protected
PageData? dco_decode_opt_box_autoadd_page_data(dynamic raw);
@protected
PageBrief dco_decode_page_brief(dynamic raw);
@protected
PageData dco_decode_page_data(dynamic raw);
@protected
PageDto dco_decode_page_dto(dynamic raw);
@protected
Place dco_decode_place(dynamic raw);
@protected
PlaceKind dco_decode_place_kind(dynamic raw);
@protected
(String?, String?) dco_decode_record_opt_string_opt_string(dynamic raw);
@protected
RelatedDto dco_decode_related_dto(dynamic raw);
@protected
TimelineDayDto dco_decode_timeline_day_dto(dynamic raw);
@protected
TimelineDto dco_decode_timeline_dto(dynamic raw);
@protected
TitleHit dco_decode_title_hit(dynamic raw);
@protected
int dco_decode_u_32(dynamic raw);
@protected
BigInt dco_decode_u_64(dynamic raw);
@protected
int dco_decode_u_8(dynamic raw);
@protected
void dco_decode_unit(dynamic raw);
@protected
BigInt dco_decode_usize(dynamic raw);
@protected
AnyhowException sse_decode_AnyhowException(SseDeserializer deserializer);
@protected
SynapseGraph
sse_decode_Auto_Owned_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph(
SseDeserializer deserializer,
);
@protected
SynapseGraph
sse_decode_Auto_Ref_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph(
SseDeserializer deserializer,
);
@protected
SynapseGraph
sse_decode_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph(
SseDeserializer deserializer,
);
@protected
String sse_decode_String(SseDeserializer deserializer);
@protected
AssetDto sse_decode_asset_dto(SseDeserializer deserializer);
@protected
BacklinkGroup sse_decode_backlink_group(SseDeserializer deserializer);
@protected
BlockDto sse_decode_block_dto(SseDeserializer deserializer);
@protected
BlockHit sse_decode_block_hit(SseDeserializer deserializer);
@protected
BlockRefDto sse_decode_block_ref_dto(SseDeserializer deserializer);
@protected
bool sse_decode_bool(SseDeserializer deserializer);
@protected
BlockRefDto sse_decode_box_autoadd_block_ref_dto(
SseDeserializer deserializer,
);
@protected
PageData sse_decode_box_autoadd_page_data(SseDeserializer deserializer);
@protected
Place sse_decode_box_autoadd_place(SseDeserializer deserializer);
@protected
EditDto sse_decode_edit_dto(SseDeserializer deserializer);
@protected
double sse_decode_f_32(SseDeserializer deserializer);
@protected
int sse_decode_i_32(SseDeserializer deserializer);
@protected
PlatformInt64 sse_decode_i_64(SseDeserializer deserializer);
@protected
List<String> sse_decode_list_String(SseDeserializer deserializer);
@protected
List<BacklinkGroup> sse_decode_list_backlink_group(
SseDeserializer deserializer,
);
@protected
List<BlockDto> sse_decode_list_block_dto(SseDeserializer deserializer);
@protected
List<BlockHit> sse_decode_list_block_hit(SseDeserializer deserializer);
@protected
List<EditDto> sse_decode_list_edit_dto(SseDeserializer deserializer);
@protected
List<PageBrief> sse_decode_list_page_brief(SseDeserializer deserializer);
@protected
List<PageData> sse_decode_list_page_data(SseDeserializer deserializer);
@protected
List<PageDto> sse_decode_list_page_dto(SseDeserializer deserializer);
@protected
List<int> sse_decode_list_prim_u_8_loose(SseDeserializer deserializer);
@protected
Uint8List sse_decode_list_prim_u_8_strict(SseDeserializer deserializer);
@protected
List<RelatedDto> sse_decode_list_related_dto(SseDeserializer deserializer);
@protected
List<TimelineDayDto> sse_decode_list_timeline_day_dto(
SseDeserializer deserializer,
);
@protected
List<TitleHit> sse_decode_list_title_hit(SseDeserializer deserializer);
@protected
String? sse_decode_opt_String(SseDeserializer deserializer);
@protected
BlockRefDto? sse_decode_opt_box_autoadd_block_ref_dto(
SseDeserializer deserializer,
);
@protected
PageData? sse_decode_opt_box_autoadd_page_data(SseDeserializer deserializer);
@protected
PageBrief sse_decode_page_brief(SseDeserializer deserializer);
@protected
PageData sse_decode_page_data(SseDeserializer deserializer);
@protected
PageDto sse_decode_page_dto(SseDeserializer deserializer);
@protected
Place sse_decode_place(SseDeserializer deserializer);
@protected
PlaceKind sse_decode_place_kind(SseDeserializer deserializer);
@protected
(String?, String?) sse_decode_record_opt_string_opt_string(
SseDeserializer deserializer,
);
@protected
RelatedDto sse_decode_related_dto(SseDeserializer deserializer);
@protected
TimelineDayDto sse_decode_timeline_day_dto(SseDeserializer deserializer);
@protected
TimelineDto sse_decode_timeline_dto(SseDeserializer deserializer);
@protected
TitleHit sse_decode_title_hit(SseDeserializer deserializer);
@protected
int sse_decode_u_32(SseDeserializer deserializer);
@protected
BigInt sse_decode_u_64(SseDeserializer deserializer);
@protected
int sse_decode_u_8(SseDeserializer deserializer);
@protected
void sse_decode_unit(SseDeserializer deserializer);
@protected
BigInt sse_decode_usize(SseDeserializer deserializer);
@protected
void sse_encode_AnyhowException(
AnyhowException self,
SseSerializer serializer,
);
@protected
void
sse_encode_Auto_Owned_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph(
SynapseGraph self,
SseSerializer serializer,
);
@protected
void
sse_encode_Auto_Ref_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph(
SynapseGraph self,
SseSerializer serializer,
);
@protected
void
sse_encode_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph(
SynapseGraph self,
SseSerializer serializer,
);
@protected
void sse_encode_String(String self, SseSerializer serializer);
@protected
void sse_encode_asset_dto(AssetDto self, SseSerializer serializer);
@protected
void sse_encode_backlink_group(BacklinkGroup self, SseSerializer serializer);
@protected
void sse_encode_block_dto(BlockDto self, SseSerializer serializer);
@protected
void sse_encode_block_hit(BlockHit self, SseSerializer serializer);
@protected
void sse_encode_block_ref_dto(BlockRefDto self, SseSerializer serializer);
@protected
void sse_encode_bool(bool self, SseSerializer serializer);
@protected
void sse_encode_box_autoadd_block_ref_dto(
BlockRefDto self,
SseSerializer serializer,
);
@protected
void sse_encode_box_autoadd_page_data(
PageData self,
SseSerializer serializer,
);
@protected
void sse_encode_box_autoadd_place(Place 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_i_32(int self, SseSerializer serializer);
@protected
void sse_encode_i_64(PlatformInt64 self, SseSerializer serializer);
@protected
void sse_encode_list_String(List<String> self, SseSerializer serializer);
@protected
void sse_encode_list_backlink_group(
List<BacklinkGroup> self,
SseSerializer serializer,
);
@protected
void sse_encode_list_block_dto(List<BlockDto> self, SseSerializer serializer);
@protected
void sse_encode_list_block_hit(List<BlockHit> self, SseSerializer serializer);
@protected
void sse_encode_list_edit_dto(List<EditDto> self, SseSerializer serializer);
@protected
void sse_encode_list_page_brief(
List<PageBrief> self,
SseSerializer serializer,
);
@protected
void sse_encode_list_page_data(List<PageData> self, SseSerializer serializer);
@protected
void sse_encode_list_page_dto(List<PageDto> self, SseSerializer serializer);
@protected
void sse_encode_list_prim_u_8_loose(List<int> self, SseSerializer serializer);
@protected
void sse_encode_list_prim_u_8_strict(
Uint8List self,
SseSerializer serializer,
);
@protected
void sse_encode_list_related_dto(
List<RelatedDto> self,
SseSerializer serializer,
);
@protected
void sse_encode_list_timeline_day_dto(
List<TimelineDayDto> self,
SseSerializer serializer,
);
@protected
void sse_encode_list_title_hit(List<TitleHit> self, SseSerializer serializer);
@protected
void sse_encode_opt_String(String? self, SseSerializer serializer);
@protected
void sse_encode_opt_box_autoadd_block_ref_dto(
BlockRefDto? self,
SseSerializer serializer,
);
@protected
void sse_encode_opt_box_autoadd_page_data(
PageData? self,
SseSerializer serializer,
);
@protected
void sse_encode_page_brief(PageBrief self, SseSerializer serializer);
@protected
void sse_encode_page_data(PageData self, SseSerializer serializer);
@protected
void sse_encode_page_dto(PageDto self, SseSerializer serializer);
@protected
void sse_encode_place(Place self, SseSerializer serializer);
@protected
void sse_encode_place_kind(PlaceKind self, SseSerializer serializer);
@protected
void sse_encode_record_opt_string_opt_string(
(String?, String?) self,
SseSerializer serializer,
);
@protected
void sse_encode_related_dto(RelatedDto self, SseSerializer serializer);
@protected
void sse_encode_timeline_day_dto(
TimelineDayDto self,
SseSerializer serializer,
);
@protected
void sse_encode_timeline_dto(TimelineDto self, SseSerializer serializer);
@protected
void sse_encode_title_hit(TitleHit self, SseSerializer serializer);
@protected
void sse_encode_u_32(int self, SseSerializer serializer);
@protected
void sse_encode_u_64(BigInt self, SseSerializer serializer);
@protected
void sse_encode_u_8(int self, SseSerializer serializer);
@protected
void sse_encode_unit(void self, SseSerializer serializer);
@protected
void sse_encode_usize(BigInt self, SseSerializer serializer);
}
// Section: wire_class
class RustLibWire implements BaseWire {
RustLibWire.fromExternalLibrary(ExternalLibrary lib);
void
rust_arc_increment_strong_count_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph(
int ptr,
) => wasmModule
.rust_arc_increment_strong_count_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph(
ptr,
);
void
rust_arc_decrement_strong_count_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph(
int ptr,
) => wasmModule
.rust_arc_decrement_strong_count_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph(
ptr,
);
}
@JS('wasm_bindgen')
external RustLibWasmModule get wasmModule;
@JS()
@anonymous
extension type RustLibWasmModule._(JSObject _) implements JSObject {
external void
rust_arc_increment_strong_count_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph(
int ptr,
);
external void
rust_arc_decrement_strong_count_RustOpaque_flutter_rust_bridgefor_generatedRustAutoOpaqueInnerSynapseGraph(
int ptr,
);
}
+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;
}
+198
View File
@@ -0,0 +1,198 @@
import 'package:flutter/material.dart';
/// Synapse's design tokens.
///
/// Typography: Inter for UI and note text (designed for screens, clear at small sizes, wide
/// language coverage), Noto Serif for page and journal titles (a quiet, bookish voice that
/// separates "the document" from the chrome), Source Code Pro for code. All three are bundled
/// (OFL) so the app looks the same offline on every platform.
///
/// Colour: warm paper neutrals instead of pure white/black to keep long reading calm, one
/// accent (deep teal) for links and focus, amber for block references and a muted green for
/// done tasks. Dark mode mirrors the same hues at lower saturation.
@immutable
class SynapseColors extends ThemeExtension<SynapseColors> {
const SynapseColors({
required this.paper,
required this.surface,
required this.ink,
required this.muted,
required this.faint,
required this.line,
required this.accent,
required this.accentSoft,
required this.ref,
required this.done,
required this.codeBg,
required this.highlight,
});
final Color paper;
final Color surface;
final Color ink;
final Color muted;
final Color faint;
final Color line;
final Color accent;
final Color accentSoft;
final Color ref;
final Color done;
final Color codeBg;
final Color highlight;
static const light = SynapseColors(
paper: Color(0xFFFAF8F4),
surface: Color(0xFFF3F0EA),
ink: Color(0xFF23262B),
muted: Color(0xFF6B6F76),
faint: Color(0xFFA9A69F),
line: Color(0xFFE4E0D8),
accent: Color(0xFF1F7A74),
accentSoft: Color(0x1A1F7A74),
ref: Color(0xFFB0741E),
done: Color(0xFF6F8F5E),
codeBg: Color(0xFFEFEBE3),
highlight: Color(0x66F3D86B),
);
static const dark = SynapseColors(
paper: Color(0xFF16181B),
surface: Color(0xFF1D2024),
ink: Color(0xFFE4E2DD),
muted: Color(0xFF9A9FA6),
faint: Color(0xFF61666D),
line: Color(0xFF2B2F35),
accent: Color(0xFF63C2B8),
accentSoft: Color(0x2263C2B8),
ref: Color(0xFFD9A55A),
done: Color(0xFF8DAF7B),
codeBg: Color(0xFF23272C),
highlight: Color(0x55B89B2E),
);
@override
SynapseColors copyWith() => this;
@override
SynapseColors lerp(SynapseColors? other, double t) {
if (other == null) return this;
Color l(Color a, Color b) => Color.lerp(a, b, t)!;
return SynapseColors(
paper: l(paper, other.paper),
surface: l(surface, other.surface),
ink: l(ink, other.ink),
muted: l(muted, other.muted),
faint: l(faint, other.faint),
line: l(line, other.line),
accent: l(accent, other.accent),
accentSoft: l(accentSoft, other.accentSoft),
ref: l(ref, other.ref),
done: l(done, other.done),
codeBg: l(codeBg, other.codeBg),
highlight: l(highlight, other.highlight),
);
}
}
const uiFont = 'Inter';
const titleFont = 'NotoSerif';
const monoFont = 'SourceCodePro';
/// Text metrics of the outliner, shared by rendering and editing so a block does not jump
/// when it switches between the two.
const blockFontSize = 15.0;
const blockLineHeight = 1.55;
extension SynapseThemeX on BuildContext {
SynapseColors get colors => Theme.of(this).extension<SynapseColors>()!;
}
ThemeData buildTheme(Brightness brightness) {
final c = brightness == Brightness.light
? SynapseColors.light
: SynapseColors.dark;
final scheme =
ColorScheme.fromSeed(
seedColor: c.accent,
brightness: brightness,
).copyWith(
primary: c.accent,
surface: c.paper,
onSurface: c.ink,
surfaceContainerLowest: c.paper,
surfaceContainerLow: c.surface,
surfaceContainer: c.surface,
surfaceContainerHigh: c.surface,
outline: c.line,
outlineVariant: c.line,
);
final base = ThemeData(
useMaterial3: true,
brightness: brightness,
colorScheme: scheme,
fontFamily: uiFont,
scaffoldBackgroundColor: c.paper,
canvasColor: c.paper,
dividerColor: c.line,
splashFactory: NoSplash.splashFactory,
visualDensity: VisualDensity.compact,
extensions: [c],
);
final t = base.textTheme.apply(bodyColor: c.ink, displayColor: c.ink);
return base.copyWith(
textTheme: t.copyWith(
bodyMedium: t.bodyMedium?.copyWith(
fontSize: blockFontSize,
height: blockLineHeight,
),
headlineLarge: TextStyle(
fontFamily: titleFont,
fontSize: 30,
fontWeight: FontWeight.w600,
height: 1.25,
color: c.ink,
letterSpacing: -0.2,
),
headlineSmall: TextStyle(
fontFamily: titleFont,
fontSize: 22,
fontWeight: FontWeight.w600,
height: 1.3,
color: c.ink,
),
labelSmall: TextStyle(
fontFamily: uiFont,
fontSize: 11,
fontWeight: FontWeight.w600,
letterSpacing: 0.8,
color: c.muted,
),
),
textSelectionTheme: TextSelectionThemeData(
cursorColor: c.accent,
selectionColor: c.accentSoft.withAlpha(0x55),
selectionHandleColor: c.accent,
),
tooltipTheme: TooltipThemeData(
waitDuration: const Duration(milliseconds: 500),
decoration: BoxDecoration(
color: c.ink,
borderRadius: BorderRadius.circular(6),
),
textStyle: TextStyle(color: c.paper, fontSize: 12),
),
dialogTheme: DialogThemeData(
backgroundColor: c.paper,
surfaceTintColor: Colors.transparent,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(14),
side: BorderSide(color: c.line),
),
),
scrollbarTheme: ScrollbarThemeData(
thickness: const WidgetStatePropertyAll(6),
radius: const Radius.circular(3),
thumbColor: WidgetStatePropertyAll(c.faint.withAlpha(0x66)),
),
);
}
+111
View File
@@ -0,0 +1,111 @@
import 'package:flutter/material.dart';
import '../backend/graph_backend.dart';
import '../state/app_state.dart';
import '../theme/theme.dart';
import '../widgets/common.dart';
import '../widgets/dates.dart';
/// Every non-journal page, most recently edited first, loaded in pages of 100.
class AllPagesView extends StatefulWidget {
const AllPagesView({super.key});
@override
State<AllPagesView> createState() => _AllPagesViewState();
}
class _AllPagesViewState extends State<AllPagesView> {
final _pages = <PageDto>[];
bool _loading = false;
bool _done = false;
@override
void initState() {
super.initState();
_more();
}
Future<void> _more() async {
if (_loading || _done) return;
_loading = true;
final batch = await AppScope.read(context).backend
.listPages(limit: 100, offset: _pages.length);
if (!mounted) return;
setState(() {
_pages.addAll(batch);
_done = batch.length < 100;
_loading = false;
});
}
@override
Widget build(BuildContext context) {
final app = AppScope.read(context);
final colors = context.colors;
return LayoutBuilder(
builder: (context, box) => NotificationListener<ScrollNotification>(
onNotification: (n) {
if (n.metrics.extentAfter < 600) _more();
return false;
},
child: ListView.builder(
padding: EdgeInsets.fromLTRB(
sidePadding(box.maxWidth),
36,
sidePadding(box.maxWidth),
80,
),
itemCount: _pages.length + 1,
itemBuilder: (context, i) {
if (i == 0) {
return Padding(
padding: const EdgeInsets.only(bottom: 20),
child: Text(
'All pages',
style: Theme.of(context).textTheme.headlineLarge,
),
);
}
final p = _pages[i - 1];
final edited = DateTime.fromMillisecondsSinceEpoch(
p.updatedAt.toInt(),
);
return InkWell(
borderRadius: BorderRadius.circular(8),
onTap: () => app.openId(p.id),
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 9, horizontal: 8),
child: Row(
children: [
Expanded(
child: Text(
p.title,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(fontSize: 14.5, color: colors.ink),
),
),
if (p.originJournal != null)
Text(
'born ${shortDate(parseDay(p.originJournal!))}',
style: TextStyle(fontSize: 12, color: colors.faint),
),
const SizedBox(width: 16),
SizedBox(
width: 70,
child: Text(
shortDate(edited),
textAlign: TextAlign.right,
style: TextStyle(fontSize: 12, color: colors.muted),
),
),
],
),
),
);
},
),
),
);
}
}
+229
View File
@@ -0,0 +1,229 @@
import 'package:flutter/material.dart';
import '../backend/graph_backend.dart';
import '../editor/outline_view.dart';
import '../state/app_state.dart';
import '../state/outline_controller.dart';
import '../theme/theme.dart';
import '../widgets/common.dart';
import '../widgets/dates.dart';
/// Continuous feed of journals, today on top, loading older days as you scroll.
class JournalsView extends StatefulWidget {
const JournalsView({super.key});
@override
State<JournalsView> createState() => _JournalsViewState();
}
class _Day {
_Day(this.view, this.controller);
final PageData view;
final OutlineController controller;
}
class _JournalsViewState extends State<JournalsView> {
static const _batch = 7;
final _days = <_Day>[];
bool _loading = false;
bool _exhausted = false;
Object? _error;
@override
void initState() {
super.initState();
_loadMore();
}
@override
void dispose() {
for (final d in _days) {
d.controller.dispose();
}
super.dispose();
}
Future<void> _loadMore() async {
if (_loading || _exhausted) return;
setState(() => _loading = true);
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 (!mounted) return;
setState(() {
for (final v in views) {
_days.add(
_Day(
v,
OutlineController(
backend: app.backend,
queue: app.queue,
pageId: v.page.id,
blocks: v.blocks,
),
),
);
}
_exhausted = views.length < _batch;
_loading = false;
});
} catch (e) {
if (mounted) {
setState(() {
_error = e;
_loading = false;
});
}
}
}
@override
Widget build(BuildContext context) {
final app = AppScope.read(context);
final today = app.backend.today();
return LayoutBuilder(
builder: (context, box) {
final pad = sidePadding(box.maxWidth);
return NotificationListener<ScrollNotification>(
onNotification: (n) {
if (n.metrics.extentAfter < 800) _loadMore();
return false;
},
child: CustomScrollView(
slivers: [
const SliverToBoxAdapter(child: SizedBox(height: 28)),
for (final d in _days)
SliverPadding(
padding: EdgeInsets.symmetric(horizontal: pad),
sliver: SliverMainAxisGroup(
slivers: [
SliverToBoxAdapter(
child: _JournalHeader(view: d.view, today: today),
),
OutlineSliver(controller: d.controller),
SliverToBoxAdapter(
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 36),
child: Divider(height: 1, color: context.colors.line),
),
),
],
),
),
SliverToBoxAdapter(
child: Padding(
padding: const EdgeInsets.only(bottom: 80),
child: Center(
child: _error != null
? Text('Could not load journals: $_error')
: _exhausted
? Text(
'The beginning of your journals',
style: TextStyle(
color: context.colors.faint,
fontSize: 13,
),
)
: const SizedBox(
width: 18,
height: 18,
child: CircularProgressIndicator(strokeWidth: 2),
),
),
),
),
],
),
);
},
);
}
}
class _JournalHeader extends StatelessWidget {
const _JournalHeader({required this.view, required this.today});
final PageData view;
final String today;
@override
Widget build(BuildContext context) {
final app = AppScope.read(context);
final date = view.page.journalDate!;
final colors = context.colors;
final rel = relativeDay(date, today);
return Padding(
padding: const EdgeInsets.only(bottom: 14),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
Flexible(
child: MouseRegion(
cursor: SystemMouseCursors.click,
child: GestureDetector(
onTap: () => app.openId(view.page.id),
child: Text(
longDate(date),
style: Theme.of(context).textTheme.headlineSmall,
),
),
),
),
const SizedBox(width: 12),
Padding(
padding: const EdgeInsets.only(bottom: 4),
child: Text(
rel == null ? weekday(date) : '$rel · ${weekday(date)}',
style: TextStyle(color: colors.muted, fontSize: 13),
),
),
],
),
const SizedBox(height: 4),
JournalChain(view: view),
],
),
);
}
}
/// Previous / next journal links (the episodic chain).
class JournalChain extends StatelessWidget {
const JournalChain({super.key, required this.view});
final PageData view;
@override
Widget build(BuildContext context) {
final app = AppScope.read(context);
final prev = view.prevJournal;
final next = view.nextJournal;
if (prev == null && next == null) return const SizedBox.shrink();
return Row(
children: [
if (prev != null)
TextLink(
shortDate(parseDay(prev)),
icon: Icons.west_rounded,
onTap: () => app.openTitle(prev),
style: const TextStyle(fontSize: 12),
),
if (prev != null && next != null)
Padding(
padding: const EdgeInsets.symmetric(horizontal: 10),
child: Text('·', style: TextStyle(color: context.colors.faint)),
),
if (next != null)
TextLink(
shortDate(parseDay(next)),
icon: Icons.east_rounded,
iconAfter: true,
onTap: () => app.openTitle(next),
style: const TextStyle(fontSize: 12),
),
],
);
}
}
+476
View File
@@ -0,0 +1,476 @@
import 'package:flutter/material.dart';
import '../backend/graph_backend.dart';
import '../editor/outline_view.dart';
import '../state/app_state.dart';
import '../state/outline_controller.dart';
import '../theme/theme.dart';
import '../widgets/common.dart';
import '../widgets/dates.dart';
import 'journals_view.dart';
/// A single page: title, aliases, outline, linked references and related notes.
class PageScreen extends StatefulWidget {
const PageScreen({super.key, required this.target});
final PageTarget target;
@override
State<PageScreen> createState() => _PageScreenState();
}
class _PageScreenState extends State<PageScreen> {
PageData? _view;
OutlineController? _outline;
List<BacklinkGroup>? _backlinks;
List<RelatedDto>? _related;
Object? _error;
@override
void initState() {
super.initState();
_load();
}
@override
void dispose() {
_outline?.dispose();
super.dispose();
}
Future<void> _load() async {
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!);
}
if (!mounted) return;
if (v == null) {
setState(() => _error = 'This page no longer exists.');
return;
}
final view = v;
setState(() {
_view = view;
_outline = OutlineController(
backend: app.backend,
queue: app.queue,
pageId: view.page.id,
blocks: view.blocks,
);
});
app.pageShown(view.page);
// Make sure pending writes (e.g. a link just typed elsewhere) are visible.
await app.queue.idle;
final results = await Future.wait([
app.backend.backlinks(view.page.id),
app.backend.related(view.page.id),
]);
if (!mounted) return;
setState(() {
_backlinks = results[0] as List<BacklinkGroup>;
_related = results[1] as List<RelatedDto>;
});
} catch (e) {
if (mounted) setState(() => _error = e);
}
}
@override
Widget build(BuildContext context) {
if (_error != null) {
return Center(
child: Text('$_error', style: TextStyle(color: context.colors.muted)),
);
}
final view = _view;
if (view == null) return const SizedBox.shrink();
return LayoutBuilder(
builder: (context, box) {
final wide = box.maxWidth >= 1180;
final mainWidth = wide ? box.maxWidth - 300 : box.maxWidth;
final pad = sidePadding(mainWidth);
final scroll = CustomScrollView(
slivers: [
const SliverToBoxAdapter(child: SizedBox(height: 36)),
SliverPadding(
padding: EdgeInsets.symmetric(horizontal: pad),
sliver: SliverMainAxisGroup(
slivers: [
SliverToBoxAdapter(child: _Header(view: view)),
OutlineSliver(controller: _outline!),
SliverToBoxAdapter(
child: _LinkedReferences(groups: _backlinks),
),
if (!wide)
SliverToBoxAdapter(child: RelatedPanel(related: _related)),
const SliverToBoxAdapter(child: SizedBox(height: 120)),
],
),
),
],
);
if (!wide) return scroll;
return Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Expanded(child: scroll),
Container(
width: 300,
decoration: BoxDecoration(
border: Border(left: BorderSide(color: context.colors.line)),
),
child: SingleChildScrollView(
padding: const EdgeInsets.fromLTRB(20, 44, 20, 40),
child: RelatedPanel(related: _related, compact: true),
),
),
],
);
},
);
}
}
class _Header extends StatelessWidget {
const _Header({required this.view});
final PageData view;
@override
Widget build(BuildContext context) {
final page = view.page;
final colors = context.colors;
final journal = page.journalDate;
final app = AppScope.read(context);
return Padding(
padding: const EdgeInsets.only(bottom: 18),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
if (journal != null) ...[
Text(
longDate(journal),
style: Theme.of(context).textTheme.headlineLarge,
),
const SizedBox(height: 4),
Row(
children: [
Text(
weekday(journal),
style: TextStyle(color: colors.muted, fontSize: 13),
),
const SizedBox(width: 14),
JournalChain(view: view),
],
),
] else ...[
_TitleField(page: page),
const SizedBox(height: 6),
Wrap(
spacing: 14,
runSpacing: 4,
crossAxisAlignment: WrapCrossAlignment.center,
children: [
if (page.originJournal != null)
TextLink(
'Born ${longDate(page.originJournal!)}',
icon: Icons.spa_outlined,
onTap: () => app.openTitle(page.originJournal!),
style: const TextStyle(fontSize: 12),
),
_Aliases(page: page, initial: view.aliases),
],
),
],
],
),
);
}
}
/// Page title; editing it renames the page (and rewrites every link to it).
class _TitleField extends StatefulWidget {
const _TitleField({required this.page});
final PageDto page;
@override
State<_TitleField> createState() => _TitleFieldState();
}
class _TitleFieldState extends State<_TitleField> {
late final _text = TextEditingController(text: widget.page.title);
late final _focus = FocusNode()..addListener(_blur);
late String _committed = widget.page.title;
@override
void dispose() {
_text.dispose();
_focus.dispose();
super.dispose();
}
void _blur() {
if (!_focus.hasFocus) _commit();
}
Future<void> _commit() async {
final title = _text.text.trim();
if (title.isEmpty || title == _committed) {
_text.text = _committed;
return;
}
final app = AppScope.read(context);
final messenger = ScaffoldMessenger.of(context);
try {
await app.queue.run(() => app.backend.renamePage(widget.page.id, title));
_committed = title;
app.renamed(widget.page.id, title);
} catch (e) {
_text.text = _committed;
messenger.showSnackBar(SnackBar(content: Text('Rename failed: $e')));
}
}
@override
Widget build(BuildContext context) => TextField(
controller: _text,
focusNode: _focus,
style: Theme.of(context).textTheme.headlineLarge,
decoration: const InputDecoration.collapsed(hintText: 'Untitled'),
maxLines: null,
onSubmitted: (_) => _focus.unfocus(),
textInputAction: TextInputAction.done,
);
}
class _Aliases extends StatefulWidget {
const _Aliases({required this.page, required this.initial});
final PageDto page;
final List<String> initial;
@override
State<_Aliases> createState() => _AliasesState();
}
class _AliasesState extends State<_Aliases> {
late final List<String> _aliases = List.of(widget.initial);
bool _adding = false;
final _text = TextEditingController();
@override
void dispose() {
_text.dispose();
super.dispose();
}
Future<void> _add() async {
final alias = _text.text.trim();
setState(() => _adding = false);
_text.clear();
if (alias.isEmpty || _aliases.contains(alias)) return;
final app = AppScope.read(context);
await app.queue.run(() => app.backend.addAlias(widget.page.id, alias));
if (mounted) setState(() => _aliases.add(alias));
}
Future<void> _remove(String alias) async {
final app = AppScope.read(context);
await app.queue.run(() => app.backend.removeAlias(alias));
if (mounted) setState(() => _aliases.remove(alias));
}
@override
Widget build(BuildContext context) {
final colors = context.colors;
return Wrap(
spacing: 6,
runSpacing: 4,
crossAxisAlignment: WrapCrossAlignment.center,
children: [
for (final a in _aliases)
Container(
padding: const EdgeInsets.only(left: 8, right: 2),
decoration: BoxDecoration(
color: colors.surface,
borderRadius: BorderRadius.circular(20),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Text(a, style: TextStyle(fontSize: 12, color: colors.muted)),
InkResponse(
radius: 10,
onTap: () => _remove(a),
child: Padding(
padding: const EdgeInsets.all(3),
child: Icon(
Icons.close_rounded,
size: 12,
color: colors.faint,
),
),
),
],
),
),
if (_adding)
SizedBox(
width: 140,
child: TextField(
controller: _text,
autofocus: true,
style: TextStyle(fontSize: 12, color: colors.ink),
decoration: const InputDecoration.collapsed(hintText: 'alias'),
onSubmitted: (_) => _add(),
onTapOutside: (_) => _add(),
),
)
else
TextLink(
_aliases.isEmpty ? 'Add alias' : 'Alias',
icon: Icons.add_rounded,
onTap: () => setState(() => _adding = true),
style: const TextStyle(fontSize: 12),
),
],
);
}
}
class _LinkedReferences extends StatelessWidget {
const _LinkedReferences({required this.groups});
final List<BacklinkGroup>? groups;
@override
Widget build(BuildContext context) {
final g = groups;
if (g == null || g.isEmpty) return const SizedBox(height: 40);
final app = AppScope.read(context);
final colors = context.colors;
final count = g.fold<int>(0, (n, x) => n + x.blocks.length);
return Padding(
padding: const EdgeInsets.only(top: 56),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SectionLabel(
'Linked references',
trailing: Text(
'$count',
style: TextStyle(fontSize: 11, color: colors.faint),
),
),
const SizedBox(height: 12),
for (final group in g)
Container(
margin: const EdgeInsets.only(bottom: 12),
padding: const EdgeInsets.fromLTRB(14, 10, 14, 10),
decoration: BoxDecoration(
color: colors.surface,
borderRadius: BorderRadius.circular(10),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
TextLink(
group.isJournal
? longDate(group.pageTitle)
: group.pageTitle,
onTap: () => app.openId(group.pageId),
style: TextStyle(
fontSize: 13,
fontWeight: FontWeight.w600,
color: colors.ink,
),
),
const SizedBox(height: 4),
for (final b in group.blocks)
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Dot(),
const SizedBox(width: 4),
Expanded(
child: StaticBlock(
content: b.content,
onTap: () => app.openId(group.pageId),
),
),
],
),
],
),
),
],
),
);
}
}
/// Notes related by spreading activation over links, synapses and time.
class RelatedPanel extends StatelessWidget {
const RelatedPanel({super.key, required this.related, this.compact = false});
final List<RelatedDto>? related;
final bool compact;
@override
Widget build(BuildContext context) {
final r = related;
final colors = context.colors;
final app = AppScope.read(context);
final top = (r == null || r.isEmpty) ? 1.0 : r.first.score;
return Padding(
padding: EdgeInsets.only(top: compact ? 0 : 40),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const SectionLabel('Related'),
const SizedBox(height: 4),
Text(
'Strengthened by links, visits and shared days',
style: TextStyle(fontSize: 12, color: colors.faint),
),
const SizedBox(height: 14),
if (r == null)
const SizedBox.shrink()
else if (r.isEmpty)
Text(
'Nothing yet. Link this note to others.',
style: TextStyle(fontSize: 13, color: colors.muted),
)
else
for (final x in r)
Padding(
padding: const EdgeInsets.only(bottom: 10),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
TextLink(
x.page.isJournal ? longDate(x.page.title) : x.page.title,
icon: x.page.isJournal
? Icons.calendar_today_outlined
: Icons.description_outlined,
onTap: () => app.openId(x.page.id),
style: TextStyle(fontSize: 13.5, color: colors.ink),
),
const SizedBox(height: 4),
ClipRRect(
borderRadius: BorderRadius.circular(2),
child: LinearProgressIndicator(
value: (x.score / top).clamp(0.05, 1.0),
minHeight: 3,
backgroundColor: colors.line,
color: colors.accent.withAlpha(0x99),
),
),
],
),
),
],
),
);
}
}
+215
View File
@@ -0,0 +1,215 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../backend/graph_backend.dart';
import '../state/app_state.dart';
import '../theme/theme.dart';
/// Ctrl+K: jump to a page by title or alias, or create it.
Future<void> showQuickSwitcher(BuildContext context) => showDialog<void>(
context: context,
barrierColor: Colors.black.withAlpha(0x33),
builder: (_) =>
AppScope(state: AppScope.read(context), child: const QuickSwitcher()),
);
class QuickSwitcher extends StatefulWidget {
const QuickSwitcher({super.key});
@override
State<QuickSwitcher> createState() => _QuickSwitcherState();
}
class _QuickSwitcherState extends State<QuickSwitcher> {
final _text = TextEditingController();
List<TitleHit> _hits = const [];
int _selected = 0;
int _seq = 0;
@override
void initState() {
super.initState();
_search('');
}
@override
void dispose() {
_text.dispose();
super.dispose();
}
String get _query => _text.text.trim();
bool get _offerCreate =>
_query.isNotEmpty &&
!_hits.any((h) => h.title.toLowerCase() == _query.toLowerCase());
int get _count => _hits.length + (_offerCreate ? 1 : 0);
Future<void> _search(String q) async {
final seq = ++_seq;
final hits = await AppScope.read(context).backend
.searchTitles(q, limit: 12);
if (!mounted || seq != _seq) return;
setState(() {
_hits = hits;
_selected = 0;
});
}
void _open(int i) {
final app = AppScope.read(context);
Navigator.of(context).pop();
if (i < _hits.length) {
app.openId(_hits[i].pageId);
} else if (_query.isNotEmpty) {
app.openTitle(_query);
}
}
KeyEventResult _key(FocusNode _, KeyEvent e) {
if (e is! KeyDownEvent && e is! KeyRepeatEvent) {
return KeyEventResult.ignored;
}
if (_count == 0) return KeyEventResult.ignored;
if (e.logicalKey == LogicalKeyboardKey.arrowDown) {
setState(() => _selected = (_selected + 1) % _count);
return KeyEventResult.handled;
}
if (e.logicalKey == LogicalKeyboardKey.arrowUp) {
setState(() => _selected = (_selected - 1 + _count) % _count);
return KeyEventResult.handled;
}
return KeyEventResult.ignored;
}
@override
Widget build(BuildContext context) {
final colors = context.colors;
return Align(
alignment: const Alignment(0, -0.55),
child: Material(
color: colors.paper,
borderRadius: BorderRadius.circular(14),
clipBehavior: Clip.antiAlias,
child: Container(
width: 560,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(14),
border: Border.all(color: colors.line),
),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Padding(
padding: const EdgeInsets.fromLTRB(18, 14, 18, 12),
child: Row(
children: [
Icon(Icons.search_rounded, size: 18, color: colors.muted),
const SizedBox(width: 10),
Expanded(
child: Focus(
onKeyEvent: _key,
child: TextField(
controller: _text,
autofocus: true,
style: TextStyle(fontSize: 16, color: colors.ink),
decoration: const InputDecoration.collapsed(
hintText: 'Search or create a page',
),
onChanged: (q) => _search(q),
onSubmitted: (_) => _open(_selected),
),
),
),
],
),
),
if (_count > 0) Divider(height: 1, color: colors.line),
ConstrainedBox(
constraints: const BoxConstraints(maxHeight: 380),
child: ListView(
shrinkWrap: true,
padding: const EdgeInsets.all(6),
children: [
for (var i = 0; i < _count; i++)
_Item(
selected: i == _selected,
onTap: () => _open(i),
icon: i < _hits.length
? Icons.description_outlined
: Icons.add_rounded,
title: i < _hits.length
? _hits[i].title
: 'Create page “$_query”',
detail: i < _hits.length && _hits[i].isAlias
? 'alias'
: null,
),
],
),
),
],
),
),
),
);
}
}
class _Item extends StatelessWidget {
const _Item({
required this.selected,
required this.onTap,
required this.icon,
required this.title,
this.detail,
});
final bool selected;
final VoidCallback onTap;
final IconData icon;
final String title;
final String? detail;
@override
Widget build(BuildContext context) {
final colors = context.colors;
return MouseRegion(
cursor: SystemMouseCursors.click,
child: GestureDetector(
onTap: onTap,
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 9),
decoration: BoxDecoration(
color: selected ? colors.accentSoft : null,
borderRadius: BorderRadius.circular(8),
),
child: Row(
children: [
Icon(
icon,
size: 16,
color: selected ? colors.accent : colors.muted,
),
const SizedBox(width: 10),
Expanded(
child: Text(
title,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(fontSize: 14, color: colors.ink),
),
),
if (detail != null)
Text(
detail!,
style: TextStyle(fontSize: 12, color: colors.faint),
),
],
),
),
),
);
}
}
+390
View File
@@ -0,0 +1,390 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../state/app_state.dart';
import '../theme/theme.dart';
import '../widgets/dates.dart';
import 'all_pages_view.dart';
import 'journals_view.dart';
import 'page_screen.dart';
import 'quick_switcher.dart';
import 'timeline_view.dart';
/// App frame: sidebar (navigation, recents, theme), top bar and the current view.
class Shell extends StatefulWidget {
const Shell({super.key});
@override
State<Shell> createState() => _ShellState();
}
class _ShellState extends State<Shell> {
bool _sidebar = true;
final _scaffold = GlobalKey<ScaffoldState>();
@override
Widget build(BuildContext context) {
final app = AppScope.of(context);
final colors = context.colors;
final route = app.route;
return CallbackShortcuts(
bindings: {
const SingleActivator(LogicalKeyboardKey.keyK, control: true): () =>
showQuickSwitcher(context),
const SingleActivator(LogicalKeyboardKey.keyK, meta: true): () =>
showQuickSwitcher(context),
const SingleActivator(
LogicalKeyboardKey.keyJ,
control: true,
shift: true,
): () =>
app.go(const JournalsRoute()),
const SingleActivator(
LogicalKeyboardKey.keyT,
control: true,
shift: true,
): () =>
app.go(const TimelineRoute()),
const SingleActivator(
LogicalKeyboardKey.backslash,
control: true,
): () =>
setState(() => _sidebar = !_sidebar),
const SingleActivator(LogicalKeyboardKey.arrowLeft, alt: true):
app.back,
const SingleActivator(LogicalKeyboardKey.arrowRight, alt: true):
app.forward,
},
child: Focus(
autofocus: true,
child: LayoutBuilder(
builder: (context, box) {
final narrow = box.maxWidth < 760;
final sidebar = _Sidebar(
onNavigate: () {
if (narrow) _scaffold.currentState?.closeDrawer();
},
);
return Scaffold(
key: _scaffold,
drawer: narrow
? Drawer(backgroundColor: colors.surface, child: sidebar)
: null,
body: Row(
children: [
if (!narrow)
AnimatedContainer(
duration: const Duration(milliseconds: 180),
curve: Curves.easeOutCubic,
width: _sidebar ? 248 : 0,
child: ClipRect(
child: OverflowBox(
alignment: Alignment.topLeft,
minWidth: 248,
maxWidth: 248,
child: sidebar,
),
),
),
Expanded(
child: Column(
children: [
_TopBar(
onMenu: () => narrow
? _scaffold.currentState?.openDrawer()
: setState(() => _sidebar = !_sidebar),
),
Expanded(
child: KeyedSubtree(
key: ValueKey(route),
child: switch (route) {
JournalsRoute() => const JournalsView(),
TimelineRoute() => const TimelineView(),
AllPagesRoute() => const AllPagesView(),
PageTarget() => PageScreen(target: route),
},
),
),
],
),
),
],
),
);
},
),
),
);
}
}
class _TopBar extends StatelessWidget {
const _TopBar({required this.onMenu});
final VoidCallback onMenu;
@override
Widget build(BuildContext context) {
final app = AppScope.of(context);
final colors = context.colors;
final brightness = Theme.of(context).brightness;
Widget icon(IconData i, String tip, VoidCallback? f) => IconButton(
tooltip: tip,
onPressed: f,
iconSize: 18,
color: colors.muted,
disabledColor: colors.line,
icon: Icon(i),
);
return Container(
height: 48,
padding: const EdgeInsets.symmetric(horizontal: 8),
child: Row(
children: [
icon(Icons.menu_rounded, 'Toggle sidebar (Ctrl+\\)', onMenu),
icon(
Icons.arrow_back_rounded,
'Back (Alt+←)',
app.canGoBack ? app.back : null,
),
icon(
Icons.arrow_forward_rounded,
'Forward (Alt+→)',
app.canGoForward ? app.forward : null,
),
const Spacer(),
_SearchPill(onTap: () => showQuickSwitcher(context)),
const SizedBox(width: 4),
icon(
brightness == Brightness.dark
? Icons.light_mode_outlined
: Icons.dark_mode_outlined,
'Toggle theme',
() => app.toggleTheme(brightness),
),
],
),
);
}
}
class _SearchPill extends StatelessWidget {
const _SearchPill({required this.onTap});
final VoidCallback onTap;
@override
Widget build(BuildContext context) {
final colors = context.colors;
return InkWell(
onTap: onTap,
borderRadius: BorderRadius.circular(8),
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
decoration: BoxDecoration(
border: Border.all(color: colors.line),
borderRadius: BorderRadius.circular(8),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(Icons.search_rounded, size: 16, color: colors.muted),
const SizedBox(width: 8),
Text('Search', style: TextStyle(fontSize: 13, color: colors.muted)),
const SizedBox(width: 18),
Text('Ctrl K', style: TextStyle(fontSize: 11, color: colors.faint)),
],
),
),
);
}
}
class _Sidebar extends StatelessWidget {
const _Sidebar({required this.onNavigate});
final VoidCallback onNavigate;
@override
Widget build(BuildContext context) {
final app = AppScope.of(context);
final colors = context.colors;
final route = app.route;
void go(AppRoute r) {
app.go(r);
onNavigate();
}
return Container(
color: colors.surface,
child: SafeArea(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Padding(
padding: const EdgeInsets.fromLTRB(20, 18, 20, 22),
child: Row(
children: [
CustomPaint(
size: const Size(20, 20),
painter: _Logo(colors.accent),
),
const SizedBox(width: 10),
Text(
'Synapse',
style: TextStyle(
fontFamily: titleFont,
fontSize: 18,
fontWeight: FontWeight.w600,
color: colors.ink,
),
),
],
),
),
_NavItem(
icon: Icons.calendar_today_outlined,
label: 'Journals',
selected: route is JournalsRoute,
onTap: () => go(const JournalsRoute()),
),
_NavItem(
icon: Icons.timeline_rounded,
label: 'Timeline',
selected: route is TimelineRoute,
onTap: () => go(const TimelineRoute()),
),
_NavItem(
icon: Icons.description_outlined,
label: 'All pages',
selected: route is AllPagesRoute,
onTap: () => go(const AllPagesRoute()),
),
const SizedBox(height: 22),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 20),
child: Text(
'RECENT',
style: Theme.of(context).textTheme.labelSmall,
),
),
const SizedBox(height: 6),
Expanded(
child: ListView(
padding: EdgeInsets.zero,
children: [
for (final p in app.recent)
_NavItem(
label: p.isJournal ? longDate(p.title) : p.title,
selected: route is PageTarget && route.id == p.id,
dense: true,
onTap: () => go(PageTarget(id: p.id)),
),
],
),
),
],
),
),
);
}
}
class _NavItem extends StatefulWidget {
const _NavItem({
this.icon,
required this.label,
required this.selected,
required this.onTap,
this.dense = false,
});
final IconData? icon;
final String label;
final bool selected;
final VoidCallback onTap;
final bool dense;
@override
State<_NavItem> createState() => _NavItemState();
}
class _NavItemState extends State<_NavItem> {
bool _hover = false;
@override
Widget build(BuildContext context) {
final colors = context.colors;
final active = widget.selected;
return MouseRegion(
cursor: SystemMouseCursors.click,
onEnter: (_) => setState(() => _hover = true),
onExit: (_) => setState(() => _hover = false),
child: GestureDetector(
onTap: widget.onTap,
child: Container(
margin: const EdgeInsets.symmetric(horizontal: 10, vertical: 1),
padding: EdgeInsets.symmetric(
horizontal: 10,
vertical: widget.dense ? 6 : 8,
),
decoration: BoxDecoration(
color: active
? colors.accentSoft
: _hover
? colors.line.withAlpha(0x66)
: null,
borderRadius: BorderRadius.circular(8),
),
child: Row(
children: [
if (widget.icon != null) ...[
Icon(
widget.icon,
size: 16,
color: active ? colors.accent : colors.muted,
),
const SizedBox(width: 10),
],
Expanded(
child: Text(
widget.label,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: TextStyle(
fontSize: widget.dense ? 13 : 14,
fontWeight: active ? FontWeight.w600 : FontWeight.w500,
color: active
? colors.ink
: (widget.dense ? colors.muted : colors.ink),
),
),
),
],
),
),
),
);
}
}
/// Two linked nodes: the mark.
class _Logo extends CustomPainter {
_Logo(this.color);
final Color color;
@override
void paint(Canvas canvas, Size size) {
final p = Paint()..color = color;
final a = Offset(size.width * 0.25, size.height * 0.68);
final b = Offset(size.width * 0.75, size.height * 0.32);
canvas.drawLine(
a,
b,
Paint()
..color = color.withAlpha(0x99)
..strokeWidth = 2,
);
canvas.drawCircle(a, size.width * 0.18, p);
canvas.drawCircle(b, size.width * 0.14, p);
}
@override
bool shouldRepaint(_Logo old) => old.color != color;
}
+507
View File
@@ -0,0 +1,507 @@
import 'dart:math' as math;
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../backend/graph_backend.dart';
import '../state/app_state.dart';
import '../theme/theme.dart';
import '../widgets/dates.dart';
/// Loaded timeline data, fetched in fixed chunks of days as the view pans.
class TimelineModel extends ChangeNotifier {
TimelineModel(this.backend, this.today);
static const chunkDays = 32;
final GraphBackend backend;
/// Day index 0.
final DateTime today;
final _loaded = <int>{};
final days = <int, TimelineDayDto>{};
final titles = <String, PageBrief>{};
/// Where each page hangs: (day index, row).
final born = <String, (int, int)>{};
DateTime dayAt(int index) => today.add(Duration(days: index));
int indexOf(String ymd) => parseDay(ymd).difference(today).inDays;
void ensure(int from, int to) {
final c0 = (from / chunkDays).floor();
final c1 = (to / chunkDays).floor();
for (var c = c0; c <= c1; c++) {
if (_loaded.add(c)) _load(c);
}
}
Future<void> _load(int chunk) async {
final start = chunk * chunkDays;
try {
final t = await backend.timeline(
formatDay(dayAt(start)),
formatDay(dayAt(start + chunkDays - 1)),
);
for (final p in t.pages) {
titles[p.id] = p;
}
for (final d in t.days) {
final i = indexOf(d.date);
days[i] = d;
for (var k = 0; k < d.created.length; k++) {
born[d.created[k]] = (i, k);
}
}
notifyListeners();
} catch (e) {
_loaded.remove(chunk);
debugPrint('timeline chunk $chunk failed: $e');
}
}
}
/// Journals on a horizontal line, each linked to the next; pages hang below the journal
/// they were born in, with faint edges to the days they were edited. Pan by dragging, zoom
/// with the wheel or a pinch, tap a node to open it.
class TimelineView extends StatefulWidget {
const TimelineView({super.key});
@override
State<TimelineView> createState() => _TimelineViewState();
}
class _TimelineViewState extends State<TimelineView> {
late final TimelineModel _model;
final _view = _Viewport();
final _hits = <(Rect, String)>[];
double _startDayWidth = 0;
bool _placed = false;
@override
void initState() {
super.initState();
final backend = AppScope.read(context).backend;
_model = TimelineModel(backend, parseDay(backend.today()));
}
@override
void dispose() {
_model.dispose();
_view.dispose();
super.dispose();
}
void _zoom(double factor, double focalX) {
final dw = (_view.dayWidth * factor).clamp(4.0, 260.0);
// Keep the day under the focal point fixed.
final day = (focalX - _view.x) / _view.dayWidth;
_view.update(dayWidth: dw, x: focalX - day * dw);
}
void _tap(Offset p) {
for (final (r, id) in _hits.reversed) {
if (r.inflate(3).contains(p)) {
AppScope.read(context).openId(id);
return;
}
}
}
@override
Widget build(BuildContext context) {
final colors = context.colors;
return LayoutBuilder(
builder: (context, box) {
if (!_placed) {
_placed = true;
_view.x = box.maxWidth - 140;
}
return Stack(
children: [
Positioned.fill(
child: ClipRect(
child: Listener(
onPointerSignal: (e) {
if (e is PointerScrollEvent) {
if (HardwareKeyboard.instance.isShiftPressed) {
_view.update(x: _view.x - e.scrollDelta.dy);
} else {
_zoom(
math.pow(1.0015, -e.scrollDelta.dy).toDouble(),
e.localPosition.dx,
);
}
}
},
child: GestureDetector(
behavior: HitTestBehavior.opaque,
onTapUp: (d) => _tap(d.localPosition),
onScaleStart: (_) => _startDayWidth = _view.dayWidth,
onScaleUpdate: (d) {
if (d.scale != 1.0) {
final target = _startDayWidth * d.scale;
_zoom(target / _view.dayWidth, d.localFocalPoint.dx);
}
_view.update(
x: _view.x + d.focalPointDelta.dx,
y: math.min(0, _view.y + d.focalPointDelta.dy),
);
},
child: CustomPaint(
painter: _TimelinePainter(
model: _model,
view: _view,
colors: colors,
hits: _hits,
textScaler: MediaQuery.textScalerOf(context),
),
size: Size.infinite,
),
),
),
),
),
Positioned(
right: 20,
top: 16,
child: _Toolbar(
onToday: () => _view.update(x: box.maxWidth - 140, y: 0),
onZoomIn: () => _zoom(1.4, box.maxWidth / 2),
onZoomOut: () => _zoom(1 / 1.4, box.maxWidth / 2),
),
),
Positioned(left: 24, bottom: 18, child: _Legend(colors: colors)),
],
);
},
);
}
}
class _Viewport extends ChangeNotifier {
double dayWidth = 64;
/// Screen x of day 0 (today).
double x = 0;
/// Vertical scroll of the hanging pages (<= 0).
double y = 0;
void update({double? dayWidth, double? x, double? y}) {
this.dayWidth = dayWidth ?? this.dayWidth;
this.x = x ?? this.x;
this.y = y ?? this.y;
notifyListeners();
}
}
class _TimelinePainter extends CustomPainter {
_TimelinePainter({
required this.model,
required this.view,
required this.colors,
required this.hits,
required this.textScaler,
}) : super(repaint: Listenable.merge([model, view]));
final TimelineModel model;
final _Viewport view;
final SynapseColors colors;
final List<(Rect, String)> hits;
final TextScaler textScaler;
static const axisY = 120.0;
static const rowH = 28.0;
double xOf(int day) => view.x + day * view.dayWidth;
TextPainter _label(String text, TextStyle style, double maxWidth) {
return TextPainter(
text: TextSpan(text: text, style: style),
textDirection: TextDirection.ltr,
maxLines: 1,
ellipsis: '…',
textScaler: textScaler,
)..layout(maxWidth: math.max(0, maxWidth));
}
@override
void paint(Canvas canvas, Size size) {
hits.clear();
final dw = view.dayWidth;
final first = ((0 - view.x) / dw).floor() - 1;
final last = ((size.width - view.x) / dw).ceil() + 1;
// Load a margin around the viewport so edges to nearby days can be drawn.
final margin = (size.width / dw).ceil();
model.ensure(first - margin, last + margin);
// Axis.
canvas.drawLine(
Offset(0, axisY),
Offset(size.width, axisY),
Paint()
..color = colors.line
..strokeWidth = 1,
);
// Month and day ticks.
final labelStyle = TextStyle(
fontFamily: uiFont,
fontSize: 11,
color: colors.muted,
);
for (var d = first; d <= last; d++) {
final date = model.dayAt(d);
final x = xOf(d);
if (date.day == 1) {
canvas.drawLine(
Offset(x, axisY - 40),
Offset(x, axisY - 8),
Paint()..color = colors.line,
);
final tp = _label(
'${monthName(date.month)} ${date.year}',
labelStyle.copyWith(fontWeight: FontWeight.w600, color: colors.ink),
200,
);
tp.paint(canvas, Offset(x + 6, axisY - 44));
}
if (dw >= 22) {
final tp = _label(
'${date.day}',
labelStyle.copyWith(color: colors.faint),
dw,
);
tp.paint(canvas, Offset(x - tp.width / 2, axisY - 24));
}
}
// Month of the first visible day, pinned to the left edge.
final firstDate = model.dayAt(first + 1);
final sticky = _label(
'${monthName(firstDate.month)} ${firstDate.year}',
labelStyle.copyWith(fontWeight: FontWeight.w600, color: colors.ink),
200,
);
final nextMonth = DateTime.utc(firstDate.year, firstDate.month + 1);
final nextX = xOf(nextMonth.difference(model.today).inDays);
final stickyX = math.min(24.0, nextX - sticky.width - 12);
canvas.drawRect(
Rect.fromLTWH(stickyX - 6, axisY - 48, sticky.width + 12, 22),
Paint()..color = colors.paper,
);
sticky.paint(canvas, Offset(stickyX, axisY - 44));
// Today marker.
final tx = xOf(0);
if (tx >= 0 && tx <= size.width) {
canvas.drawLine(
Offset(tx, axisY - 30),
Offset(tx, size.height),
Paint()
..color = colors.accent.withAlpha(0x33)
..strokeWidth = 1,
);
}
final journalDays =
model.days.entries
.where((e) => e.value.journalId != null)
.map((e) => e.key)
.toList()
..sort();
// Episodic chain: each journal linked to the next.
final chain = Paint()
..color = colors.accent.withAlpha(0x88)
..strokeWidth = 2
..strokeCap = StrokeCap.round;
for (var k = 0; k + 1 < journalDays.length; k++) {
final a = journalDays[k], b = journalDays[k + 1];
if (b < first || a > last) continue;
canvas.drawLine(Offset(xOf(a), axisY), Offset(xOf(b), axisY), chain);
}
final y0 = axisY + 44 + view.y;
final showLabels = dw >= 34;
// Labels may run until the next day that also has pages hanging from it.
final withPages =
model.days.entries
.where((e) => e.value.created.isNotEmpty)
.map((e) => e.key)
.toList()
..sort();
double labelWidth(int d) {
final next = withPages.where((x) => x > d).firstOrNull;
final room = next == null ? 220.0 : (next - d) * dw - 18;
return room.clamp(40.0, 220.0);
}
// Edges from pages to the days they were edited.
final edge = Paint()
..style = PaintingStyle.stroke
..strokeWidth = 1;
for (final e in model.days.entries) {
final d = e.key;
for (final ed in e.value.edited) {
final b = model.born[ed.pageId];
if (b == null || b.$1 == d) continue;
if ((b.$1 < first && d < first) || (b.$1 > last && d > last)) continue;
final from = Offset(xOf(b.$1) + 4, y0 + b.$2 * rowH);
final to = Offset(xOf(d), axisY);
edge.color = colors.ref.withAlpha(
(30 + 20 * math.min(ed.edits, 6)).toInt(),
);
final mid = Offset(
(from.dx + to.dx) / 2,
from.dy + 24 + (from.dx - to.dx).abs() * 0.08,
);
canvas.drawPath(
Path()
..moveTo(from.dx, from.dy)
..quadraticBezierTo(mid.dx, mid.dy, to.dx, to.dy),
edge,
);
}
}
// Pages hanging from their birth day, and journal nodes.
for (var d = first; d <= last; d++) {
final day = model.days[d];
if (day == null) continue;
final x = xOf(d);
if (day.created.isNotEmpty) {
canvas.drawLine(
Offset(x, axisY),
Offset(x, y0 + (day.created.length - 1) * rowH),
Paint()
..color = colors.line
..strokeWidth = 1,
);
}
for (var k = 0; k < day.created.length; k++) {
final id = day.created[k];
final c = Offset(x, y0 + k * rowH);
if (c.dy < axisY + 8) continue;
canvas.drawCircle(c, 4, Paint()..color = colors.paper);
canvas.drawCircle(
c,
4,
Paint()
..color = colors.muted
..style = PaintingStyle.stroke
..strokeWidth = 1.5,
);
var hit = Rect.fromCircle(center: c, radius: 6);
if (showLabels) {
final title = model.titles[id]?.title ?? '…';
final tp = _label(
title,
TextStyle(fontFamily: uiFont, fontSize: 12, color: colors.ink),
labelWidth(d),
);
final at = Offset(c.dx + 9, c.dy - tp.height / 2);
tp.paint(canvas, at);
hit = hit.expandToInclude(at & tp.size);
}
hits.add((hit, id));
}
final jid = day.journalId;
if (jid != null) {
final c = Offset(x, axisY);
final r = day.created.isNotEmpty || day.edited.isNotEmpty ? 6.0 : 4.5;
canvas.drawCircle(c, r + 2, Paint()..color = colors.paper);
canvas.drawCircle(c, r, Paint()..color = colors.accent);
hits.add((Rect.fromCircle(center: c, radius: r + 6), jid));
}
}
}
@override
bool shouldRepaint(_TimelinePainter old) =>
old.colors != colors || old.model != model || old.view != view;
}
class _Toolbar extends StatelessWidget {
const _Toolbar({
required this.onToday,
required this.onZoomIn,
required this.onZoomOut,
});
final VoidCallback onToday;
final VoidCallback onZoomIn;
final VoidCallback onZoomOut;
@override
Widget build(BuildContext context) {
final colors = context.colors;
Widget btn(IconData i, String tip, VoidCallback f) => IconButton(
tooltip: tip,
onPressed: f,
icon: Icon(i, size: 18, color: colors.muted),
);
return Container(
decoration: BoxDecoration(
color: colors.paper,
borderRadius: BorderRadius.circular(10),
border: Border.all(color: colors.line),
),
child: Row(
children: [
btn(Icons.today_outlined, 'Today', onToday),
btn(Icons.remove_rounded, 'Zoom out', onZoomOut),
btn(Icons.add_rounded, 'Zoom in', onZoomIn),
],
),
);
}
}
class _Legend extends StatelessWidget {
const _Legend({required this.colors});
final SynapseColors colors;
@override
Widget build(BuildContext context) {
Widget item(Widget mark, String text) => Padding(
padding: const EdgeInsets.only(right: 16),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
mark,
const SizedBox(width: 6),
Text(text, style: TextStyle(fontSize: 12, color: colors.muted)),
],
),
);
return Row(
children: [
item(
Container(
width: 9,
height: 9,
decoration: BoxDecoration(
color: colors.accent,
shape: BoxShape.circle,
),
),
'Journal',
),
item(
Container(
width: 9,
height: 9,
decoration: BoxDecoration(
shape: BoxShape.circle,
border: Border.all(color: colors.muted, width: 1.5),
),
),
'Page born that day',
),
item(Container(width: 16, height: 1.5, color: colors.ref), 'Edited on'),
],
);
}
}
+168
View File
@@ -0,0 +1,168 @@
import 'dart:math' as math;
import 'package:flutter/material.dart';
import '../editor/block_row.dart';
import '../editor/markdown.dart';
import '../state/app_state.dart';
import '../theme/theme.dart';
/// Max width of the reading column.
const contentWidth = 780.0;
/// Horizontal padding that centres a [contentWidth] column in `width`.
double sidePadding(double width) => math.max(20, (width - contentWidth) / 2);
/// Small caps section label.
class SectionLabel extends StatelessWidget {
const SectionLabel(this.text, {super.key, this.trailing});
final String text;
final Widget? trailing;
@override
Widget build(BuildContext context) => Row(
children: [
Text(text.toUpperCase(), style: Theme.of(context).textTheme.labelSmall),
if (trailing != null) ...[const SizedBox(width: 8), trailing!],
],
);
}
/// A link-like text button.
class TextLink extends StatefulWidget {
const TextLink(
this.text, {
super.key,
required this.onTap,
this.style,
this.icon,
this.iconAfter = false,
});
final String text;
final VoidCallback onTap;
final TextStyle? style;
final IconData? icon;
final bool iconAfter;
@override
State<TextLink> createState() => _TextLinkState();
}
class _TextLinkState extends State<TextLink> {
bool _hover = false;
@override
Widget build(BuildContext context) {
final colors = context.colors;
final color = _hover
? colors.accent
: (widget.style?.color ?? colors.muted);
final style = (widget.style ?? const TextStyle(fontSize: 13)).copyWith(
color: color,
);
final icon = widget.icon == null
? null
: Icon(widget.icon, size: (style.fontSize ?? 13) + 2, color: color);
return MouseRegion(
cursor: SystemMouseCursors.click,
onEnter: (_) => setState(() => _hover = true),
onExit: (_) => setState(() => _hover = false),
child: GestureDetector(
onTap: widget.onTap,
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
if (icon != null && !widget.iconAfter) ...[
icon,
const SizedBox(width: 4),
],
Flexible(
child: Text(
widget.text,
style: style,
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
),
if (icon != null && widget.iconAfter) ...[
const SizedBox(width: 4),
icon,
],
],
),
),
);
}
}
/// Read-only rendered block (linked references). Taps on links navigate; a tap elsewhere
/// calls [onTap].
class StaticBlock extends StatefulWidget {
const StaticBlock({super.key, required this.content, this.onTap});
final String content;
final VoidCallback? onTap;
@override
State<StaticBlock> createState() => _StaticBlockState();
}
class _StaticBlockState extends State<StaticBlock> {
RenderedBlock? _r;
@override
void dispose() {
_r?.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final app = AppScope.read(context);
return LayoutBuilder(
builder: (context, box) => ListenableBuilder(
listenable: app.refs,
builder: (context, _) {
_r?.dispose();
_r = BlockRenderer(
RenderContext(
colors: context.colors,
base: blockTextStyle(context),
refs: app.refs,
assetPath: app.backend.assetPath,
onPage: app.openTitle,
onBlockRef: (r) => app.openId(r.pageId),
onUrl: openUrl,
maxWidth: box.maxWidth,
),
).render(widget.content);
return GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: widget.onTap,
child: Text.rich(_r!.span),
);
},
),
);
}
}
/// Bullet dot used outside the editor.
class Dot extends StatelessWidget {
const Dot({super.key});
@override
Widget build(BuildContext context) => SizedBox(
width: 18,
height: blockFontSize * blockLineHeight,
child: Center(
child: Container(
width: 5,
height: 5,
decoration: BoxDecoration(
shape: BoxShape.circle,
color: context.colors.faint,
),
),
),
);
}
+48
View File
@@ -0,0 +1,48 @@
const _months = [
'January', 'February', 'March', 'April', 'May', 'June', 'July', //
'August', 'September', 'October', 'November', 'December',
];
const _days = [
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday',
'Sunday',
];
DateTime parseDay(String ymd) {
final p = ymd.split('-');
return DateTime.utc(int.parse(p[0]), int.parse(p[1]), int.parse(p[2]));
}
String formatDay(DateTime d) =>
'${d.year.toString().padLeft(4, '0')}-${d.month.toString().padLeft(2, '0')}-'
'${d.day.toString().padLeft(2, '0')}';
/// "21 October 2026"
String longDate(String ymd) {
final d = parseDay(ymd);
return '${d.day} ${_months[d.month - 1]} ${d.year}';
}
/// "Tuesday"
String weekday(String ymd) => _days[parseDay(ymd).weekday - 1];
/// "21 Oct"
String shortDate(DateTime d) =>
'${d.day} ${_months[d.month - 1].substring(0, 3)}';
String monthName(int month) => _months[month - 1];
/// "Today", "Yesterday" or null.
String? relativeDay(String ymd, String today) {
final diff = parseDay(today).difference(parseDay(ymd)).inDays;
return switch (diff) {
0 => 'Today',
1 => 'Yesterday',
-1 => 'Tomorrow',
_ => null,
};
}