Add hover copy actions for fenced and inline chat code

This commit is contained in:
2026-11-07 02:52:29 +00:00
parent 9e6d55942f
commit 4340c3e72f
6 changed files with 549 additions and 45 deletions
@@ -0,0 +1,206 @@
import 'dart:async';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'chat_copy_button.dart';
/// Keeps inline code as a TextSpan: only its hover control lives in an overlay.
/// No recognizers or embedded widgets intercept text selection or wrapping.
class ChatCodeHover {
OverlayEntry? _entry;
Timer? _exit;
Object? _active;
bool _disposed = false;
void show(
BuildContext context,
Object token,
String text,
Offset pointer, {
required bool cupertino,
}) {
if (_disposed) return;
hide();
final overlay = Overlay.maybeOf(context, rootOverlay: true);
final box = overlay?.context.findRenderObject();
if (overlay == null || box is! RenderBox) return;
_active = token;
Rect anchor = Rect.fromCenter(center: pointer, width: 1, height: 48);
RenderParagraph? paragraph;
void findParagraph(RenderObject object) {
if (object is RenderParagraph) {
paragraph = object;
return;
}
object.visitChildren(findParagraph);
}
final render = context.findRenderObject();
if (render != null) findParagraph(render);
final textRender = paragraph;
if (textRender != null) {
final position = textRender.getPositionForOffset(
textRender.globalToLocal(pointer),
);
final boxes = textRender.getBoxesForSelection(
TextSelection(
baseOffset: position.offset,
extentOffset: position.offset + 1,
),
);
if (boxes.isNotEmpty) {
anchor = boxes.first.toRect().shift(
textRender.localToGlobal(Offset.zero),
);
}
}
final localAnchor = anchor.shift(-box.localToGlobal(Offset.zero));
_entry = OverlayEntry(
builder: (context) => Positioned.fill(
child: CustomSingleChildLayout(
delegate: _CopyPosition(localAnchor),
child: MouseRegion(
onEnter: (_) => _exit?.cancel(),
onExit: (_) => scheduleHide(token),
child: cupertino
? DecoratedBox(
decoration: BoxDecoration(
color: CupertinoColors.secondarySystemBackground
.resolveFrom(context),
borderRadius: BorderRadius.circular(8),
border: Border.all(
color: CupertinoColors.separator.resolveFrom(context),
),
),
child: ChatCopyButton(
text: text,
cupertino: true,
showLabel: true,
),
)
: Material(
elevation: 3,
borderRadius: BorderRadius.circular(8),
child: ChatCopyButton(
text: text,
cupertino: false,
showLabel: true,
),
),
),
),
),
);
overlay.insert(_entry!);
}
/// A short grace period lets the mouse cross from text to its Copy control.
void scheduleHide(Object token) {
if (_active != token) return;
_exit?.cancel();
_exit = Timer(const Duration(milliseconds: 180), hide);
}
void hide() {
_exit?.cancel();
_exit = null;
_entry?.remove();
_entry?.dispose();
_entry = null;
_active = null;
}
void dispose() {
_disposed = true;
hide();
}
}
class _CopyPosition extends SingleChildLayoutDelegate {
_CopyPosition(this.anchor);
final Rect anchor;
@override
BoxConstraints getConstraintsForChild(BoxConstraints constraints) =>
constraints.loosen();
@override
Offset getPositionForChild(Size size, Size childSize) {
final above = anchor.top - childSize.height - 6;
final y = above >= 4 ? above : anchor.bottom + 6;
return Offset(
anchor.left.clamp(
4.0,
(size.width - childSize.width - 4).clamp(4.0, double.infinity),
),
y.clamp(
4.0,
(size.height - childSize.height - 4).clamp(4.0, double.infinity),
),
);
}
@override
bool shouldRelayout(_CopyPosition oldDelegate) =>
anchor != oldDelegate.anchor;
}
/// The copy slot always occupies the same space, so hover never shifts code.
/// Keyboard focus also reveals it; a touch on the code still selects normally.
class ChatCodeCopyRegion extends StatefulWidget {
const ChatCodeCopyRegion({
super.key,
required this.code,
required this.cupertino,
required this.label,
required this.child,
});
final String code;
final bool cupertino;
final Widget label, child;
@override
State<ChatCodeCopyRegion> createState() => _ChatCodeCopyRegionState();
}
class _ChatCodeCopyRegionState extends State<ChatCodeCopyRegion> {
bool _hover = false, _focus = false;
@override
Widget build(BuildContext context) {
final visible = _hover || _focus;
return MouseRegion(
onEnter: (_) => setState(() => _hover = true),
onExit: (_) => setState(() => _hover = false),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
mainAxisSize: MainAxisSize.min,
children: [
Row(
children: [
Expanded(child: widget.label),
Focus(
skipTraversal: true,
onFocusChange: (value) => setState(() => _focus = value),
child: ExcludeSemantics(
excluding: !visible,
child: IgnorePointer(
ignoring: !visible,
child: Opacity(
opacity: visible ? 1 : 0,
child: SelectionContainer.disabled(
child: ChatCopyButton(
text: widget.code,
cupertino: widget.cupertino,
showLabel: true,
),
),
),
),
),
),
],
),
const SizedBox(height: 4),
widget.child,
],
),
);
}
}
@@ -17,10 +17,12 @@ class ChatCopyButton extends StatefulWidget {
super.key,
required this.text,
required this.cupertino,
this.showLabel = false,
});
final String text;
final bool cupertino;
final bool showLabel;
@override
State<ChatCopyButton> createState() => _ChatCopyButtonState();
@@ -30,6 +32,15 @@ class _ChatCopyButtonState extends State<ChatCopyButton> {
bool _copied = false;
Timer? _reset;
@override
void didUpdateWidget(ChatCopyButton oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.text != widget.text) {
_reset?.cancel();
_copied = false;
}
}
@override
void dispose() {
_reset?.cancel();
@@ -37,8 +48,9 @@ class _ChatCopyButtonState extends State<ChatCopyButton> {
}
Future<void> _copy() async {
await Clipboard.setData(ClipboardData(text: widget.text));
if (!mounted) return;
final text = widget.text;
await Clipboard.setData(ClipboardData(text: text));
if (!mounted || widget.text != text) return;
setState(() => _copied = true);
_reset?.cancel();
_reset = Timer(const Duration(seconds: 2), () {
@@ -49,6 +61,27 @@ class _ChatCopyButtonState extends State<ChatCopyButton> {
@override
Widget build(BuildContext context) {
final label = _copied ? chatCopiedLabel : chatCopyLabel;
if (widget.showLabel) {
final icon = Icon(
_copied
? (widget.cupertino ? CupertinoIcons.checkmark : Icons.check)
: (widget.cupertino
? CupertinoIcons.doc_on_doc
: Icons.copy_outlined),
);
return Semantics(
identifier: 'chat-code-copy',
child: widget.cupertino
? CupertinoButton(
onPressed: _copy,
child: Row(
mainAxisSize: MainAxisSize.min,
children: [icon, const SizedBox(width: 6), Text(label)],
),
)
: TextButton.icon(onPressed: _copy, icon: icon, label: Text(label)),
);
}
if (widget.cupertino) {
return Semantics(
button: true,
@@ -191,8 +191,18 @@ class ChatLinkSpans {
style: span.style,
recognizer: leaf ? recognizer : null,
mouseCursor: leaf ? SystemMouseCursors.click : null,
onEnter: leaf ? (_) => _hover(url) : null,
onExit: leaf ? (_) => _hover(null) : null,
onEnter: leaf
? (event) {
span.onEnter?.call(event);
_hover(url);
}
: null,
onExit: leaf
? (event) {
span.onExit?.call(event);
_hover(null);
}
: null,
semanticsLabel: span.semanticsLabel,
children: children == null
? null
@@ -5,6 +5,7 @@ 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 '../sessions/chat_adaptive.dart';
import 'chat_link_launcher.dart';
@@ -42,12 +43,16 @@ class _ChatMarkdownViewState extends State<ChatMarkdownView> {
onChanged: () => setState(() => _rendered = null),
);
Widget? _rendered;
final _codeHover = ChatCodeHover();
ScrollPosition? _scroll;
ModalRoute<dynamic>? _route;
@override
void didUpdateWidget(ChatMarkdownView oldWidget) {
super.didUpdateWidget(oldWidget);
if (widget.text != oldWidget.text) {
_rendered = null;
_codeHover.hide();
}
}
@@ -57,10 +62,17 @@ class _ChatMarkdownViewState extends State<ChatMarkdownView> {
// 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();
}
@@ -74,20 +86,30 @@ class _ChatMarkdownViewState extends State<ChatMarkdownView> {
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),
),
],
return _rendered = Listener(
onPointerDown: (_) => _codeHover.hide(),
onPointerSignal: (_) => _codeHover.hide(),
child: NotificationListener<ScrollNotification>(
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], cupertino),
),
],
),
),
),
);
}
@@ -200,25 +222,22 @@ class _ChatMarkdownViewState extends State<ChatMarkdownView> {
? 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),
),
return ChatCodeCopyRegion(
code: code,
cupertino: cupertino,
label: Text(markdownCodeLabel(language), style: labelStyle),
child: DecoratedBox(
decoration: BoxDecoration(color: _codeFill(context, cupertino)),
child: Padding(
padding: const EdgeInsets.all(12),
child: ChatTranscriptHorizontalScrollView(
child: Text(
code,
style: const TextStyle(fontFamily: appMonospaceFamily),
),
),
),
],
),
);
}
}
@@ -252,9 +271,11 @@ class _ChatMarkdownViewState extends State<ChatMarkdownView> {
required bool cupertino,
TextStyle? style,
}) {
return Text.rich(
TextSpan(children: _spans(context, parseInline(text), cupertino)),
style: style,
return Builder(
builder: (textContext) => Text.rich(
TextSpan(children: _spans(textContext, parseInline(text), cupertino)),
style: style,
),
);
}
@@ -266,14 +287,10 @@ class _ChatMarkdownViewState extends State<ChatMarkdownView> {
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),
),
MarkdownInlineCode(text: final text) => _inlineCode(
context,
text,
cupertino,
),
MarkdownStrong(spans: final inner) => TextSpan(
style: const TextStyle(fontWeight: FontWeight.bold),
@@ -292,6 +309,29 @@ class _ChatMarkdownViewState extends State<ChatMarkdownView> {
},
];
TextSpan _inlineCode(BuildContext context, String text, bool cupertino) {
final token = text;
return TextSpan(
text: text,
style: TextStyle(
fontFamily: appMonospaceFamily,
backgroundColor: _codeFill(context, cupertino),
),
onEnter: (event) {
if (_route?.isCurrent != false) {
_codeHover.show(
context,
token,
text,
event.position,
cupertino: cupertino,
);
}
},
onExit: (_) => _codeHover.scheduleHide(token),
);
}
InlineSpan _link(
BuildContext context,
String url,