dashPi: a self-hosted home dashboard, its sync server and phone app

The dashboard (Raspberry Pi 3.5" screen + web pages), the end-to-end
encrypted sync mailbox (PHP + SQLite) and the Android companion app
(Flutter), with docs, clean-install checks and screenshots made from
demo data.

Built mostly with an AI coding assistant; not yet reviewed line by line
by a human (see README and SECURITY.md).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Bashy 2026-10-24 09:35:12 +02:00
commit fb3c01cdd7
333 changed files with 45151 additions and 0 deletions

284
app/lib/notes/markdown.dart Normal file
View file

@ -0,0 +1,284 @@
// Markdown → widgets for the notes' preview: the same reading as the web page's (notes.js md):
// headings, paragraphs (a line break is a break), - / 1. lists (nested by indent), - [ ] tasks
// (tappable: onTask(n) with n counted like toggleTask), > quotes, ``` code, tables, --- rules;
// inline **bold**, *italic*, ~~strike~~, ==mark==, `code`, [links](https://…), bare URLs, #tags.
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../app/theme.dart';
const _cool = Color(0xFF5CC8FF), _dim = Color(0xFF5D6472), _codeBg = Color(0xFF10131A);
const mono = TextStyle(fontFamily: 'monospace', fontSize: 13.5);
final _fence = RegExp(r'^\s*(```|~~~)'), _head = RegExp(r'^(#{1,6})\s+(.*)$'), _hr = RegExp(r'^\s*([-*_])(\s*\1){2,}\s*$');
final _quote = RegExp(r'^\s*>'), _item = RegExp(r'^(\s*)([-*+]|\d+[.)])\s+(.*)$');
final _tsep = RegExp(r'^\s*\|?\s*:?-{2,}:?\s*(\|\s*:?-{2,}:?\s*)*\|?\s*$');
final _taskLine = RegExp(r'^(\s*(?:>\s*)*(?:[-*+]|\d+[.)])\s+\[)([ xX])(\].*)$');
final tagRe = RegExp(r'(^|\s)#(\p{L}[\p{L}\p{N}_/-]*)', unicode: true);
final _inline = RegExp(
r'`([^`]+)`' // 1 code
r'|\[([^\]]+)\]\(([^)\s]+)\)' // 2, 3 link
r'''|(https?://[^\s<>()]+[^\s<>().,;:!?'"])''' // 4 bare URL
r'|\*\*(.+?)\*\*|__(.+?)__' // 5, 6 bold
r'|(?<![*\w])\*(?!\s)(.+?)\*(?!\w)' // 7 italic
r'|(?<![_\w])_(?!\s)(.+?)_(?!\w)' // 8 italic
r'|~~(.+?)~~' // 9 strike
r'|==(.+?)==' // 10 mark
r'|(?<=^|\s)#(\p{L}[\p{L}\p{N}_/-]*)', // 11 tag
unicode: true);
/// Tick / untick the n-th checkbox in the text (counted outside code blocks, like the preview).
String toggleTask(String src, int n) {
final lines = src.split('\n');
var k = 0;
String? fence;
for (var i = 0; i < lines.length; i++) {
final f = _fence.firstMatch(lines[i]);
if (fence != null) {
if (lines[i].trim().startsWith(fence)) fence = null;
continue;
}
if (f != null) {
fence = f[1];
continue;
}
final m = _taskLine.firstMatch(lines[i]);
if (m != null && k++ == n) {
lines[i] = '${m[1]}${m[2] == ' ' ? 'x' : ' '}${m[3]}';
break;
}
}
return lines.join('\n');
}
class MarkdownView extends StatefulWidget {
const MarkdownView(this.text, {super.key, this.onTask, this.onTag});
final String text;
final void Function(int n)? onTask;
final void Function(String tag)? onTag;
@override
State<MarkdownView> createState() => _MarkdownViewState();
}
class _MarkdownViewState extends State<MarkdownView> {
final _taps = <TapGestureRecognizer>[];
int _task = 0;
@override
void dispose() {
for (final t in _taps) {
t.dispose();
}
super.dispose();
}
TapGestureRecognizer _tap(VoidCallback fn) {
final t = TapGestureRecognizer()..onTap = fn;
_taps.add(t);
return t;
}
void _openLink(String url) {
Clipboard.setData(ClipboardData(text: url));
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('Link copied: $url')));
}
// ---- inline ------------------------------------------------------------------------------
List<InlineSpan> _spans(String s, TextStyle st) {
final out = <InlineSpan>[];
var at = 0;
for (final m in _inline.allMatches(s)) {
if (m.start > at) out.add(TextSpan(text: s.substring(at, m.start), style: st));
at = m.end;
if (m[1] != null) {
out.add(TextSpan(text: m[1], style: st.merge(mono).copyWith(backgroundColor: _codeBg)));
} else if (m[2] != null || m[4] != null) {
final url = m[3] ?? m[4]!;
if (!RegExp(r'^(https?:|mailto:)', caseSensitive: false).hasMatch(url)) {
out.add(TextSpan(text: m[0], style: st));
continue;
}
out.add(TextSpan(text: m[2] ?? url, style: st.copyWith(color: _cool, decoration: TextDecoration.underline,
decorationColor: _cool), recognizer: _tap(() => _openLink(url))));
} else if (m[5] != null || m[6] != null) {
out.addAll(_spans(m[5] ?? m[6]!, st.copyWith(fontWeight: FontWeight.bold)));
} else if (m[7] != null || m[8] != null) {
out.addAll(_spans(m[7] ?? m[8]!, st.copyWith(fontStyle: FontStyle.italic)));
} else if (m[9] != null) {
out.addAll(_spans(m[9]!, st.copyWith(color: _dim, decoration: TextDecoration.lineThrough)));
} else if (m[10] != null) {
out.addAll(_spans(m[10]!, st.copyWith(backgroundColor: const Color(0xFF4A3B1E))));
} else if (m[11] != null) {
final tag = m[11]!;
out.add(TextSpan(text: '#$tag', style: st.copyWith(color: _cool),
recognizer: widget.onTag == null ? null : _tap(() => widget.onTag!(tag.toLowerCase()))));
}
}
if (at < s.length) out.add(TextSpan(text: s.substring(at), style: st));
return out;
}
Widget _text(String s, TextStyle st) => Text.rich(TextSpan(children: _spans(s, st)));
// ---- blocks ------------------------------------------------------------------------------
List<Widget> _blocks(String src, TextStyle base) {
final lines = src.replaceAll('\r\n', '\n').split('\n');
final out = <Widget>[];
bool starts(String l) =>
_fence.hasMatch(l) || _head.hasMatch(l) || _hr.hasMatch(l) || _quote.hasMatch(l) || _item.hasMatch(l);
var i = 0;
while (i < lines.length) {
final l = lines[i];
if (l.trim().isEmpty) {
i++;
continue;
}
RegExpMatch? m;
if ((m = _fence.firstMatch(l)) != null) {
final code = <String>[];
for (i++; i < lines.length && !lines[i].trim().startsWith(m![1]!); i++) {
code.add(lines[i]);
}
i++;
out.add(Container(
width: double.infinity,
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(color: _codeBg, borderRadius: BorderRadius.circular(10)),
child: SingleChildScrollView(scrollDirection: Axis.horizontal, child: Text(code.join('\n'), style: mono)),
));
} else if ((m = _head.firstMatch(l)) != null) {
final n = m![1]!.length;
final size = const [24.0, 20.0, 17.5, 15.5, 15.0, 15.0][n - 1];
out.add(Padding(
padding: const EdgeInsets.only(top: 6),
child: _text(m[2]!.replaceAll(RegExp(r'\s#+\s*$'), ''), base.copyWith(fontSize: size,
fontWeight: FontWeight.bold, color: n == 1 ? accent : n >= 4 ? muted : null)),
));
i++;
} else if (_hr.hasMatch(l)) {
out.add(const Divider(color: card2, height: 20));
i++;
} else if (_quote.hasMatch(l)) {
final q = <String>[];
for (; i < lines.length && _quote.hasMatch(lines[i]); i++) {
q.add(lines[i].replaceFirst(RegExp(r'^\s*>\s?'), ''));
}
out.add(Container(
padding: const EdgeInsets.only(left: 12),
decoration: const BoxDecoration(border: Border(left: BorderSide(color: Color(0xFF3A4253), width: 3))),
child: _column(_blocks(q.join('\n'), base.copyWith(color: muted))),
));
} else if (l.contains('|') && i + 1 < lines.length && _tsep.hasMatch(lines[i + 1])) {
List<String> cells(String x) => x.trim().replaceAll(RegExp(r'^\||\|$'), '').split('|').map((c) => c.trim()).toList();
final rows = [cells(l)];
for (i += 2; i < lines.length && lines[i].contains('|') && lines[i].trim().isNotEmpty; i++) {
rows.add(cells(lines[i]));
}
final w = rows.map((r) => r.length).reduce((a, b) => a > b ? a : b);
out.add(SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Table(
defaultColumnWidth: const IntrinsicColumnWidth(),
border: TableBorder.all(color: card2),
children: [
for (final (k, r) in rows.indexed)
TableRow(
decoration: k == 0 ? const BoxDecoration(color: _codeBg) : null,
children: [
for (var c = 0; c < w; c++)
Padding(padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 5),
child: _text(c < r.length ? r[c] : '', k == 0 ? base.copyWith(fontWeight: FontWeight.bold) : base)),
],
),
],
),
));
} else if (_item.hasMatch(l)) {
final items = <(int, bool, String)>[];
while (i < lines.length) {
final x = lines[i];
final im = _item.firstMatch(x);
if (im != null) {
items.add((im[1]!.replaceAll('\t', ' ').length, RegExp(r'\d').hasMatch(im[2]!), im[3]!));
} else if (x.trim().isNotEmpty && RegExp(r'^\s').hasMatch(x) && items.isNotEmpty) {
final (a, b, t) = items.removeLast(); // a wrapped line of the item above
items.add((a, b, '$t\n${x.trim()}'));
} else {
break;
}
i++;
}
out.add(_list(items, base));
} else {
final p = <String>[];
for (; i < lines.length && lines[i].trim().isNotEmpty && !(p.isNotEmpty && starts(lines[i])); i++) {
p.add(lines[i]);
}
out.add(_text(p.join('\n'), base));
}
}
return out;
}
/// One row per item, indented by its depth (the indents seen so far, like nested lists).
Widget _list(List<(int, bool, String)> items, TextStyle base) {
final stack = <int>[], numbers = <int>[];
final rows = <Widget>[];
for (final (ind, ordered, text) in items) {
while (stack.isNotEmpty && ind < stack.last) {
stack.removeLast();
numbers.removeLast();
}
if (stack.isEmpty || ind > stack.last) {
stack.add(ind);
numbers.add(0);
}
numbers[numbers.length - 1]++;
final depth = stack.length - 1;
final t = RegExp(r'^\[([ xX])\](\s+|$)([\s\S]*)$').firstMatch(text);
Widget lead;
Widget body;
if (t != null) {
final n = _task++, done = t[1] != ' ';
lead = InkWell(
onTap: widget.onTask == null ? null : () => widget.onTask!(n),
child: Padding(
padding: const EdgeInsets.only(right: 6),
child: Icon(done ? Icons.check_box : Icons.check_box_outline_blank, size: 21, color: done ? accent : muted),
),
);
body = _text(t[3]!, done ? base.copyWith(color: _dim, decoration: TextDecoration.lineThrough) : base);
} else {
lead = SizedBox(
width: 22,
child: Text(ordered ? '${numbers.last}.' : depth.isEven ? '•' : '◦', style: base.copyWith(color: muted)),
);
body = _text(text, base);
}
rows.add(Padding(
padding: EdgeInsets.only(left: 4 + depth * 20.0, top: 2, bottom: 2),
child: Row(crossAxisAlignment: CrossAxisAlignment.start, children: [lead, Expanded(child: body)]),
));
}
return _column(rows, gap: 0);
}
Widget _column(List<Widget> ws, {double gap = 8}) => Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
for (final (k, w) in ws.indexed) ...[if (k > 0) SizedBox(height: gap), w],
],
);
@override
Widget build(BuildContext context) {
for (final t in _taps) {
t.dispose();
}
_taps.clear();
_task = 0;
final base = DefaultTextStyle.of(context).style.copyWith(fontSize: 15.5, height: 1.45);
return _column(_blocks(widget.text, base), gap: 10);
}
}

