357 lines
12 KiB
Dart
357 lines
12 KiB
Dart
import 'dart:async';
|
||
|
||
import 'package:flutter/cupertino.dart';
|
||
import 'package:flutter/material.dart';
|
||
import 'package:flutter/semantics.dart';
|
||
|
||
import 'chat_transcript_selection.dart';
|
||
import '../../../../ui/text/monospace.dart';
|
||
import '../sessions/chat_adaptive.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<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> {
|
||
late final ChatLinkSpans _links = ChatLinkSpans(
|
||
onChanged: () => setState(() => _rendered = null),
|
||
);
|
||
Widget? _rendered;
|
||
|
||
@override
|
||
void didUpdateWidget(ChatMarkdownView oldWidget) {
|
||
super.didUpdateWidget(oldWidget);
|
||
if (widget.text != oldWidget.text) {
|
||
_rendered = null;
|
||
}
|
||
}
|
||
|
||
@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;
|
||
}
|
||
|
||
@override
|
||
void dispose() {
|
||
_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 cupertino =
|
||
chatControlsStyleOf(context) == ChatControlsStyle.cupertino;
|
||
final gap = chatParagraphGap(context);
|
||
final blocks = chatMarkdownCache.blocksFor(widget.text);
|
||
return _rendered = _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], cupertino),
|
||
),
|
||
],
|
||
),
|
||
);
|
||
}
|
||
|
||
/// 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, 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 ChatTranscriptHorizontalScrollView(
|
||
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: ChatTranscriptHorizontalScrollView(
|
||
child: Text(
|
||
code,
|
||
style: const TextStyle(fontFamily: appMonospaceFamily),
|
||
),
|
||
),
|
||
),
|
||
),
|
||
],
|
||
);
|
||
}
|
||
}
|
||
|
||
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 and monospace family as a fenced
|
||
// block mark the run as code; the size stays the surrounding text's.
|
||
style: TextStyle(
|
||
fontFamily: appMonospaceFamily,
|
||
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,
|
||
) => _links.link(
|
||
context,
|
||
url,
|
||
_spans(context, spans, cupertino),
|
||
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. 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;
|
||
}
|