import 'dart:async'; import 'package:flutter/material.dart'; import 'package:flutter/semantics.dart'; import 'chat_transcript_selection.dart'; import 'chat_code_hover.dart'; import '../../../../ui/text/monospace.dart'; import 'chat_link_launcher.dart'; import 'chat_link_spans.dart'; import 'chat_markdown.dart'; import 'chat_markdown_cache.dart'; import 'chat_message_bubble.dart'; /// Renders one assistant text part with native text widgets and the host's own /// theme roles. Links (`http`, `https`, `mailto` and `www.` hosts only) open /// through [onOpenLink] when given, else the [ChatLinkScope] launcher, which by /// default opens them outside the app. 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? onOpenLink; @override State 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? onOpenLink, }) => ChatMarkdownView(text: text, onOpenLink: onOpenLink); class _ChatMarkdownViewState extends State { late final ChatLinkSpans _links = ChatLinkSpans( onChanged: () => setState(() => _rendered = null), ); Widget? _rendered; final _codeHover = ChatCodeHover(); ScrollPosition? _scroll; ModalRoute? _route; @override void didUpdateWidget(ChatMarkdownView oldWidget) { super.didUpdateWidget(oldWidget); if (widget.text != oldWidget.text) { _rendered = null; _codeHover.hide(); } } @override void didChangeDependencies() { super.didChangeDependencies(); // Cached spans use host theme/localization roles. Never freeze those when // brightness, typography, locale or surrounding text styles change. _rendered = null; _codeHover.hide(); _route = ModalRoute.of(context); _scroll?.removeListener(_codeHover.hide); _scroll = Scrollable.maybeOf(context)?.position; _scroll?.addListener(_codeHover.hide); } @override void dispose() { _codeHover.dispose(); _scroll?.removeListener(_codeHover.hide); _links.dispose(); super.dispose(); } @override Widget build(BuildContext context) { // A new token or usage update elsewhere in the turn must not reparse and // rebuild every earlier answer part, or disturb its text selection. if (_rendered != null) return _rendered!; final gap = chatParagraphGap(context); final blocks = chatMarkdownCache.blocksFor(widget.text); return _rendered = Listener( onPointerDown: (_) => _codeHover.hide(), onPointerSignal: (_) => _codeHover.hide(), child: NotificationListener( onNotification: (_) { _codeHover.hide(); return false; }, child: _links.selectionArea( context, Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: [ for (var index = 0; index < blocks.length; index += 1) Padding( padding: EdgeInsets.only( top: index == 0 ? 0 : _gapAfter(blocks[index - 1], gap), ), child: _block(context, blocks[index]), ), ], ), ), ), ); } /// Blocks are separated by an empty line of body text, like paragraphs; /// a heading stays close to the content it introduces. double _gapAfter(MarkdownBlock previous, double paragraphGap) => previous is MarkdownHeading ? 8 : paragraphGap; Widget _block(BuildContext context, MarkdownBlock block) { switch (block) { case MarkdownHeading(level: final level, text: final text): return Semantics( container: true, headingLevel: level, child: _text(context, text, style: _headingStyle(context, level)), ); case MarkdownParagraph(text: final text): return _text(context, text); case MarkdownRule(): return Divider(color: _dividerColor(context)); case MarkdownQuote(lines: final lines): return DecoratedBox( decoration: BoxDecoration( border: BorderDirectional( start: BorderSide(color: _dividerColor(context)), ), ), 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), ], ), ), ); 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}.' : '•'), ), Expanded(child: _text(context, items[index])), ], ), ), ], ), ); case MarkdownTable(header: final header, rows: final rows): return ChatTranscriptHorizontalScrollView( label: 'table', child: Table( defaultColumnWidth: const IntrinsicColumnWidth(), border: TableBorder.all(color: _dividerColor(context)), children: [ TableRow( decoration: BoxDecoration(color: _headerFill(context)), children: [ for (final cell in header) _cell(context, cell, header: true), ], ), for (final row in rows) TableRow( children: [for (final cell in row) _cell(context, cell)], ), ], ), ); case MarkdownCode(language: final language, code: final code): final labelStyle = _roleStyle( context, Theme.of(context).textTheme.labelSmall, ); return ChatCodeCopyRegion( code: code, label: Text(markdownCodeLabel(language), style: labelStyle), child: DecoratedBox( decoration: BoxDecoration(color: _codeFill(context)), child: Padding( padding: const EdgeInsets.all(12), child: ChatTranscriptHorizontalScrollView( label: 'code block', child: Text( code, style: const TextStyle(fontFamily: appMonospaceFamily), ), ), ), ), ); } } Widget _cell(BuildContext context, String text, {bool header = false}) { final style = header ? _roleStyle(context, Theme.of(context).textTheme.labelLarge) : null; return Semantics( role: header ? SemanticsRole.columnHeader : null, child: Padding( padding: const EdgeInsets.all(8), child: _text(context, text, style: style), ), ); } Widget _text(BuildContext context, String text, {TextStyle? style}) { return Builder( builder: (textContext) => Text.rich( TextSpan(children: _spans(textContext, parseInline(text))), style: style, ), ); } List _spans(BuildContext context, List spans) => [ for (final span in spans) switch (span) { MarkdownPlain(text: final text) => TextSpan(text: text), MarkdownInlineCode(text: final text) => _inlineCode(context, text), MarkdownStrong(spans: final inner) => TextSpan( style: const TextStyle(fontWeight: FontWeight.bold), children: _spans(context, inner), ), MarkdownEmphasis(spans: final inner) => TextSpan( style: const TextStyle(fontStyle: FontStyle.italic), children: _spans(context, inner), ), MarkdownLink(url: final url, spans: final inner) => _link( context, url, inner, ), }, ]; TextSpan _inlineCode(BuildContext context, String text) { final token = text; return TextSpan( text: text, style: TextStyle( fontFamily: appMonospaceFamily, backgroundColor: _codeFill(context), ), onEnter: (event) { if (_route?.isCurrent != false) { _codeHover.show(context, token, text, event.position); } }, onExit: (_) => _codeHover.scheduleHide(token), ); } InlineSpan _link( BuildContext context, String url, List spans, ) => _links.link( context, url, _spans(context, spans), onOpen: (uri) { final onOpenLink = widget.onOpenLink; if (onOpenLink != null) return onOpenLink(uri.toString()); unawaited(openChatLink(context, uri)); }, ); /// 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. TextStyle? _headingStyle(BuildContext context, int level) { final text = Theme.of(context).textTheme; final 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. 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) { final theme = Theme.of(context); return theme.dividerTheme.color ?? theme.dividerColor; } Color _codeFill(BuildContext context) => Theme.of(context).colorScheme.surfaceContainerHighest; Color _headerFill(BuildContext context) => Theme.of(context).colorScheme.surfaceContainerHigh; }