mirror of
https://github.com/Dasemu/Synapse.git
synced 2026-11-26 15:26:17 +00:00
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:
1 parent
c3d6636606
commit
df42d4010f
135 files changed
+17689
No files matched your search
@@ -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),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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),
|
||||
);
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
// 
|
||||
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,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -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),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user