View file

@ -0,0 +1,346 @@
// One note: Preview (markdown.dart — tap a checkbox to tick it, a #tag to list its notes) or Edit
// (the markdown text, a toolbar above the keyboard; Enter in a list item starts the next one).
// Saves a second after the last key and on leaving; when a sync changed the note meanwhile, the
// text is kept as a copy beside it (notes_model.saveNote). A change arriving while nothing is typed
// here just shows up.
import 'dart:async';
import 'package:flutter/material.dart';
import '../app/sync_service.dart';
import '../app/theme.dart';
import 'markdown.dart';
import 'notes_model.dart';
import 'notes_page.dart' show askFolder;
class NoteEditor extends StatefulWidget {
const NoteEditor({super.key, required this.sync, this.id, this.folder = '', this.pinned = false, this.startText = '',
this.onTag});
final SyncService sync;
final String? id; // null = a new note (saved once there's text)
final String folder, startText;
final bool pinned;
final void Function(String tag)? onTag;
@override
State<NoteEditor> createState() => _NoteEditorState();
}
final _itemRe = RegExp(r'^(\s*)([-*+]|\d+[.)])(\s+)(\[[ xX]\]\s+)?(.*)$');
class _NoteEditorState extends State<NoteEditor> {
late String? id = widget.id;
late final Note? first = id == null ? null : getNote(widget.sync.store, id!);
late final text = TextEditingController(text: first?.body ?? widget.startText);
late String? base = first?.rev;
late String folder = first?.folder ?? widget.folder;
late bool pinned = first?.pinned ?? widget.pinned;
late bool editing = first == null || first!.body.trim().isEmpty;
late String last = text.text;
bool dirty = false;
Timer? timer;
final focus = FocusNode();
SyncService get sync => widget.sync;
Note? get note => id == null ? null : getNote(sync.store, id!);
@override
void initState() {
super.initState();
sync.addListener(_synced);
if (first == null) text.selection = const TextSelection.collapsed(offset: 0);
}
@override
void dispose() {
_save(later: true);
sync.removeListener(_synced);
timer?.cancel();
text.dispose();
focus.dispose();
super.dispose();
}
/// Data arrived / changed: the note changed elsewhere and nothing's typed here → show it.
void _synced() {
if (id == null || !mounted) return;
final n = note;
if (n == null) { // deleted on another device
if (dirty) {
id = null; // what's typed becomes a new note
_save(later: true);
} else {
Navigator.of(context).maybePop();
}
return;
}
if (n.rev != base && !dirty) {
setState(() {
base = n.rev;
text.text = last = n.body;
});
}
if (n.folder != folder || n.pinned != pinned) {
setState(() {
folder = n.folder;
pinned = n.pinned;
});
}
}
/// later: from dispose / a sync callback — the pages hear about it after this frame.
void _save({bool later = false}) {
timer?.cancel();
if (!dirty) return;
dirty = false;
if (id == null && text.text.trim().isEmpty) return; // an empty new note: nothing to keep
final (nid, conflict) = saveNote(sync.store, id: id, body: text.text, base: base, folder: folder, pinned: pinned);
id = nid;
base = note?.rev;
if (later) {
scheduleMicrotask(sync.changed);
return;
}
sync.changed();
if (conflict && mounted) {
setState(() {});
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
content: Text('This note changed on another device meanwhile — your text is kept as a separate copy.')));
}
}
void _changed(String v) {
// Enter at the end of a list item: the next item (an empty item ends the list)
final p = text.selection.baseOffset;
if (v.length == last.length + 1 && p > 0 && text.selection.isCollapsed && v[p - 1] == '\n' &&
v.substring(0, p - 1) + v.substring(p) == last) {
final s = v.lastIndexOf('\n', p - 2) + 1;
final m = _itemRe.firstMatch(v.substring(s, p - 1));
if (m != null) {
if (m[5]!.trim().isEmpty) {
_set(v.substring(0, s) + v.substring(p), s);
} else {
final n = RegExp(r'^(\d+)([.)])$').firstMatch(m[2]!);
final mark = '${m[1]}${n == null ? m[2] : '${int.parse(n[1]!) + 1}${n[2]}'}${m[3]}${m[4] != null ? '[ ] ' : ''}';
_set(v.substring(0, p) + mark + v.substring(p), p + mark.length);
}
return;
}
}
last = v;
_dirty();
}
void _set(String v, int cursor) {
text.value = TextEditingValue(text: v, selection: TextSelection.collapsed(offset: cursor));
last = v;
_dirty();
}
void _dirty() {
dirty = true;
timer?.cancel();
timer = Timer(const Duration(seconds: 1), _save);
}
// ---- toolbar -------------------------------------------------------------------------------
void _wrap(String a, [String? b, String ph = 'text']) {
b ??= a;
final v = text.text, sel = text.selection.isValid ? text.selection : TextSelection.collapsed(offset: v.length);
final inner = sel.isCollapsed ? ph : sel.textInside(v);
_set(v.replaceRange(sel.start, sel.end, '$a$inner$b'), sel.start + a.length + inner.length);
text.selection = TextSelection(baseOffset: sel.start + a.length, extentOffset: sel.start + a.length + inner.length);
focus.requestFocus();
}
void _lines(String Function(String) fn) {
final v = text.text, sel = text.selection.isValid ? text.selection : TextSelection.collapsed(offset: v.length);
final s = sel.start == 0 ? 0 : v.lastIndexOf('\n', sel.start - 1) + 1;
var e = v.indexOf('\n', sel.end);
if (e < 0) e = v.length;
final block = v.substring(s, e).split('\n').map(fn).join('\n');
_set(v.replaceRange(s, e, block), s + block.length);
focus.requestFocus();
}
late final tools = <(Widget, String, VoidCallback)>[
(const Text('H', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 17)), 'Heading', () => _lines((l) =>
RegExp(r'^#{1,5}\s').hasMatch(l) ? '#$l' : RegExp(r'^#{6}\s').hasMatch(l) ? l.replaceFirst(RegExp(r'^#+\s'), '') : '# $l')),
(const Icon(Icons.format_bold), 'Bold', () => _wrap('**')),
(const Icon(Icons.format_italic), 'Italic', () => _wrap('*')),
(const Icon(Icons.format_strikethrough), 'Strikethrough', () => _wrap('~~')),
(const Icon(Icons.format_list_bulleted), 'List', () => _lines((l) => RegExp(r'^\s*[-*+]\s').hasMatch(l)
? l.replaceFirst(RegExp(r'^(\s*)[-*+]\s+(\[[ xX]\]\s+)?'), '') : '- $l')),
(const Icon(Icons.check_box_outlined), 'Checklist', () => _lines((l) => RegExp(r'^\s*[-*+]\s\[[ xX]\]').hasMatch(l)
? l.replaceFirst(RegExp(r'^\s*[-*+]\s\[[ xX]\]\s?'), '') : l.replaceFirst(RegExp(r'^\s*(?:[-*+]\s+)?'), '- [ ] '))),
(const Icon(Icons.format_quote), 'Quote', () => _lines((l) => l.startsWith('>') ? l.replaceFirst(RegExp(r'^>\s?'), '') : '> $l')),
(const Icon(Icons.code), 'Code', () => _wrap('`', '`', 'code')),
(const Icon(Icons.link), 'Link', () => _wrap('[', '](https://)', 'link')),
(const Icon(Icons.tag), 'Tag', () => _wrap('#', '', 'tag')),
];
// ---- the menu ------------------------------------------------------------------------------
Future<void> _move() async {
final f = await askFolder(context, sync, folder);
if (f == null) return;
setState(() => folder = cleanFolder(f));
if (id != null) {
_save();
setNote(sync.store, id!, {'folder': folder});
sync.changed();
}
}
void _pin() {
setState(() => pinned = !pinned);
if (id != null) {
_save();
setNote(sync.store, id!, {'pinned': pinned ? 1 : 0});
sync.changed();
}
}
void _trash() {
_save();
if (id != null) {
trashNote(sync.store, id!, true);
sync.changed();
}
dirty = false;
Navigator.pop(context);
}
@override
Widget build(BuildContext context) {
final n = note;
final trashed = n?.trashed != null;
final showEdit = editing && !trashed;
return Scaffold(
appBar: AppBar(
titleSpacing: 0,
title: InkWell(
onTap: trashed ? null : _move,
child: Row(mainAxisSize: MainAxisSize.min, children: [
Icon(folder.isEmpty ? Icons.folder_off_outlined : Icons.folder_outlined, size: 18, color: muted),
const SizedBox(width: 6),
Flexible(child: Text(folder.isEmpty ? 'No folder' : folder, overflow: TextOverflow.ellipsis,
style: const TextStyle(fontSize: 15, color: muted))),
]),
),
actions: [
if (!trashed) ...[
IconButton(
tooltip: editing ? 'Preview' : 'Edit',
icon: Icon(editing ? Icons.visibility_outlined : Icons.edit_outlined),
onPressed: () {
_save();
setState(() => editing = !editing);
if (editing) focus.requestFocus();
},
),
IconButton(
tooltip: pinned ? 'Unpin' : 'Pin to the top',
icon: Icon(pinned ? Icons.push_pin : Icons.push_pin_outlined, color: pinned ? accent : null),
onPressed: _pin,
),
],
PopupMenuButton<String>(
icon: const Icon(Icons.more_vert),
color: card2,
onSelected: (k) {
switch (k) {
case 'move':
_move();
case 'trash':
_trash();
case 'restore':
trashNote(sync.store, id!, false);
sync.changed();
case 'purge':
deleteNote(sync.store, id!);
sync.changed();
Navigator.pop(context);
}
},
itemBuilder: (_) => trashed
? const [
PopupMenuItem(value: 'restore', child: Text('Restore')),
PopupMenuItem(value: 'purge', child: Text('Delete for good', style: TextStyle(color: bad))),
]
: const [
PopupMenuItem(value: 'move', child: Text('Move to folder…')),
PopupMenuItem(value: 'trash', child: Text('Move to the trash')),
],
),
],
),
body: SafeArea(
top: false,
child: Column(children: [
if (trashed)
_banner('In the trash — restore it to edit.', null)
else if (n?.origin != null)
_banner('Conflicted copy: this note was changed on two devices at once, and this is the version that didn\'t '
'win — the other one kept the original. Take what you need, then keep it or move it to the trash.',
TextButton(onPressed: () {
setNote(sync.store, id!, {'origin': null});
sync.changed();
}, child: const Text('Keep as a normal note'))),
Expanded(
child: showEdit
? Padding(
padding: const EdgeInsets.fromLTRB(16, 4, 16, 0),
child: TextField(
controller: text,
focusNode: focus,
autofocus: first == null,
expands: true,
maxLines: null,
keyboardType: TextInputType.multiline,
textCapitalization: TextCapitalization.sentences,
style: const TextStyle(fontFamily: 'monospace', fontSize: 15, height: 1.45),
decoration: const InputDecoration(border: InputBorder.none,
hintText: 'Write in markdown: # heading, **bold**, - [ ] a task, #tag …'),
onChanged: _changed,
),
)
: ListView(padding: const EdgeInsets.fromLTRB(18, 10, 18, 40), children: [
if (text.text.trim().isEmpty)
const Text('Empty — tap ✎ to write.', style: TextStyle(color: muted))
else
MarkdownView(
text.text,
onTask: trashed ? null : (i) => setState(() {
_set(toggleTask(text.text, i), 0);
_save();
}),
onTag: widget.onTag == null ? null : (t) {
widget.onTag!(t);
Navigator.pop(context);
},
),
]),
),
if (showEdit)
Container(
color: card,
height: 46,
child: ListView(scrollDirection: Axis.horizontal, children: [
for (final (icon, tip, fn) in tools) IconButton(tooltip: tip, icon: icon, onPressed: fn),
]),
),
]),
),
);
}
Widget _banner(String msg, Widget? action) => Container(
width: double.infinity,
margin: const EdgeInsets.fromLTRB(12, 8, 12, 0),
padding: const EdgeInsets.fromLTRB(12, 10, 12, 4),
decoration: BoxDecoration(color: const Color(0xFF3A2A17), borderRadius: BorderRadius.circular(10)),
child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
Text(msg, style: const TextStyle(color: Color(0xFFF4D6A8), fontSize: 13.5)),
if (action != null) Align(alignment: Alignment.centerRight, child: action) else const SizedBox(height: 6),
]),
);
}

