dashboard/app/lib/notes/note_editor.dart
bashynx fb3c01cdd7 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>
2026-10-24 09:56:19 +02:00

346 lines
13 KiB
Dart

// 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),
]),
);
}