todo-app/lib/sync/notes_markdown.dart
Krzysztof kuhy Rudnicki 9f2ffdb8a9
Some checks failed
dependency freshness / dependencies on newest stable (push) Has been cancelled
file-length / file length <= 250 lines (push) Has been cancelled
md-naming / markdown naming convention (push) Has been cancelled
release-apk / release (APK) (push) Has been cancelled
Attach any file to a note, of any size, not only images
📎 now picks any file (Android: Camera / Gallery / File; desktop: an
unfiltered dialog) and the desktop page accepts any dropped file. Photo and
screenshot formats up to 64 MB are still re-encoded and shown inline;
everything else is stored byte for byte on dufs beside the images and linked
as [name](url), shown as a row with its size that opens in the platform's
app (Android) or a new browser tab (desktop). BACKLOG.md rewrites file links
to ~/data/cloud/todo-images/ like image links.

There is no size cap, so no layer holds a file in memory: uploads and
downloads stream through DufsImageClient, writes land in a .tmp renamed when
whole (an interrupted download no longer leaves a truncated file that looks
done), the desktop page POSTs the browser's own Blob with fetch, and Android's
"File" uses file_picker, because file_selector's Android side reads the whole
file into memory on the UI thread. Verified with a 1 GB file end to end on
desktop (peak RSS +36 MB) and on an API 36 emulator.

The wrapper serves attachments from the origin that holds the GitHub token
and the notes, so only script-free types open inline (nosniff), the rest
download; writes carrying another site's Origin are refused (this also
closes cross-site overwrites of the backup files); and attachment routes run
concurrently so a long upload or a playing video cannot stall the page.

Also: cupertino_icons 2.0.0 (unused, but the freshness gate blocks the
pubspec otherwise), open_file 4.0.0 and file_picker 13.1.0 pinned.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 12:17:06 +02:00

112 lines
4.0 KiB
Dart

import 'package:todo/data/note.dart';
import 'package:todo/images/attachment_links.dart';
import 'package:uuid/uuid.dart';
/// Serialises notes to (and parses them back from) a single Markdown file.
///
/// The whole document is valid Markdown: each note is preceded by an HTML
/// comment carrying its metadata (id, priority, status, timestamps), which
/// renders invisibly, followed by the note body verbatim. Keeping the `id`
/// lets [NoteRepository.importNotes] re-import a file as a *merge* (by id)
/// rather than creating duplicates — the basis for "never lose ideas"
/// recovery and round-tripping a backup.
///
/// Attached-image links are written as their on-disk path on kuhy's PC
/// (`~/data/cloud/todo-images/…`) so an agent reading `BACKLOG.md` can open
/// the picture directly; [parse] turns them back into the dufs URL, so a
/// backup still round-trips exactly.
class NotesMarkdown {
// Private ctor: this is a static-only utility class, never instantiated.
const NotesMarkdown._(); // coverage:ignore-line
static const _uuid = Uuid();
/// First line of an exported file; identifies the format/version.
static const header = '<!-- todo-backlog v1 -->';
/// Matches a per-note metadata marker at the start of a line. The body is
/// everything between one marker and the next (or end of file).
static final _markerPattern = RegExp(
r'^<!--\s*@note\s+(.*?)\s*-->[ \t]*$',
multiLine: true,
);
/// Matches `key="value"` attribute pairs inside a marker.
static final _attrPattern = RegExp(r'(\w+)="([^"]*)"');
/// Renders [notes] to a single Markdown document.
static String export(List<Note> notes) {
final buffer = StringBuffer()
..writeln(header)
..writeln();
for (final note in notes) {
buffer
..writeln(
'<!-- @note id="${note.id}" priority="${note.priority.name}" '
'status="${note.status.name}" '
'created="${note.createdAt.toIso8601String()}" '
'updated="${note.updatedAt.toIso8601String()}" -->',
)
..writeln(toBacklogAttachmentPaths(note.text))
..writeln();
}
return buffer.toString();
}
/// Parses a previously exported (or hand-written) document back into notes.
///
/// Tolerant by design: a missing/blank `id` gets a fresh UUID (treated as
/// a new note), and unknown/missing priority/status/timestamps fall back
/// to sensible defaults so a partially hand-edited file never throws.
static List<Note> parse(String content) {
final markers = _markerPattern.allMatches(content).toList();
final notes = <Note>[];
for (var i = 0; i < markers.length; i++) {
final marker = markers[i];
final attrs = _parseAttrs(marker.group(1) ?? '');
final bodyStart = marker.end;
final bodyEnd = i + 1 < markers.length
? markers[i + 1].start
: content.length;
final body = fromBacklogAttachmentPaths(
content.substring(bodyStart, bodyEnd).trim(),
);
final id = attrs['id'];
notes.add(
Note(
id: (id != null && id.isNotEmpty) ? id : _uuid.v4(),
text: body,
priority: _enumByName(
Priority.values,
attrs['priority'],
Priority.defaultValue,
),
status: _enumByName(Status.values, attrs['status'], Status.todo),
createdAt:
DateTime.tryParse(attrs['created'] ?? '') ?? DateTime.now(),
updatedAt:
DateTime.tryParse(attrs['updated'] ?? '') ?? DateTime.now(),
),
);
}
return notes;
}
/// Extracts `key="value"` pairs from a marker's attribute string.
static Map<String, String> _parseAttrs(String raw) {
return {
for (final m in _attrPattern.allMatches(raw)) m.group(1)!: m.group(2)!,
};
}
/// Resolves an enum value by its [Enum.name], falling back to [fallback].
static T _enumByName<T extends Enum>(
List<T> values,
String? name,
T fallback,
) {
return values.firstWhere((v) => v.name == name, orElse: () => fallback);
}
}