View file

@ -0,0 +1,136 @@
// Notes: the dashboard's notes plugin (plugins/notes/db.py) on the phone — one synced row per note
// in "notes.note": folder ("Work/Acme", '' = none), body (markdown), pinned, created / updated
// (UTC), rev / revs (versions, for the sync's "keep both copies" — SyncStore.forks), origin (a
// conflicted copy: the rev it keeps), trashed (in the trash since). Title = the first line, tags =
// the #words — worked out on read, like the web page.
import 'dart:math';
import '../sync/store.dart';
import 'markdown.dart' show tagRe;
const noteTable = 'notes.note';
const _revs = 200; // versions remembered per note (db.REVS)
String nowIso() => '${DateTime.now().toUtc().toIso8601String().substring(0, 19)}Z';
String newRev() {
final r = Random.secure();
return List.generate(6, (_) => r.nextInt(256).toRadixString(16).padLeft(2, '0')).join();
}
String noteTitle(String body) {
for (final l in body.split('\n')) {
final s = l.trim().replaceFirst(RegExp(r'^#+'), '').trim();
if (s.isNotEmpty) return s.length > 120 ? s.substring(0, 120) : s;
}
return 'Untitled';
}
List<String> noteTags(String body) {
final plain = body.replaceAll(RegExp(r'```[\s\S]*?(```|$)'), '').replaceAll(RegExp(r'`[^`\n]*`'), '');
return {for (final m in tagRe.allMatches(plain)) m[2]!.toLowerCase()}.toList();
}
String noteSnippet(String body) {
final lines = body.split('\n');
final first = lines.indexWhere((l) => l.trim().isNotEmpty);
final text = lines.skip(first + 1).map((l) => l.replaceFirst(RegExp(r'^\s*(?:[-*+]|\d+[.)])\s+(?:\[[ xX]\]\s+)?'), '')).join(' ')
.replaceAll(RegExp(r'[#>*_`~=\[\]]|\(http[^)]*\)'), '').replaceAll(RegExp(r'\s+'), ' ').trim();
return text.length > 160 ? text.substring(0, 160) : text;
}
/// " Work / Acme/ " → "Work/Acme".
String cleanFolder(String f) => f.replaceAll('\\', '/').split('/').map((p) => p.trim()).where((p) => p.isNotEmpty).join('/');
/// Lower case without accents, for search.
String fold(String s) {
const from = 'áäàâãåčćďéěëèêíïìîľĺňñóöòôõőřŕšśťúůüùûűýÿžźżłąęß';
const to = 'aaaaaaccdeeeeeiiiillnnoooooorrssstuuuuuuyyzzzlaes';
final out = StringBuffer();
for (final c in s.toLowerCase().split('')) {
final i = from.indexOf(c);
out.write(i < 0 ? c : to[i]);
}
return out.toString();
}
class Note {
Note(this.r);
final Map<String, dynamic> r;
String get id => r['_u'] as String;
String get body => (r['body'] as String?) ?? '';
String get folder => (r['folder'] as String?) ?? '';
bool get pinned => (r['pinned'] as num? ?? 0) != 0;
String get updated => (r['updated'] as String?) ?? '';
String get rev => (r['rev'] as String?) ?? '';
String? get origin => r['origin'] as String?;
String? get trashed => r['trashed'] as String?;
String get title => noteTitle(body);
List<String> get tags => noteTags(body);
}
List<Note> allNotes(SyncStore s) => [for (final r in s.rows(noteTable)) Note(r)];
Note? getNote(SyncStore s, String id) {
final r = s.row(noteTable, id);
return r == null ? null : Note(r);
}
/// Save the text typed on version [base] → (the note's id, conflict). A new note: no id. When the
/// note changed meanwhile (a sync came in), the text becomes a copy beside it (db.save).
(String, bool) saveNote(SyncStore s, {String? id, required String body, String? base, String folder = '', bool pinned = false}) {
final t = nowIso();
final cur = id == null ? null : s.row(noteTable, id);
if (cur == null || (base != null && base != cur['rev'] && body != cur['body'])) {
final rev = newRev(), nid = SyncStore.randomId();
final copy = cur != null;
s.put(noteTable, nid, {
'folder': copy ? cur['folder'] : cleanFolder(folder), 'body': body, 'pinned': copy ? 0 : (pinned ? 1 : 0),
'created': t, 'updated': t, 'rev': rev, 'revs': rev, 'origin': copy ? rev : null, 'trashed': null,
});
return (nid, copy);
}
if (body == cur['body']) return (id!, false);
final row = {...cur, 'body': body, 'updated': t};
if (s.known(noteTable, id!)) { // seen elsewhere: a new version (else typing goes on in this one)
final rev = newRev();
final revs = [...((cur['revs'] as String?) ?? '').split(' ').where((x) => x.isNotEmpty), rev];
row['rev'] = rev;
row['revs'] = revs.skip(max(0, revs.length - _revs)).join(' ');
}
s.put(noteTable, id, row);
return (id, false);
}
/// Pinned, folder, trashed, origin — no new version.
void setNote(SyncStore s, String id, Map<String, dynamic> fields) {
final cur = s.row(noteTable, id);
if (cur != null) s.put(noteTable, id, {...cur, ...fields});
}
void trashNote(SyncStore s, String id, bool on) => setNote(s, id, {'trashed': on ? nowIso() : null});
/// For good (from the trash).
void deleteNote(SyncStore s, String id) => s.delete(noteTable, id);
int emptyTrash(SyncStore s) {
final gone = allNotes(s).where((n) => n.trashed != null).toList();
for (final n in gone) {
s.delete(noteTable, n.id);
}
return gone.length;
}
/// Every note in [from] and its sub-folders moves to [to] (same sub-paths).
int renameFolder(SyncStore s, String from, String to) {
from = cleanFolder(from);
to = cleanFolder(to);
var n = 0;
for (final x in allNotes(s)) {
if (x.folder == from || x.folder.startsWith('$from/')) {
setNote(s, x.id, {'folder': cleanFolder(to + x.folder.substring(from.length))});
n++;
}
}
return n;
}

