Files
pipelines/app/lib/features/chat/ui/transcript/chat_markdown_view.dart
T
alan d02d5ea11d Chat transcript: wheel and trackpad scrolling always reaches the transcript
Root causes found in release web captures (1280x800 and 560x900):
- Follow mode undid small wheel/trackpad ticks at the end: each tick is its
  own scroll, re-judged as following within 32 px and jumped back. A user
  scroll toward older rows now releases the end however small; the jump
  control appears once streamed content moves the end beyond the threshold.
- The end-of-scroll jump ran inside the position's activity switch, so a
  touch or scrollbar drag released near the end recursed without end (stack
  overflow during the gesture). The jump now runs after the notification.
- Horizontally scrolling code blocks and tables claimed diagonal trackpad
  gestures whole. HorizontalScrollView gives mostly vertical gestures to the
  enclosing list; sideways and Shift + wheel still scroll the block.
- The wheel over the floating chat bar, composer and jump control moved
  nothing. VerticalWheelForwarder scrolls the transcript from them unless
  something under the pointer claims the event.

Adds widget tests per content kind and scroll mode, follow/touch/Load older
tests, a capture-kit check (tool/capture/examples/chat-wheel-scroll.json)
with eval/expect steps, wheel dx/repeat, --params and eval: targets, a
transcript scroll probe and fixture options, and fixes the kit ignoring a
script's size. Notes in notes/chat-wheel-scroll.md.
2026-11-02 20:37:36 +00:00

385 lines
13 KiB
Dart
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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 '../../../../ui/layout/wheel_scroll_forwarding.dart';
import '../sessions/chat_adaptive.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. 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 = {};
Widget? _rendered;
@override
void didUpdateWidget(ChatMarkdownView oldWidget) {
super.didUpdateWidget(oldWidget);
if (widget.text != oldWidget.text ||
(widget.onOpenLink == null) != (oldWidget.onOpenLink == null)) {
_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() {
for (final recognizer in _links.values) {
recognizer.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 = _selectable(
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;
/// 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 HorizontalScrollView(
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: HorizontalScrollView(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 = () => widget.onOpenLink?.call(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;
}