feat(app): render native transcript markdown

Port the web markdown subset to a pure Dart parser and a native
Material/Cupertino block renderer, with a caller seam for assistant text
parts and safe http(s) link activation.

- parser: entities, paragraphs, H1-H6, fenced code, quotes, lists, tables,
  rules, inline code/emphasis/links; entity overflow stays literal
- renderer: host text roles, inline/fenced code fills, table header fill,
  heading level and list/columnHeader semantics, horizontal code/table
  scrolling, native selection
- tests cover parser safety, both hosts, the seam and real taps
- probe plus note record the web evidence and remaining limits
This commit is contained in:
2026-10-21 23:34:33 +01:00
parent 6a0f1c345e
commit a5afc55a9d
9 changed files with 2133 additions and 0 deletions
@@ -0,0 +1,353 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/semantics.dart';
import '../../../../ui/adaptive/host.dart';
import '../sessions/chat_adaptive.dart';
import 'chat_markdown.dart';
/// Renders one assistant text part with native text widgets and the host's own
/// theme roles. Link activation is the caller's job: [onOpenLink] receives only
/// an `http`/`https` target. No font family, size, colour or component
/// dimension is overridden; code keeps its exact whitespace and scrolls
/// sideways instead of widening the transcript.
class ChatMarkdownView extends StatefulWidget {
const ChatMarkdownView({super.key, required this.text, this.onOpenLink});
final String text;
final ValueChanged<String>? onOpenLink;
@override
State<ChatMarkdownView> createState() => _ChatMarkdownViewState();
}
/// The transcript's `ChatMessageTextBuilder` seam: a caller that already has the
/// markdown renderer can pass this function as `textBuilder`.
Widget chatMarkdownText(
BuildContext context,
String text, {
ValueChanged<String>? onOpenLink,
}) => ChatMarkdownView(text: text, onOpenLink: onOpenLink);
class _ChatMarkdownViewState extends State<ChatMarkdownView> {
final Map<String, TapGestureRecognizer> _links = {};
@override
void dispose() {
for (final recognizer in _links.values) {
recognizer.dispose();
}
super.dispose();
}
@override
Widget build(BuildContext context) {
final cupertino =
chatControlsStyleOf(context) == ChatControlsStyle.cupertino;
return _selectable(
context,
Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
spacing: 8,
children: [
for (final block in parseMarkdown(widget.text))
_block(context, block, cupertino),
],
),
);
}
/// Selection is provided by the native [SelectionArea]. A Cupertino-only app
/// has no `MaterialLocalizations`, which `SelectionArea` asserts on, so one
/// English default localization scope is added there for its context menu.
Widget _selectable(BuildContext context, Widget child) {
final area = SelectionArea(child: child);
if (!usesCupertinoHost(context)) return area;
return Localizations(
locale: Localizations.maybeLocaleOf(context) ?? const Locale('en'),
delegates: const [
DefaultWidgetsLocalizations.delegate,
DefaultMaterialLocalizations.delegate,
DefaultCupertinoLocalizations.delegate,
],
child: area,
);
}
Widget _block(BuildContext context, MarkdownBlock block, bool cupertino) {
switch (block) {
case MarkdownHeading(level: final level, text: final text):
return Semantics(
container: true,
headingLevel: level,
child: _text(
context,
text,
cupertino: cupertino,
style: _headingStyle(context, level, cupertino),
),
);
case MarkdownParagraph(text: final text):
return _text(context, text, cupertino: cupertino);
case MarkdownRule():
return Divider(color: _dividerColor(context, cupertino));
case MarkdownQuote(lines: final lines):
return DecoratedBox(
decoration: BoxDecoration(
border: BorderDirectional(
start: BorderSide(color: _dividerColor(context, cupertino)),
),
),
child: Padding(
padding: const EdgeInsetsDirectional.only(start: 12),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
spacing: 4,
children: [
for (final line in lines)
if (line.trim().isNotEmpty)
_text(context, line, cupertino: cupertino),
],
),
),
);
case MarkdownList(ordered: final ordered, items: final items):
return Semantics(
container: true,
explicitChildNodes: true,
role: SemanticsRole.list,
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
spacing: 4,
children: [
for (var index = 0; index < items.length; index += 1)
Semantics(
container: true,
role: SemanticsRole.listItem,
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsetsDirectional.only(end: 8),
child: Text(ordered ? '${index + 1}.' : '\u2022'),
),
Expanded(
child: _text(
context,
items[index],
cupertino: cupertino,
),
),
],
),
),
],
),
);
case MarkdownTable(header: final header, rows: final rows):
return SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Table(
defaultColumnWidth: const IntrinsicColumnWidth(),
border: TableBorder.all(color: _dividerColor(context, cupertino)),
children: [
TableRow(
decoration: BoxDecoration(
color: _headerFill(context, cupertino),
),
children: [
for (final cell in header)
_cell(context, cell, cupertino, header: true),
],
),
for (final row in rows)
TableRow(
children: [
for (final cell in row) _cell(context, cell, cupertino),
],
),
],
),
);
case MarkdownCode(language: final language, code: final code):
final labelStyle = _roleStyle(
context,
cupertino
? CupertinoTheme.of(context).textTheme.textStyle
: Theme.of(context).textTheme.labelSmall,
);
return Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
spacing: 4,
children: [
Text(markdownCodeLabel(language), style: labelStyle),
DecoratedBox(
decoration: BoxDecoration(color: _codeFill(context, cupertino)),
child: Padding(
padding: const EdgeInsets.all(12),
child: SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Text(code),
),
),
),
],
);
}
}
Widget _cell(
BuildContext context,
String text,
bool cupertino, {
bool header = false,
}) {
final style = header
? _roleStyle(
context,
cupertino
? CupertinoTheme.of(context).textTheme.navTitleTextStyle
: Theme.of(context).textTheme.labelLarge,
)
: null;
return Semantics(
role: header ? SemanticsRole.columnHeader : null,
child: Padding(
padding: const EdgeInsets.all(8),
child: _text(context, text, cupertino: cupertino, style: style),
),
);
}
Widget _text(
BuildContext context,
String text, {
required bool cupertino,
TextStyle? style,
}) {
return Text.rich(
TextSpan(children: _spans(context, parseInline(text), cupertino)),
style: style,
);
}
List<InlineSpan> _spans(
BuildContext context,
List<MarkdownInline> spans,
bool cupertino,
) => [
for (final span in spans)
switch (span) {
MarkdownPlain(text: final text) => TextSpan(text: text),
MarkdownInlineCode(text: final text) => TextSpan(
text: text,
// The same host-theme surface as a fenced block marks the run as
// code without a font, size or literal colour override.
style: TextStyle(backgroundColor: _codeFill(context, cupertino)),
),
MarkdownStrong(spans: final inner) => TextSpan(
style: const TextStyle(fontWeight: FontWeight.bold),
children: _spans(context, inner, cupertino),
),
MarkdownEmphasis(spans: final inner) => TextSpan(
style: const TextStyle(fontStyle: FontStyle.italic),
children: _spans(context, inner, cupertino),
),
MarkdownLink(url: final url, spans: final inner) => _link(
context,
url,
inner,
cupertino,
),
},
];
InlineSpan _link(
BuildContext context,
String url,
List<MarkdownInline> spans,
bool cupertino,
) {
final children = _spans(context, spans, cupertino);
final onOpenLink = widget.onOpenLink;
if (!isSafeMarkdownLink(url) || onOpenLink == null) {
return TextSpan(children: children);
}
final recognizer = _links.putIfAbsent(url, TapGestureRecognizer.new);
recognizer.onTap = () => onOpenLink(url);
return _withRecognizer(
TextSpan(
style: const TextStyle(decoration: TextDecoration.underline),
children: children,
),
recognizer,
);
}
/// A `TextSpan` only dispatches a recognizer when it also owns text, not when
/// it only owns children, so a link's recognizer is copied onto its text
/// leaves. The underline stays on the shared parent.
InlineSpan _withRecognizer(InlineSpan span, TapGestureRecognizer recognizer) {
if (span is! TextSpan) return span;
final children = span.children;
return TextSpan(
text: span.text,
style: span.style,
recognizer: span.text == null ? span.recognizer : recognizer,
children: children == null
? null
: [for (final child in children) _withRecognizer(child, recognizer)],
);
}
/// Heading roles are a non-increasing sequence from the host's own text
/// theme. H3–H6 share one title role, matching the web renderer's flat
/// lower-heading treatment, and no level falls back to a body role, so a
/// heading never reads like a paragraph. Cupertino has two title roles, so
/// H2–H6 share the middle-title role rather than plain body text.
TextStyle? _headingStyle(BuildContext context, int level, bool cupertino) {
final TextStyle? role;
if (cupertino) {
final theme = CupertinoTheme.of(context).textTheme;
role = switch (level) {
1 => theme.navLargeTitleTextStyle,
_ => theme.navTitleTextStyle,
};
} else {
final text = Theme.of(context).textTheme;
role = switch (level) {
1 => text.headlineSmall,
2 => text.titleLarge,
_ => text.titleMedium,
};
}
return _roleStyle(context, role);
}
/// Merges a host theme role into the ambient text style. Cupertino roles are
/// `inherit: false`, which `Text` cannot merge directly.
TextStyle? _roleStyle(BuildContext context, TextStyle? role) => role == null
? null
: DefaultTextStyle.of(
context,
).style.copyWith(inherit: true).merge(role.copyWith(inherit: true));
Color _dividerColor(BuildContext context, bool cupertino) {
if (cupertino) return CupertinoColors.separator.resolveFrom(context);
final theme = Theme.of(context);
return theme.dividerTheme.color ?? theme.dividerColor;
}
Color _codeFill(BuildContext context, bool cupertino) => cupertino
? CupertinoColors.tertiarySystemFill.resolveFrom(context)
: Theme.of(context).colorScheme.surfaceContainerHighest;
Color _headerFill(BuildContext context, bool cupertino) => cupertino
? CupertinoColors.tertiarySystemFill.resolveFrom(context)
: Theme.of(context).colorScheme.surfaceContainerHigh;
}