View file

@ -0,0 +1,437 @@
// Notes: the list — search box, where you are in the title (tap: All / Pinned / conflicted copies /
// folders / tags / Trash), pinned first, newest change first; + = a new note there; tap = the note
// (note_editor.dart), long-press = pin, move, trash. ⋮: rename the folder, empty the trash.
import 'package:flutter/material.dart';
import '../app/sync_service.dart';
import '../app/theme.dart';
import 'note_editor.dart';
import 'notes_model.dart';
/// Where the list is: all, pinned, conflicts, folder (value), tag (value), trash.
typedef NoteFilter = ({String kind, String? value});
class NotesPage extends StatefulWidget {
const NotesPage({super.key, required this.sync, this.actions = const []});
final SyncService sync;
final List<Widget> actions;
@override
State<NotesPage> createState() => _NotesPageState();
}
class _NotesPageState extends State<NotesPage> {
NoteFilter filter = (kind: 'all', value: null);
final search = TextEditingController();
String get label => switch (filter.kind) {
'pinned' => 'Pinned',
'conflicts' => 'Conflicted copies',
'folder' => filter.value!.split('/').last,
'tag' => '#${filter.value}',
'trash' => 'Trash',
_ => 'Notes',
};
List<Note> shown(List<Note> all) {
var l = filter.kind == 'trash' ? all.where((n) => n.trashed != null) : all.where((n) => n.trashed == null);
l = switch (filter.kind) {
'pinned' => l.where((n) => n.pinned),
'conflicts' => l.where((n) => n.origin != null),
'folder' => l.where((n) => n.folder == filter.value || n.folder.startsWith('${filter.value}/')),
'tag' => l.where((n) => n.tags.contains(filter.value)),
_ => l,
};
final words = fold(search.text).split(RegExp(r'\s+')).where((w) => w.isNotEmpty).toList();
if (words.isNotEmpty) {
l = l.where((n) {
final t = fold('${n.body} ${n.folder}');
return words.every(t.contains);
});
}
final out = l.toList()
..sort((a, b) {
if (filter.kind != 'trash' && a.pinned != b.pinned) return a.pinned ? -1 : 1;
return (b.trashed ?? b.updated).compareTo(a.trashed ?? a.updated);
});
return out;
}
void _open(Note? n) => Navigator.push(context, MaterialPageRoute(builder: (_) => NoteEditor(
sync: widget.sync,
id: n?.id,
folder: filter.kind == 'folder' ? filter.value! : '',
pinned: filter.kind == 'pinned',
startText: filter.kind == 'tag' ? '\n\n#${filter.value}' : '',
onTag: (t) => setState(() => filter = (kind: 'tag', value: t)),
)));
/// The sheet behind the title: where to look.
void _where(List<Note> all) {
final live = all.where((n) => n.trashed == null).toList();
final folders = <String, int>{};
for (final n in live) {
if (n.folder.isEmpty) continue;
final parts = n.folder.split('/');
for (var i = 1; i <= parts.length; i++) {
final p = parts.take(i).join('/');
folders[p] = (folders[p] ?? 0) + 1;
}
}
final tags = <String, int>{};
for (final n in live) {
for (final t in n.tags) {
tags[t] = (tags[t] ?? 0) + 1;
}
}
final pinned = live.where((n) => n.pinned).length, copies = live.where((n) => n.origin != null).length;
showModalBottomSheet(
context: context,
backgroundColor: card,
isScrollControlled: true,
builder: (c) {
Widget item(NoteFilter f, Widget icon, String text, int n, {int depth = 0}) => ListTile(
dense: true,
contentPadding: EdgeInsets.only(left: 16 + depth * 18.0, right: 16),
leading: icon,
title: Text(text, overflow: TextOverflow.ellipsis),
trailing: n > 0 ? Text('$n', style: const TextStyle(color: muted)) : null,
selected: f == filter,
selectedColor: accent,
onTap: () {
Navigator.pop(c);
setState(() => filter = f);
},
);
final names = folders.keys.toList()..sort();
final tagNames = tags.keys.toList()..sort();
return DraggableScrollableSheet(
expand: false,
initialChildSize: .6,
maxChildSize: .92,
builder: (_, scroll) => ListView(controller: scroll, children: [
item((kind: 'all', value: null), const Icon(Icons.notes), 'All notes', live.length),
if (pinned > 0) item((kind: 'pinned', value: null), const Icon(Icons.push_pin_outlined), 'Pinned', pinned),
if (copies > 0)
item((kind: 'conflicts', value: null), const Icon(Icons.warning_amber, color: Color(0xFFFF9A4D)),
'Conflicted copies', copies),
if (names.isNotEmpty) const _Cap('Folders'),
for (final f in names)
item((kind: 'folder', value: f), const Icon(Icons.folder_outlined, size: 20), f.split('/').last, folders[f]!,
depth: '/'.allMatches(f).length),
if (tagNames.isNotEmpty) ...[
const _Cap('Tags'),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 14),
child: Wrap(spacing: 6, runSpacing: 6, children: [
for (final t in tagNames)
ChoiceChip(
label: Text('#$t ${tags[t]}'),
selected: filter == (kind: 'tag', value: t),
onSelected: (_) {
Navigator.pop(c);
setState(() => filter = (kind: 'tag', value: t));
},
),
]),
),
],
const Divider(color: card2),
item((kind: 'trash', value: null), const Icon(Icons.delete_outline), 'Trash', all.length - live.length),
const SizedBox(height: 12),
]),
);
},
);
}
/// Long-press: pin, move, trash (or, in the trash: restore, delete for good).
void _actions(Note n) {
final s = widget.sync.store;
showModalBottomSheet(
context: context,
backgroundColor: card,
builder: (c) => SafeArea(child: Column(mainAxisSize: MainAxisSize.min, children: [
ListTile(title: Text(n.title, style: const TextStyle(fontWeight: FontWeight.bold), overflow: TextOverflow.ellipsis)),
if (n.trashed == null) ...[
ListTile(
leading: Icon(n.pinned ? Icons.push_pin : Icons.push_pin_outlined),
title: Text(n.pinned ? 'Unpin' : 'Pin to the top'),
onTap: () {
Navigator.pop(c);
setNote(s, n.id, {'pinned': n.pinned ? 0 : 1});
widget.sync.changed();
},
),
ListTile(
leading: const Icon(Icons.drive_file_move_outlined),
title: const Text('Move to folder…'),
onTap: () async {
Navigator.pop(c);
final f = await askFolder(context, widget.sync, n.folder);
if (f != null) {
setNote(s, n.id, {'folder': cleanFolder(f)});
widget.sync.changed();
}
},
),
ListTile(
leading: const Icon(Icons.delete_outline),
title: const Text('Move to the trash'),
onTap: () {
Navigator.pop(c);
trashNote(s, n.id, true);
widget.sync.changed();
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: const Text('Moved to the trash'),
persist: false, // with an action Flutter keeps it up until tapped
action: SnackBarAction(label: 'Undo', onPressed: () {
trashNote(s, n.id, false);
widget.sync.changed();
}),
));
},
),
] else ...[
ListTile(
leading: const Icon(Icons.restore),
title: const Text('Restore'),
onTap: () {
Navigator.pop(c);
trashNote(s, n.id, false);
widget.sync.changed();
},
),
ListTile(
leading: const Icon(Icons.delete_forever, color: bad),
title: const Text('Delete for good', style: TextStyle(color: bad)),
onTap: () {
Navigator.pop(c);
deleteNote(s, n.id);
widget.sync.changed();
},
),
],
])),
);
}
Future<void> _renameFolder() async {
final old = filter.value!;
final to = await askText(context, 'Rename folder', old, hint: 'a/b for a sub-folder');
if (to == null || cleanFolder(to).isEmpty || cleanFolder(to) == old) return;
renameFolder(widget.sync.store, old, to);
widget.sync.changed();
setState(() => filter = (kind: 'folder', value: cleanFolder(to)));
}
void _emptyTrash() => showDialog(
context: context,
builder: (d) => AlertDialog(
title: const Text('Empty the trash?'),
content: const Text('The notes in it are deleted on every device.'),
actions: [
TextButton(onPressed: () => Navigator.pop(d), child: const Text('Cancel')),
TextButton(onPressed: () {
Navigator.pop(d);
emptyTrash(widget.sync.store);
widget.sync.changed();
}, child: const Text('Delete them', style: TextStyle(color: bad))),
],
),
);
@override
Widget build(BuildContext context) => ListenableBuilder(
listenable: widget.sync,
builder: (context, _) {
final all = allNotes(widget.sync.store);
final list = shown(all);
return Scaffold(
appBar: AppBar(
title: InkWell(
onTap: () => _where(all),
child: Row(mainAxisSize: MainAxisSize.min, children: [
Flexible(child: Text(label, overflow: TextOverflow.ellipsis)),
const Icon(Icons.arrow_drop_down),
]),
),
actions: [
...widget.actions,
if (filter.kind == 'folder' || filter.kind == 'trash')
PopupMenuButton<String>(
icon: const Icon(Icons.more_vert),
color: card2,
onSelected: (k) => k == 'rename' ? _renameFolder() : _emptyTrash(),
itemBuilder: (_) => [
if (filter.kind == 'folder') const PopupMenuItem(value: 'rename', child: Text('Rename folder')),
if (filter.kind == 'trash') const PopupMenuItem(value: 'empty', child: Text('Empty the trash')),
],
),
],
),
floatingActionButton: filter.kind == 'trash'
? null
: FloatingActionButton(
backgroundColor: accent,
foregroundColor: bg,
tooltip: 'New note',
onPressed: () => _open(null),
child: const Icon(Icons.add),
),
body: Column(children: [
Padding(
padding: const EdgeInsets.fromLTRB(12, 4, 12, 6),
child: TextField(
controller: search,
onChanged: (_) => setState(() {}),
decoration: InputDecoration(
isDense: true,
hintText: 'Search notes',
prefixIcon: const Icon(Icons.search, size: 20),
suffixIcon: search.text.isEmpty ? null : IconButton(
icon: const Icon(Icons.close, size: 18),
onPressed: () => setState(search.clear),
),
filled: true,
fillColor: card,
border: OutlineInputBorder(borderRadius: BorderRadius.circular(10), borderSide: BorderSide.none),
),
),
),
Expanded(
child: list.isEmpty
? Center(child: Text(
search.text.isNotEmpty ? 'Nothing matches.'
: filter.kind == 'trash' ? 'The trash is empty.' : 'No notes here yet — + to write one.',
style: const TextStyle(color: muted)))
: ListView.builder(
padding: const EdgeInsets.fromLTRB(12, 0, 12, 88),
itemCount: list.length,
itemBuilder: (_, i) => _tile(list[i]),
),
),
]),
);
},
);
Widget _tile(Note n) {
final snip = noteSnippet(n.body), tags = n.tags.take(4).toList();
final showFolder = filter.kind != 'folder' && n.folder.isNotEmpty;
return Card(
margin: const EdgeInsets.only(bottom: 8),
child: InkWell(
borderRadius: BorderRadius.circular(12),
onTap: () => _open(n),
onLongPress: () => _actions(n),
child: Padding(
padding: const EdgeInsets.fromLTRB(14, 10, 14, 10),
child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
Row(children: [
if (n.pinned && filter.kind != 'trash')
const Padding(padding: EdgeInsets.only(right: 4), child: Icon(Icons.push_pin, size: 15, color: accent)),
if (n.origin != null)
const Padding(padding: EdgeInsets.only(right: 4),
child: Icon(Icons.warning_amber, size: 16, color: Color(0xFFFF9A4D))),
Expanded(child: Text(n.title, maxLines: 1, overflow: TextOverflow.ellipsis,
style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold))),
const SizedBox(width: 8),
Text(when(n.trashed ?? n.updated), style: const TextStyle(color: muted, fontSize: 12)),
]),
if (snip.isNotEmpty)
Padding(
padding: const EdgeInsets.only(top: 3),
child: Text(snip, maxLines: 2, overflow: TextOverflow.ellipsis, style: const TextStyle(color: muted, fontSize: 13.5)),
),
if (showFolder || tags.isNotEmpty)
Padding(
padding: const EdgeInsets.only(top: 5),
child: Wrap(spacing: 10, children: [
if (showFolder) Text('▸ ${n.folder}', style: const TextStyle(color: Color(0xFF5D6472), fontSize: 12)),
for (final t in tags) Text('#$t', style: const TextStyle(color: Color(0xFF5CC8FF), fontSize: 12)),
]),
),
]),
),
),
);
}
}
class _Cap extends StatelessWidget {
const _Cap(this.text);
final String text;
@override
Widget build(BuildContext context) => Padding(
padding: const EdgeInsets.fromLTRB(16, 14, 16, 4),
child: Text(text.toUpperCase(), style: const TextStyle(color: muted, fontSize: 12, fontWeight: FontWeight.bold)),
);
}
/// "14:05" today, "3 Oct" this year, else "3 Oct 2025".
String when(String iso) {
final d = DateTime.tryParse(iso)?.toLocal();
if (d == null) return '';
final now = DateTime.now();
const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
if (d.year == now.year && d.month == now.month && d.day == now.day) {
return '${d.hour.toString().padLeft(2, '0')}:${d.minute.toString().padLeft(2, '0')}';
}
return '${d.day} ${months[d.month - 1]}${d.year == now.year ? '' : ' ${d.year}'}';
}
/// A one-line text dialog → the text, or null when cancelled.
Future<String?> askText(BuildContext context, String title, String value, {String? hint}) {
final c = TextEditingController(text: value);
return showDialog<String>(
context: context,
builder: (d) => AlertDialog(
title: Text(title),
content: TextField(controller: c, autofocus: true, decoration: InputDecoration(hintText: hint),
onSubmitted: (v) => Navigator.pop(d, v)),
actions: [
TextButton(onPressed: () => Navigator.pop(d), child: const Text('Cancel')),
TextButton(onPressed: () => Navigator.pop(d, c.text), child: const Text('OK')),
],
),
);
}
/// Pick a folder (the ones there are, or type a new one; '' = none) → null when cancelled.
Future<String?> askFolder(BuildContext context, SyncService sync, String current) {
final names = {for (final n in allNotes(sync.store)) if (n.trashed == null && n.folder.isNotEmpty) n.folder}.toList()..sort();
return showModalBottomSheet<String>(
context: context,
backgroundColor: card,
isScrollControlled: true,
builder: (c) => SafeArea(child: ConstrainedBox(
constraints: BoxConstraints(maxHeight: MediaQuery.of(c).size.height * .7),
child: ListView(shrinkWrap: true, children: [
const ListTile(title: Text('Move to folder', style: TextStyle(fontWeight: FontWeight.bold))),
ListTile(
leading: const Icon(Icons.create_new_folder_outlined),
title: const Text('New folder…'),
onTap: () async {
final f = await askText(c, 'New folder', current, hint: 'a/b for a sub-folder');
if (c.mounted) Navigator.pop(c, f);
},
),
ListTile(
leading: const Icon(Icons.folder_off_outlined),
title: const Text('No folder'),
selected: current.isEmpty,
selectedColor: accent,
onTap: () => Navigator.pop(c, ''),
),
for (final f in names)
ListTile(
leading: const Icon(Icons.folder_outlined),
title: Text(f),
selected: f == current,
selectedColor: accent,
onTap: () => Navigator.pop(c, f),
),
]),
)),
);
}