Files
Docwell/Phone-App/lib/screens/markdown_view.dart
T
tajniak81andClaude Opus 5.5 c239d859b8 Transcribe long recordings, read scanned PDFs, and bring AI writing to phones
Follow-ups to Phase E (ADR-15):

- Recordings over 25 MB are cut into pieces and transcribed in turn:
  with ffmpeg (now in the server and all-in-one images) any format is
  re-encoded to 16 kHz mono MP3 in 20-minute pieces; without it, MP3 is
  cut at frame boundaries and WAV at sample boundaries in Go.
- PDFs without a text layer are written out by a document-capable chat
  model (Anthropic document input, OpenAI file input); Ollama is skipped.
- Phone app: AI answers render as Markdown with tappable citations; the
  editing toolbar opens the writing actions on the selection; audio
  files get Transcribe. Editor bridge protocol 4 adds setAi,
  getSelection, insertMarkdown and transcribe/transcribed.
- The transcript HTML builder moves to @docwell/editor, shared by the
  web app and the phone editor.
- An integration test runs chat, Transcribe and writing actions on a
  device against a live server; the editor test no longer expects
  headings to have only a level.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 10:04:10 +01:00

338 lines
10 KiB
Dart

// SPDX-License-Identifier: AGPL-3.0-or-later
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:markdown/markdown.dart' as md;
/// Draws an AI answer's Markdown: headings, paragraphs, lists and task
/// lists, quotes, code, tables and inline formatting. Citations like [1]
/// become tappable badges ([onCite]).
class MarkdownView extends StatefulWidget {
const MarkdownView(this.text, {super.key, this.onCite, this.style});
final String text;
final void Function(int n)? onCite;
/// The body text style (defaults to the theme's bodyMedium).
final TextStyle? style;
@override
State<MarkdownView> createState() => _MarkdownViewState();
}
class _MarkdownViewState extends State<MarkdownView> {
final _recognizers = <TapGestureRecognizer>[];
@override
void dispose() {
_dropRecognizers();
super.dispose();
}
void _dropRecognizers() {
for (final r in _recognizers) {
r.dispose();
}
_recognizers.clear();
}
@override
Widget build(BuildContext context) {
_dropRecognizers();
final nodes = md.Document(
extensionSet: md.ExtensionSet.gitHubFlavored,
encodeHtml: false,
).parse(widget.text);
final theme = Theme.of(context);
final base =
widget.style ?? theme.textTheme.bodyMedium ?? const TextStyle();
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: _blocks(nodes, base, theme),
);
}
List<Widget> _blocks(List<md.Node> nodes, TextStyle base, ThemeData theme) {
final out = <Widget>[];
for (final n in nodes) {
final w = _block(n, base, theme);
if (w != null) {
out.add(Padding(padding: const EdgeInsets.only(bottom: 8), child: w));
}
}
return out;
}
Widget? _block(md.Node node, TextStyle base, ThemeData theme) {
if (node is md.Text) {
return node.text.trim().isEmpty
? null
: Text.rich(TextSpan(children: _inline([node], base, theme)));
}
if (node is! md.Element) return null;
final kids = node.children ?? const <md.Node>[];
switch (node.tag) {
case 'h1' || 'h2' || 'h3' || 'h4' || 'h5' || 'h6':
final scale = switch (node.tag) {
'h1' => 1.4,
'h2' => 1.25,
'h3' => 1.12,
_ => 1.0,
};
final style = base.copyWith(
fontWeight: FontWeight.w700,
fontSize: (base.fontSize ?? 14) * scale,
);
return Text.rich(TextSpan(children: _inline(kids, style, theme)));
case 'p':
return Text.rich(TextSpan(children: _inline(kids, base, theme)));
case 'ul' || 'ol':
final ordered = node.tag == 'ol';
final start = int.tryParse(node.attributes['start'] ?? '') ?? 1;
var i = 0;
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
for (final li in kids.whereType<md.Element>())
_listItem(li, ordered ? '${start + i++}.' : '•', base, theme),
],
);
case 'blockquote':
return Container(
padding: const EdgeInsets.only(left: 10),
decoration: BoxDecoration(
border: Border(
left: BorderSide(
color: theme.colorScheme.outlineVariant,
width: 3,
),
),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: _blocks(kids, base, theme),
),
);
case 'pre':
return Container(
padding: const EdgeInsets.all(10),
decoration: BoxDecoration(
color: theme.colorScheme.surfaceContainerHighest,
borderRadius: BorderRadius.circular(6),
),
child: SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Text(
node.textContent.trimRight(),
style: base.copyWith(
fontFamily: 'monospace',
fontSize: (base.fontSize ?? 14) * 0.9,
),
),
),
);
case 'hr':
return const Divider();
case 'table':
return _table(node, base, theme);
}
// Anything else: its children as blocks.
final inner = _blocks(kids, base, theme);
return inner.isEmpty
? null
: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: inner,
);
}
Widget _listItem(
md.Element li,
String mark,
TextStyle base,
ThemeData theme,
) {
var kids = li.children ?? const <md.Node>[];
// GitHub task lists: an <input type=checkbox> leads the item.
String? box;
final first = kids.isEmpty ? null : kids.first;
if (first is md.Element && first.tag == 'input') {
box = first.attributes.containsKey('checked') ? '☑' : '☐';
kids = kids.skip(1).toList();
}
final blockTags = {'p', 'ul', 'ol', 'pre', 'blockquote', 'table'};
final hasBlocks = kids.any(
(k) => k is md.Element && blockTags.contains(k.tag),
);
return Padding(
padding: const EdgeInsets.only(bottom: 2),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(width: 22, child: Text(box ?? mark, style: base)),
Expanded(
child: hasBlocks
? Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: _blocks(kids, base, theme),
)
: Text.rich(TextSpan(children: _inline(kids, base, theme))),
),
],
),
);
}
Widget _table(md.Element table, TextStyle base, ThemeData theme) {
final rows = <TableRow>[];
void addRows(md.Element section, bool head) {
for (final tr
in (section.children ?? const <md.Node>[]).whereType<md.Element>()) {
rows.add(
TableRow(
children: [
for (final cell
in (tr.children ?? const <md.Node>[]).whereType<md.Element>())
Padding(
padding: const EdgeInsets.all(6),
child: Text.rich(
TextSpan(
children: _inline(
cell.children ?? const [],
head
? base.copyWith(fontWeight: FontWeight.w600)
: base,
theme,
),
),
),
),
],
),
);
}
}
for (final section
in (table.children ?? const <md.Node>[]).whereType<md.Element>()) {
addRows(section, section.tag == 'thead');
}
if (rows.isEmpty) return const SizedBox.shrink();
final cols = rows
.map((r) => r.children.length)
.reduce((a, b) => a > b ? a : b);
for (var i = 0; i < rows.length; i++) {
final missing = cols - rows[i].children.length;
if (missing > 0) {
rows[i] = TableRow(
children: [
...rows[i].children,
for (var j = 0; j < missing; j++) const SizedBox.shrink(),
],
);
}
}
return SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Table(
defaultColumnWidth: const IntrinsicColumnWidth(),
border: TableBorder.all(color: theme.colorScheme.outlineVariant),
children: rows,
),
);
}
static final _cite = RegExp(r'\[(\d{1,2})\]');
List<InlineSpan> _inline(
List<md.Node> nodes,
TextStyle style,
ThemeData theme,
) {
final out = <InlineSpan>[];
for (final n in nodes) {
if (n is md.Text) {
out.addAll(_text(n.text, style, theme));
continue;
}
if (n is! md.Element) continue;
final kids = n.children ?? const <md.Node>[];
switch (n.tag) {
case 'strong':
out.addAll(
_inline(kids, style.copyWith(fontWeight: FontWeight.w700), theme),
);
case 'em':
out.addAll(
_inline(kids, style.copyWith(fontStyle: FontStyle.italic), theme),
);
case 'del':
out.addAll(
_inline(
kids,
style.copyWith(decoration: TextDecoration.lineThrough),
theme,
),
);
case 'code':
out.add(
TextSpan(
text: n.textContent,
style: style.copyWith(
fontFamily: 'monospace',
backgroundColor: theme.colorScheme.surfaceContainerHighest,
),
),
);
case 'a':
out.addAll(
_inline(
kids,
style.copyWith(
color: theme.colorScheme.primary,
decoration: TextDecoration.underline,
),
theme,
),
);
case 'br':
out.add(const TextSpan(text: '\n'));
default:
out.addAll(_inline(kids, style, theme));
}
}
return out;
}
/// Plain text with its citations as tappable badges.
List<InlineSpan> _text(String text, TextStyle style, ThemeData theme) {
final out = <InlineSpan>[];
var at = 0;
for (final m in _cite.allMatches(text)) {
if (m.start > at) {
out.add(TextSpan(text: text.substring(at, m.start), style: style));
}
final n = int.parse(m.group(1)!);
final tap = TapGestureRecognizer()..onTap = () => widget.onCite?.call(n);
_recognizers.add(tap);
out.add(
TextSpan(
text: ' $n ',
recognizer: widget.onCite == null ? null : tap,
style: style.copyWith(
fontSize: (style.fontSize ?? 14) * 0.75,
fontWeight: FontWeight.w600,
color: theme.colorScheme.onSecondaryContainer,
backgroundColor: theme.colorScheme.secondaryContainer,
),
),
);
at = m.end;
}
if (at < text.length) {
out.add(TextSpan(text: text.substring(at), style: style));
}
return out;
}
}