// 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'|(? createState() => _MarkdownViewState(); } class _MarkdownViewState extends State { final _taps = []; 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 _spans(String s, TextStyle st) { final out = []; 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 _blocks(String src, TextStyle base) { final lines = src.replaceAll('\r\n', '\n').split('\n'); final out = []; 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 = []; 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 = []; 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 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 = []; 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 = [], numbers = []; final rows = []; 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 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); } }