Merge: clickable links in chat
This commit is contained in:
@@ -0,0 +1,14 @@
|
||||
import 'chat_link_browser_menu_stub.dart'
|
||||
if (dart.library.js_interop) 'chat_link_browser_menu_web.dart'
|
||||
as impl;
|
||||
|
||||
/// Whether a link's right-click opens the app's own "Copy link" menu: on the
|
||||
/// web the browser shows its own menu over text, so the link handles the
|
||||
/// secondary click itself. Elsewhere the selection menu carries "Copy link".
|
||||
const bool linkOwnsSecondaryClick = impl.linkOwnsSecondaryClick;
|
||||
|
||||
/// While [overLink] is true, the browser's own context menu is suppressed so a
|
||||
/// right-click on a link shows only the app's menu. This blocks the DOM event
|
||||
/// alone; it never toggles `BrowserContextMenu`, which would rebuild every
|
||||
/// selectable region (remounting its subtree and dropping its selection).
|
||||
void suppressBrowserMenuOverLink(bool overLink) => impl.suppress(overLink);
|
||||
@@ -0,0 +1,3 @@
|
||||
const bool linkOwnsSecondaryClick = false;
|
||||
|
||||
void suppress(bool overLink) {}
|
||||
@@ -0,0 +1,18 @@
|
||||
import 'dart:js_interop';
|
||||
|
||||
import 'package:web/web.dart' as web;
|
||||
|
||||
const bool linkOwnsSecondaryClick = true;
|
||||
|
||||
bool _overLink = false;
|
||||
JSFunction? _listener;
|
||||
|
||||
void suppress(bool overLink) {
|
||||
_overLink = overLink;
|
||||
if (_listener != null) return;
|
||||
final listener = ((web.Event event) {
|
||||
if (_overLink) event.preventDefault();
|
||||
}).toJS;
|
||||
_listener = listener;
|
||||
web.window.addEventListener('contextmenu', listener, true.toJS);
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import 'package:flutter/widgets.dart';
|
||||
import 'package:url_launcher/url_launcher.dart';
|
||||
|
||||
/// Opens one already-filtered link target; true when the platform accepted it.
|
||||
typedef ChatLinkLauncher = Future<bool> Function(Uri uri);
|
||||
|
||||
/// Opens [uri] outside the app: the system browser or mail client natively, a
|
||||
/// new tab on the web.
|
||||
Future<bool> launchChatLinkExternally(Uri uri) =>
|
||||
launchUrl(uri, mode: LaunchMode.externalApplication);
|
||||
|
||||
/// Supplies the launcher transcript links use; tests install a fake. Without a
|
||||
/// scope, links open with [launchChatLinkExternally].
|
||||
class ChatLinkScope extends InheritedWidget {
|
||||
const ChatLinkScope({
|
||||
super.key,
|
||||
required this.launcher,
|
||||
required super.child,
|
||||
});
|
||||
|
||||
final ChatLinkLauncher launcher;
|
||||
|
||||
static ChatLinkLauncher of(BuildContext context) =>
|
||||
context.getInheritedWidgetOfExactType<ChatLinkScope>()?.launcher ??
|
||||
launchChatLinkExternally;
|
||||
|
||||
@override
|
||||
bool updateShouldNotify(ChatLinkScope oldWidget) =>
|
||||
launcher != oldWidget.launcher;
|
||||
}
|
||||
|
||||
/// Launches [uri] with the scope's launcher, reporting a refusal or a failed
|
||||
/// platform call instead of letting it escape as an unhandled error.
|
||||
Future<void> openChatLink(BuildContext context, Uri uri) async {
|
||||
final launcher = ChatLinkScope.of(context);
|
||||
try {
|
||||
if (!await launcher(uri)) debugPrint('Link not opened: $uri');
|
||||
} on Object catch (error) {
|
||||
debugPrint('Link not opened: $uri ($error)');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/gestures.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
import '../../../../ui/adaptive/host.dart';
|
||||
import 'chat_link_browser_menu.dart';
|
||||
import 'chat_links.dart';
|
||||
|
||||
/// The link spans of one selectable text block, and the selection area that
|
||||
/// hosts them. A tap opens the link. A long press (or a native right-click)
|
||||
/// shows the selection menu with "Copy link" added; on the web, where the
|
||||
/// browser owns the right-click menu over text, a right-click on a link opens
|
||||
/// a "Copy link" menu instead. None of this consumes the text selection
|
||||
/// gestures, so links never break selecting a message.
|
||||
///
|
||||
/// The owner calls [dispose], and rebuilds its spans when [onChanged] fires
|
||||
/// (hover emphasis is a paint-only style change, which keeps a selection).
|
||||
class ChatLinkSpans {
|
||||
ChatLinkSpans({required this.onChanged});
|
||||
|
||||
/// Tests set this to exercise the web right-click path on the VM.
|
||||
@visibleForTesting
|
||||
static bool? debugOwnsSecondaryClick;
|
||||
|
||||
final VoidCallback onChanged;
|
||||
final Map<String, TapGestureRecognizer> _recognizers = {};
|
||||
final ContextMenuController _linkMenu = ContextMenuController();
|
||||
String? _hovered;
|
||||
String? _pressed;
|
||||
String? _menuLink;
|
||||
bool _disposed = false;
|
||||
|
||||
bool get _ownsSecondaryClick =>
|
||||
debugOwnsSecondaryClick ?? linkOwnsSecondaryClick;
|
||||
|
||||
/// [label] styled as a link to [target] and opened through [onOpen]. An
|
||||
/// unsafe target keeps its label as plain text.
|
||||
InlineSpan link(
|
||||
BuildContext context,
|
||||
String target,
|
||||
List<InlineSpan> label, {
|
||||
required ValueChanged<Uri> onOpen,
|
||||
}) {
|
||||
final uri = chatLinkUri(target);
|
||||
if (uri == null) return TextSpan(children: label);
|
||||
final url = uri.toString();
|
||||
final recognizer = _recognizers.putIfAbsent(url, TapGestureRecognizer.new)
|
||||
..onTapDown = (_) {
|
||||
_pressed = url;
|
||||
}
|
||||
..onTap = () {
|
||||
_pressed = null;
|
||||
onOpen(uri);
|
||||
}
|
||||
..onSecondaryTapUp = _ownsSecondaryClick
|
||||
? (details) => _showLinkMenu(context, details.globalPosition, url)
|
||||
: null;
|
||||
// The host's primary colour: a Material app's colour scheme primary, a
|
||||
// Cupertino app's tint.
|
||||
final color = CupertinoTheme.of(context).primaryColor;
|
||||
return _leaves(
|
||||
TextSpan(
|
||||
style: TextStyle(
|
||||
color: color,
|
||||
decoration: TextDecoration.underline,
|
||||
decorationColor: color,
|
||||
decorationThickness: _hovered == url ? 2.5 : 1,
|
||||
),
|
||||
children: label,
|
||||
),
|
||||
recognizer,
|
||||
url,
|
||||
);
|
||||
}
|
||||
|
||||
/// The native [SelectionArea] around [child], with "Copy link" in its menu
|
||||
/// when the press that opened the menu was on a link. 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 selectionArea(BuildContext context, Widget child) {
|
||||
final area = Listener(
|
||||
onPointerDown: (event) {
|
||||
_menuLink = event.buttons == kSecondaryMouseButton ? _hovered : null;
|
||||
_pressed = null;
|
||||
},
|
||||
child: SelectionArea(contextMenuBuilder: _selectionMenu, 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 _selectionMenu(BuildContext context, SelectableRegionState state) {
|
||||
// A touch long press opens the menu after the link's tap-down recorded it.
|
||||
final link = _menuLink ??= _pressed;
|
||||
return AdaptiveTextSelectionToolbar.buttonItems(
|
||||
anchors: state.contextMenuAnchors,
|
||||
buttonItems: [
|
||||
if (link != null) _copyItem(link, state.hideToolbar),
|
||||
...state.contextMenuButtonItems,
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
void _showLinkMenu(BuildContext context, Offset position, String url) {
|
||||
_linkMenu.show(
|
||||
context: context,
|
||||
contextMenuBuilder: (_) => TapRegion(
|
||||
onTapOutside: (_) => _linkMenu.remove(),
|
||||
child: AdaptiveTextSelectionToolbar.buttonItems(
|
||||
anchors: TextSelectionToolbarAnchors(primaryAnchor: position),
|
||||
buttonItems: [_copyItem(url, _linkMenu.remove)],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
ContextMenuButtonItem _copyItem(String url, VoidCallback done) =>
|
||||
ContextMenuButtonItem(
|
||||
label: 'Copy link',
|
||||
onPressed: () {
|
||||
Clipboard.setData(ClipboardData(text: url));
|
||||
done();
|
||||
},
|
||||
);
|
||||
|
||||
void dispose() {
|
||||
_disposed = true;
|
||||
if (_hovered != null) suppressBrowserMenuOverLink(false);
|
||||
_linkMenu.remove();
|
||||
for (final recognizer in _recognizers.values) {
|
||||
recognizer.dispose();
|
||||
}
|
||||
}
|
||||
|
||||
void _hover(String? url) {
|
||||
if (_disposed || _hovered == url) return;
|
||||
suppressBrowserMenuOverLink(url != null);
|
||||
_hovered = url;
|
||||
onChanged();
|
||||
}
|
||||
|
||||
/// A `TextSpan` only dispatches a recognizer or hover when it also owns
|
||||
/// text, so the link's handlers are copied onto its text leaves. The style
|
||||
/// stays on the shared parent.
|
||||
InlineSpan _leaves(
|
||||
InlineSpan span,
|
||||
TapGestureRecognizer recognizer,
|
||||
String url,
|
||||
) {
|
||||
if (span is! TextSpan) return span;
|
||||
final children = span.children;
|
||||
final leaf = span.text != null;
|
||||
return TextSpan(
|
||||
text: span.text,
|
||||
style: span.style,
|
||||
recognizer: leaf ? recognizer : null,
|
||||
mouseCursor: leaf ? SystemMouseCursors.click : null,
|
||||
onEnter: leaf ? (_) => _hover(url) : null,
|
||||
onExit: leaf ? (_) => _hover(null) : null,
|
||||
semanticsLabel: span.semanticsLabel,
|
||||
children: children == null
|
||||
? null
|
||||
: [for (final child in children) _leaves(child, recognizer, url)],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import 'chat_link_launcher.dart';
|
||||
import 'chat_link_spans.dart';
|
||||
import 'chat_links.dart';
|
||||
|
||||
/// Plain selectable text with its bare links made tappable: the operator's
|
||||
/// own message keeps every character exactly as typed (no markdown), and only
|
||||
/// `http(s)://`/`www.` runs outside `` `code` `` become links. Text without a
|
||||
/// link stays a plain [SelectableText].
|
||||
class ChatLinkText extends StatefulWidget {
|
||||
const ChatLinkText(this.text, {super.key});
|
||||
|
||||
final String text;
|
||||
|
||||
@override
|
||||
State<ChatLinkText> createState() => _ChatLinkTextState();
|
||||
}
|
||||
|
||||
class _ChatLinkTextState extends State<ChatLinkText> {
|
||||
late final ChatLinkSpans _links = ChatLinkSpans(
|
||||
onChanged: () => setState(() {}),
|
||||
);
|
||||
late List<ChatTextLink> _found = findTextLinks(widget.text);
|
||||
|
||||
@override
|
||||
void didUpdateWidget(ChatLinkText oldWidget) {
|
||||
super.didUpdateWidget(oldWidget);
|
||||
if (widget.text != oldWidget.text) _found = findTextLinks(widget.text);
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_links.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final text = widget.text;
|
||||
if (_found.isEmpty) return SelectableText(text);
|
||||
final spans = <InlineSpan>[];
|
||||
var at = 0;
|
||||
for (final link in _found) {
|
||||
if (link.start > at) {
|
||||
spans.add(TextSpan(text: text.substring(at, link.start)));
|
||||
}
|
||||
spans.add(
|
||||
_links.link(context, link.target, [
|
||||
TextSpan(text: text.substring(link.start, link.end)),
|
||||
], onOpen: (uri) => unawaited(openChatLink(context, uri))),
|
||||
);
|
||||
at = link.end;
|
||||
}
|
||||
if (at < text.length) spans.add(TextSpan(text: text.substring(at)));
|
||||
return _links.selectionArea(context, Text.rich(TextSpan(children: spans)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
/// Link detection for transcript text: bare URLs, `<autolinks>` and the
|
||||
/// scheme filter every activated target passes through. Pure string logic.
|
||||
library;
|
||||
|
||||
/// One bare link found in plain text: the visible range and its target.
|
||||
final class ChatTextLink {
|
||||
const ChatTextLink(this.start, this.end, this.target);
|
||||
final int start;
|
||||
final int end;
|
||||
final String target;
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) =>
|
||||
other is ChatTextLink &&
|
||||
other.start == start &&
|
||||
other.end == end &&
|
||||
other.target == target;
|
||||
|
||||
@override
|
||||
int get hashCode => Object.hash(start, end, target);
|
||||
|
||||
@override
|
||||
String toString() => 'ChatTextLink($start, $end, $target)';
|
||||
}
|
||||
|
||||
final RegExp _boundary = RegExp(r'[\p{L}\p{N}_@./\-]', unicode: true);
|
||||
final RegExp _whitespace = RegExp(r'\s');
|
||||
final RegExp _wwwHost = RegExp(
|
||||
r'^www\.[\p{L}\p{N}-]+\.[\p{L}\p{N}]',
|
||||
unicode: true,
|
||||
caseSensitive: false,
|
||||
);
|
||||
final RegExp _email = RegExp(r'^[^\s@<>()]+@[^\s@<>()]+\.[^\s@<>()]+$');
|
||||
final RegExp _autolinkScheme = RegExp(
|
||||
r'^(?:https?://|mailto:)[^\s<>]+$',
|
||||
caseSensitive: false,
|
||||
);
|
||||
|
||||
const _trailingPunctuation = '.,;:!?*_~\'"';
|
||||
const _closers = {')': '(', ']': '[', '}': '{'};
|
||||
|
||||
/// The activatable target for [url], or null. Only `http`/`https` with a host
|
||||
/// and `mailto` with an address pass; a `www.` host is opened over https. The
|
||||
/// transcript is untrusted model output, so `javascript:`, `data:`, `file:` and
|
||||
/// relative targets never activate.
|
||||
Uri? chatLinkUri(String url) {
|
||||
var value = url.trim();
|
||||
if (value.toLowerCase().startsWith('www.')) value = 'https://$value';
|
||||
final uri = Uri.tryParse(value);
|
||||
if (uri == null) return null;
|
||||
switch (uri.scheme.toLowerCase()) {
|
||||
case 'http' || 'https':
|
||||
return uri.host.isEmpty ? null : uri;
|
||||
case 'mailto':
|
||||
return uri.path.trim().isEmpty ? null : uri;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// A bare `http(s)://` or `www.` link starting exactly at [index], with
|
||||
/// trailing sentence punctuation and unbalanced closing brackets trimmed. A
|
||||
/// link never starts in the middle of a word, path or address.
|
||||
String? bareLinkAt(String text, int index) {
|
||||
if (index > 0 && _boundary.hasMatch(text[index - 1])) return null;
|
||||
final head = text
|
||||
.substring(index, (index + 8).clamp(0, text.length))
|
||||
.toLowerCase();
|
||||
final www = head.startsWith('www.');
|
||||
final prefix = head.startsWith('https://')
|
||||
? 8
|
||||
: head.startsWith('http://')
|
||||
? 7
|
||||
: www
|
||||
? 4
|
||||
: 0;
|
||||
if (prefix == 0) return null;
|
||||
var end = index;
|
||||
while (end < text.length &&
|
||||
!_whitespace.hasMatch(text[end]) &&
|
||||
!'<>"\'`'.contains(text[end])) {
|
||||
end += 1;
|
||||
}
|
||||
final url = trimLinkEnd(text.substring(index, end));
|
||||
if (url.length <= prefix) return null;
|
||||
if (www && !_wwwHost.hasMatch(url)) return null;
|
||||
return chatLinkUri(url) == null ? null : url;
|
||||
}
|
||||
|
||||
/// Drops trailing sentence punctuation, and a closing bracket only when the
|
||||
/// link does not open it too, so `(see https://x.com/a)` ends before `)` while
|
||||
/// `https://en.wikipedia.org/wiki/Dart_(language)` keeps it.
|
||||
String trimLinkEnd(String url) {
|
||||
var value = url;
|
||||
while (value.isNotEmpty) {
|
||||
final last = value[value.length - 1];
|
||||
final opener = _closers[last];
|
||||
if (_trailingPunctuation.contains(last)) {
|
||||
value = value.substring(0, value.length - 1);
|
||||
} else if (opener != null && _count(value, opener) < _count(value, last)) {
|
||||
value = value.substring(0, value.length - 1);
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
int _count(String text, String char) => char.allMatches(text).length;
|
||||
|
||||
/// The target of an `<autolink>` body: an `http(s)`/`mailto` URL or a bare
|
||||
/// email address. Anything else (HTML such as `<b>`) is not a link.
|
||||
String? autolinkTarget(String inner) {
|
||||
if (_autolinkScheme.hasMatch(inner)) {
|
||||
return chatLinkUri(inner) == null ? null : inner;
|
||||
}
|
||||
if (_email.hasMatch(inner)) return 'mailto:$inner';
|
||||
return null;
|
||||
}
|
||||
|
||||
/// Bare links in plain (non-markdown) text, outside `` `code` `` spans and
|
||||
/// ```` ``` ```` fences, so an operator's pasted command is never linkified.
|
||||
List<ChatTextLink> findTextLinks(String text) {
|
||||
final links = <ChatTextLink>[];
|
||||
var i = 0;
|
||||
while (i < text.length) {
|
||||
if (text.startsWith('```', i)) {
|
||||
final close = text.indexOf('```', i + 3);
|
||||
if (close < 0) break;
|
||||
i = close + 3;
|
||||
continue;
|
||||
}
|
||||
if (text[i] == '`') {
|
||||
final close = text.indexOf('`', i + 1);
|
||||
if (close > i) {
|
||||
i = close + 1;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
final url = bareLinkAt(text, i);
|
||||
if (url != null) {
|
||||
links.add(ChatTextLink(i, i + url.length, url));
|
||||
i += url.length;
|
||||
} else {
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
return links;
|
||||
}
|
||||
@@ -4,4 +4,5 @@ library;
|
||||
|
||||
export 'markdown_blocks.dart';
|
||||
export 'markdown_entities.dart';
|
||||
export 'chat_links.dart';
|
||||
export 'markdown_inline.dart';
|
||||
|
||||
@@ -1,18 +1,21 @@
|
||||
import 'dart:async';
|
||||
|
||||
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_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. Link activation is the caller's job: [onOpenLink] receives only
|
||||
/// an `http`/`https` target. No font family, size, colour or component
|
||||
/// 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 {
|
||||
@@ -34,14 +37,15 @@ Widget chatMarkdownText(
|
||||
}) => ChatMarkdownView(text: text, onOpenLink: onOpenLink);
|
||||
|
||||
class _ChatMarkdownViewState extends State<ChatMarkdownView> {
|
||||
final Map<String, TapGestureRecognizer> _links = {};
|
||||
late final ChatLinkSpans _links = ChatLinkSpans(
|
||||
onChanged: () => setState(() => _rendered = null),
|
||||
);
|
||||
Widget? _rendered;
|
||||
|
||||
@override
|
||||
void didUpdateWidget(ChatMarkdownView oldWidget) {
|
||||
super.didUpdateWidget(oldWidget);
|
||||
if (widget.text != oldWidget.text ||
|
||||
(widget.onOpenLink == null) != (oldWidget.onOpenLink == null)) {
|
||||
if (widget.text != oldWidget.text) {
|
||||
_rendered = null;
|
||||
}
|
||||
}
|
||||
@@ -56,9 +60,7 @@ class _ChatMarkdownViewState extends State<ChatMarkdownView> {
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
for (final recognizer in _links.values) {
|
||||
recognizer.dispose();
|
||||
}
|
||||
_links.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@@ -71,7 +73,7 @@ class _ChatMarkdownViewState extends State<ChatMarkdownView> {
|
||||
chatControlsStyleOf(context) == ChatControlsStyle.cupertino;
|
||||
final gap = chatParagraphGap(context);
|
||||
final blocks = chatMarkdownCache.blocksFor(widget.text);
|
||||
return _rendered = _selectable(
|
||||
return _rendered = _links.selectionArea(
|
||||
context,
|
||||
Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
@@ -94,23 +96,6 @@ class _ChatMarkdownViewState extends State<ChatMarkdownView> {
|
||||
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):
|
||||
@@ -303,38 +288,16 @@ class _ChatMarkdownViewState extends State<ChatMarkdownView> {
|
||||
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)],
|
||||
);
|
||||
}
|
||||
) => _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
|
||||
|
||||
@@ -9,6 +9,7 @@ import '../sessions/chat_adaptive.dart';
|
||||
import 'chat_attachment_gallery.dart';
|
||||
import '../../domain/chat_tool_calls.dart';
|
||||
import 'chat_copy_button.dart';
|
||||
import 'chat_link_text.dart';
|
||||
import 'chat_message_bubble.dart';
|
||||
import 'chat_turn_activity_view.dart';
|
||||
import 'native_disclosure.dart';
|
||||
@@ -150,7 +151,7 @@ class ChatMessageView extends StatelessWidget {
|
||||
.map((part) => '${part['text'] ?? ''}')
|
||||
.join('\n');
|
||||
final widgets = <Widget>[
|
||||
if (text.trim().isNotEmpty) SelectableText(text),
|
||||
if (text.trim().isNotEmpty) ChatLinkText(text),
|
||||
for (final part in parts.where(_isFile))
|
||||
if (!chatPartIsThumbnail(part)) _attachment(context, part),
|
||||
for (final part in parts)
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
/// Inline markdown spans for assistant prose (the web subset).
|
||||
library;
|
||||
|
||||
import 'chat_links.dart';
|
||||
|
||||
// ---- Inline -----------------------------------------------------------------
|
||||
|
||||
/// One inline markdown span.
|
||||
@@ -35,11 +37,11 @@ final class MarkdownLink extends MarkdownInline {
|
||||
}
|
||||
|
||||
final RegExp _wordChar = RegExp(r'[\p{L}\p{N}]', unicode: true);
|
||||
final RegExp _whitespace = RegExp(r'\s');
|
||||
|
||||
/// Parses inline markup into a flat span tree. Handles `` `code` ``,
|
||||
/// `**bold**` / `__bold__`, `*italic*` / `_italic_`, `[label](url)` and bare
|
||||
/// `http(s)://` autolinks; everything else stays plain text. Underscore
|
||||
/// `**bold**` / `__bold__`, `*italic*` / `_italic_`, `[label](url)`,
|
||||
/// `<https://…>` / `<mailto:…>` autolinks and bare `http(s)://` / `www.` links;
|
||||
/// everything else stays plain text. Underscore
|
||||
/// emphasis requires word boundaries so `snake_case` is never italicised.
|
||||
List<MarkdownInline> parseInline(String? text) {
|
||||
final source = text ?? '';
|
||||
@@ -87,27 +89,37 @@ List<MarkdownInline> parseInline(String? text) {
|
||||
}
|
||||
} else if (c == '[') {
|
||||
final close = source.indexOf(']', i + 1);
|
||||
if (close > i && close + 1 < source.length && source[close + 1] == '(') {
|
||||
final urlEnd = source.indexOf(')', close + 2);
|
||||
final url = urlEnd > close
|
||||
? source.substring(close + 2, urlEnd).trim()
|
||||
: '';
|
||||
if (url.isNotEmpty) {
|
||||
flush();
|
||||
spans.add(
|
||||
MarkdownLink(url, parseInline(source.substring(i + 1, close))),
|
||||
);
|
||||
i = urlEnd + 1;
|
||||
} else {
|
||||
buffer.write(c);
|
||||
i += 1;
|
||||
}
|
||||
final destination =
|
||||
close > i && close + 1 < source.length && source[close + 1] == '('
|
||||
? _destination(source, close + 2)
|
||||
: null;
|
||||
if (destination != null) {
|
||||
flush();
|
||||
spans.add(
|
||||
MarkdownLink(
|
||||
destination.url,
|
||||
parseInline(source.substring(i + 1, close)),
|
||||
),
|
||||
);
|
||||
i = destination.end;
|
||||
} else {
|
||||
buffer.write(c);
|
||||
i += 1;
|
||||
}
|
||||
} else if (c == '<') {
|
||||
final close = source.indexOf('>', i + 1);
|
||||
final inner = close > i ? source.substring(i + 1, close) : '';
|
||||
final target = inner.isEmpty ? null : autolinkTarget(inner);
|
||||
if (target != null) {
|
||||
flush();
|
||||
spans.add(MarkdownLink(target, [MarkdownPlain(inner)]));
|
||||
i = close + 1;
|
||||
} else {
|
||||
buffer.write(c);
|
||||
i += 1;
|
||||
}
|
||||
} else {
|
||||
final url = _autolinkAt(source, i);
|
||||
final url = bareLinkAt(source, i);
|
||||
if (url != null) {
|
||||
flush();
|
||||
spans.add(MarkdownLink(url, [MarkdownPlain(url)]));
|
||||
@@ -122,30 +134,30 @@ List<MarkdownInline> parseInline(String? text) {
|
||||
return spans;
|
||||
}
|
||||
|
||||
/// A bare `http(s)://` URL starting exactly at [index], with trailing
|
||||
/// punctuation trimmed.
|
||||
String? _autolinkAt(String text, int index) {
|
||||
if (!text.startsWith('http://', index) &&
|
||||
!text.startsWith('https://', index)) {
|
||||
return null;
|
||||
/// A `(destination)` starting at [start] (just after the `(`): parentheses
|
||||
/// inside it must balance, and an optional `"title"` after whitespace is
|
||||
/// dropped. Null when it is empty or never closes.
|
||||
({String url, int end})? _destination(String source, int start) {
|
||||
var depth = 0;
|
||||
for (var i = start; i < source.length; i += 1) {
|
||||
final c = source[i];
|
||||
if (c == '\n') return null;
|
||||
if (c == '(') depth += 1;
|
||||
if (c == ')') {
|
||||
if (depth == 0) {
|
||||
final url = source.substring(start, i).trim().split(' ').first;
|
||||
return url.isEmpty ? null : (url: url, end: i + 1);
|
||||
}
|
||||
depth -= 1;
|
||||
}
|
||||
}
|
||||
var end = index;
|
||||
while (end < text.length &&
|
||||
!_whitespace.hasMatch(text[end]) &&
|
||||
!'<>"\''.contains(text[end])) {
|
||||
end += 1;
|
||||
}
|
||||
var url = text.substring(index, end);
|
||||
while (url.isNotEmpty && '.,;:!?)]}'.contains(url[url.length - 1])) {
|
||||
url = url.substring(0, url.length - 1);
|
||||
}
|
||||
return url.length > 'https://'.length ? url : null;
|
||||
return null;
|
||||
}
|
||||
|
||||
/// Only `http`/`https` link targets may be activated; the transcript is
|
||||
/// untrusted model output, so `javascript:`/`data:` stay plain labels.
|
||||
bool isSafeMarkdownLink(String url) =>
|
||||
RegExp(r'^https?://', caseSensitive: false).hasMatch(url);
|
||||
/// Only `http`/`https`/`mailto` targets (and `www.` hosts) may be activated;
|
||||
/// the transcript is untrusted model output, so `javascript:`/`data:`/`file:`
|
||||
/// stay plain labels.
|
||||
bool isSafeMarkdownLink(String url) => chatLinkUri(url) != null;
|
||||
|
||||
/// The label a fenced code block shows: its language, or `code` when unnamed.
|
||||
String markdownCodeLabel(String language) {
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
# Clickable links in chat messages
|
||||
|
||||
- Detection (`lib/features/chat/ui/transcript/chat_links.dart`, pure): bare
|
||||
`http(s)://` and `www.` links with trailing punctuation and unbalanced closing
|
||||
brackets trimmed; `<https://…>`, `<mailto:…>` and `<user@host>` autolinks;
|
||||
markdown destinations keep balanced parentheses and drop a `"title"`.
|
||||
`chatLinkUri` is the only gate: `http`/`https` with a host, `mailto` with an
|
||||
address, `www.` opened over https. Everything else stays plain text.
|
||||
- Assistant markdown (`ChatMarkdownView`, also artifacts/run fields/stage
|
||||
definitions) opens links through `onOpenLink` when given, else the
|
||||
`ChatLinkScope` launcher (default: `url_launcher`, external application).
|
||||
- Operator messages (`ChatLinkText`) keep the exact typed characters; only bare
|
||||
links outside backtick code become links. Text without a link stays
|
||||
`SelectableText`.
|
||||
- Inline code and fenced code are never linkified.
|
||||
- Style: host primary colour (`CupertinoTheme.primaryColor`), underline; hover
|
||||
thickens the underline (paint-only, selection survives) with a click cursor.
|
||||
- Copy link: long press adds it to the selection toolbar. On native desktop the
|
||||
right-click selection toolbar carries it. On the web the browser owns the
|
||||
right-click menu over text, so a link handles its own secondary click and the
|
||||
DOM `contextmenu` event is suppressed only while the pointer is over a link.
|
||||
Do not toggle `BrowserContextMenu` for this: on web every `SelectableRegion`
|
||||
rebuilds without its platform menu wrapper, remounts its subtree, throws in
|
||||
`StaticSelectionContainerDelegate.hasSize` and drops the selection.
|
||||
|
||||
Browser capture: `?links=1` on the chat fixture (`tool/perf/chat_scroll_fixture.dart`).
|
||||
With the capture kit's semantics tree on, a CDP click lands on link semantics
|
||||
nodes whose rects are the bounding box of a wrapped link, so verify clicks with
|
||||
pointer events dispatched to `flutter-view`.
|
||||
|
||||
Observed, not caused by links: dragging a selection over text below a fenced
|
||||
code block in the same answer also highlights the code block.
|
||||
@@ -0,0 +1,331 @@
|
||||
import 'package:flutter/gestures.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/rendering.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:pipelines_app/features/chat/domain/chat_transcript.dart';
|
||||
import 'package:pipelines_app/features/chat/ui/transcript/chat_link_launcher.dart';
|
||||
import 'package:pipelines_app/features/chat/ui/transcript/chat_link_spans.dart';
|
||||
import 'package:pipelines_app/features/chat/ui/transcript/chat_link_text.dart';
|
||||
import 'package:pipelines_app/features/chat/ui/transcript/chat_markdown_view.dart';
|
||||
import 'package:pipelines_app/features/chat/ui/transcript/chat_message_view.dart';
|
||||
|
||||
import 'chat_markdown_test_support.dart';
|
||||
|
||||
const _reply = '''
|
||||
Read [the docs](https://example.com/docs) or <https://example.com/auto>.
|
||||
Bare https://example.com/bare. and www.example.org too.
|
||||
Never [this](javascript:alert(1)) or `https://example.com/inline`.
|
||||
```sh
|
||||
curl https://example.com/fenced
|
||||
```
|
||||
''';
|
||||
|
||||
Widget _host(Widget child, List<Uri> opened, {bool cupertino = false}) =>
|
||||
ChatLinkScope(
|
||||
launcher: (uri) async {
|
||||
opened.add(uri);
|
||||
return true;
|
||||
},
|
||||
child: markdownHost(child, cupertino: cupertino),
|
||||
);
|
||||
|
||||
TextSpan _leaf(WidgetTester tester, String text) =>
|
||||
spansOf(tester, text).firstWhere((span) => span.text == text);
|
||||
|
||||
Future<void> _tapText(WidgetTester tester, String text) async {
|
||||
final paragraph = tester
|
||||
.renderObjectList<RenderParagraph>(find.byType(RichText))
|
||||
.firstWhere((render) => render.text.toPlainText().contains(text));
|
||||
final start = paragraph.text.toPlainText().indexOf(text);
|
||||
final box = paragraph.getBoxesForSelection(
|
||||
TextSelection(baseOffset: start, extentOffset: start + 2),
|
||||
);
|
||||
final point = paragraph.localToGlobal(box.first.toRect().center);
|
||||
await tester.tapAt(point);
|
||||
await tester.pump();
|
||||
}
|
||||
|
||||
void main() {
|
||||
testWidgets('assistant links open through the launcher; code stays plain', (
|
||||
tester,
|
||||
) async {
|
||||
await phoneViewport(tester);
|
||||
final opened = <Uri>[];
|
||||
await tester.pumpWidget(
|
||||
_host(const ChatMarkdownView(text: _reply), opened),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
|
||||
final primary = Theme.of(
|
||||
tester.element(find.byType(ChatMarkdownView)),
|
||||
).colorScheme.primary;
|
||||
final docs = spansOf(tester, 'the docs').firstWhere(
|
||||
(span) => span.children != null && span.toPlainText() == 'the docs',
|
||||
);
|
||||
expect(docs.style?.color, primary);
|
||||
expect(docs.style?.decoration, TextDecoration.underline);
|
||||
expect(_leaf(tester, 'the docs').mouseCursor, SystemMouseCursors.click);
|
||||
|
||||
for (final text in [
|
||||
'the docs',
|
||||
'https://example.com/auto',
|
||||
'https://example.com/bare',
|
||||
'www.example.org',
|
||||
]) {
|
||||
expect(_leaf(tester, text).recognizer, isA<TapGestureRecognizer>());
|
||||
}
|
||||
expect(_leaf(tester, 'this').recognizer, isNull);
|
||||
expect(_leaf(tester, 'https://example.com/inline').recognizer, isNull);
|
||||
expect(
|
||||
find.byWidgetPredicate(
|
||||
(widget) =>
|
||||
widget is Text &&
|
||||
widget.data == 'curl https://example.com/fenced' &&
|
||||
widget.textSpan == null,
|
||||
),
|
||||
findsOneWidget,
|
||||
);
|
||||
|
||||
await _tapText(tester, 'the docs');
|
||||
await _tapText(tester, 'www.example.org');
|
||||
await _tapText(tester, 'https://example.com/inline');
|
||||
await _tapText(tester, 'this');
|
||||
expect(opened.map((uri) => '$uri'), [
|
||||
'https://example.com/docs',
|
||||
'https://www.example.org',
|
||||
]);
|
||||
});
|
||||
|
||||
testWidgets(
|
||||
'hovering a link thickens its underline; a click opens it',
|
||||
(tester) async {
|
||||
await phoneViewport(tester);
|
||||
final semantics = tester.ensureSemantics();
|
||||
final opened = <Uri>[];
|
||||
await tester.pumpWidget(
|
||||
_host(
|
||||
const ChatMarkdownView(text: 'go [here](https://x.com) now'),
|
||||
opened,
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
double? thickness() => spansOf(tester, 'here')
|
||||
.firstWhere(
|
||||
(span) => span.children != null && span.toPlainText() == 'here',
|
||||
)
|
||||
.style
|
||||
?.decorationThickness;
|
||||
expect(thickness(), 1);
|
||||
|
||||
final paragraph = tester.renderObject<RenderParagraph>(
|
||||
find.byType(RichText).first,
|
||||
);
|
||||
final box = paragraph.getBoxesForSelection(
|
||||
const TextSelection(baseOffset: 4, extentOffset: 6),
|
||||
);
|
||||
final mouse = await tester.createGesture(kind: PointerDeviceKind.mouse);
|
||||
addTearDown(mouse.removePointer);
|
||||
await mouse.addPointer(location: Offset.zero);
|
||||
await mouse.moveTo(paragraph.localToGlobal(box.first.toRect().center));
|
||||
await tester.pump();
|
||||
expect(thickness(), 2.5);
|
||||
await mouse.down(paragraph.localToGlobal(box.first.toRect().center));
|
||||
await tester.pump();
|
||||
await mouse.up();
|
||||
await tester.pump();
|
||||
expect(opened.map((uri) => '$uri'), ['https://x.com']);
|
||||
await mouse.moveTo(Offset.zero);
|
||||
await tester.pump();
|
||||
expect(thickness(), 1);
|
||||
expect(tester.takeException(), isNull);
|
||||
semantics.dispose();
|
||||
},
|
||||
variant: TargetPlatformVariant.all(),
|
||||
);
|
||||
|
||||
testWidgets('a long press on a link offers Copy link and opens nothing', (
|
||||
tester,
|
||||
) async {
|
||||
await phoneViewport(tester);
|
||||
final opened = <Uri>[];
|
||||
String? copied;
|
||||
tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
|
||||
SystemChannels.platform,
|
||||
(call) async {
|
||||
if (call.method == 'Clipboard.setData') {
|
||||
copied = (call.arguments as Map)['text'] as String?;
|
||||
}
|
||||
return null;
|
||||
},
|
||||
);
|
||||
addTearDown(
|
||||
() => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
|
||||
SystemChannels.platform,
|
||||
null,
|
||||
),
|
||||
);
|
||||
await tester.pumpWidget(
|
||||
_host(
|
||||
const ChatMarkdownView(text: 'go [here](https://x.com/a) now'),
|
||||
opened,
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
final paragraph = tester.renderObject<RenderParagraph>(
|
||||
find.byType(RichText).first,
|
||||
);
|
||||
final box = paragraph.getBoxesForSelection(
|
||||
const TextSelection(baseOffset: 4, extentOffset: 6),
|
||||
);
|
||||
await tester.longPressAt(
|
||||
paragraph.localToGlobal(box.first.toRect().center),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
expect(opened, isEmpty);
|
||||
expect(find.text('Copy link'), findsOneWidget);
|
||||
await tester.tap(find.text('Copy link'));
|
||||
await tester.pumpAndSettle();
|
||||
expect(copied, 'https://x.com/a');
|
||||
expect(find.text('Copy link'), findsNothing);
|
||||
expect(opened, isEmpty);
|
||||
});
|
||||
|
||||
for (final web in [false, true]) {
|
||||
testWidgets(
|
||||
'a right-click on a link offers Copy link (web: $web)',
|
||||
(tester) async {
|
||||
ChatLinkSpans.debugOwnsSecondaryClick = web;
|
||||
addTearDown(() => ChatLinkSpans.debugOwnsSecondaryClick = null);
|
||||
await phoneViewport(tester);
|
||||
final copied = <String?>[];
|
||||
tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
|
||||
SystemChannels.platform,
|
||||
(call) async {
|
||||
if (call.method == 'Clipboard.setData') {
|
||||
copied.add((call.arguments as Map)['text'] as String?);
|
||||
}
|
||||
return null;
|
||||
},
|
||||
);
|
||||
addTearDown(
|
||||
() => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
|
||||
SystemChannels.platform,
|
||||
null,
|
||||
),
|
||||
);
|
||||
final opened = <Uri>[];
|
||||
await tester.pumpWidget(
|
||||
_host(
|
||||
const ChatMarkdownView(text: 'go [here](https://x.com/r) now'),
|
||||
opened,
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
final paragraph = tester.renderObject<RenderParagraph>(
|
||||
find.byType(RichText).first,
|
||||
);
|
||||
final box = paragraph.getBoxesForSelection(
|
||||
const TextSelection(baseOffset: 4, extentOffset: 6),
|
||||
);
|
||||
final at = paragraph.localToGlobal(box.first.toRect().center);
|
||||
final mouse = await tester.createGesture(
|
||||
kind: PointerDeviceKind.mouse,
|
||||
buttons: kSecondaryMouseButton,
|
||||
);
|
||||
await mouse.addPointer(location: at);
|
||||
await tester.pump();
|
||||
await mouse.down(at);
|
||||
await tester.pump();
|
||||
await mouse.up();
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('Copy link'), findsOneWidget);
|
||||
await tester.tap(find.text('Copy link'));
|
||||
await tester.pumpAndSettle();
|
||||
expect(copied, ['https://x.com/r']);
|
||||
expect(find.text('Copy link'), findsNothing);
|
||||
expect(opened, isEmpty);
|
||||
await mouse.removePointer();
|
||||
},
|
||||
variant: TargetPlatformVariant.only(TargetPlatform.macOS),
|
||||
);
|
||||
}
|
||||
|
||||
testWidgets('a long press on plain text offers no Copy link', (tester) async {
|
||||
await phoneViewport(tester);
|
||||
await tester.pumpWidget(
|
||||
_host(
|
||||
const ChatMarkdownView(text: 'plain words [here](https://x.com)'),
|
||||
[],
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
final paragraph = tester.renderObject<RenderParagraph>(
|
||||
find.byType(RichText).first,
|
||||
);
|
||||
final box = paragraph.getBoxesForSelection(
|
||||
const TextSelection(baseOffset: 0, extentOffset: 3),
|
||||
);
|
||||
await tester.longPressAt(
|
||||
paragraph.localToGlobal(box.first.toRect().center),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text('Copy'), findsOneWidget);
|
||||
expect(find.text('Copy link'), findsNothing);
|
||||
});
|
||||
|
||||
testWidgets('the operator message keeps its text and links bare URLs', (
|
||||
tester,
|
||||
) async {
|
||||
await phoneViewport(tester);
|
||||
final opened = <Uri>[];
|
||||
const typed =
|
||||
'Check [x](https://example.com/md) and `https://code.com`, '
|
||||
'then https://example.com/bare.';
|
||||
final row = transcriptRows([
|
||||
{
|
||||
'id': 'u1',
|
||||
'role': 'user',
|
||||
'parts': [
|
||||
{'type': 'text', 'text': typed},
|
||||
],
|
||||
},
|
||||
]).single;
|
||||
for (final cupertino in [false, true]) {
|
||||
opened.clear();
|
||||
await tester.pumpWidget(
|
||||
_host(ChatMessageView(row: row), opened, cupertino: cupertino),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
expect(tester.takeException(), isNull);
|
||||
expect(find.byType(ChatLinkText), findsOneWidget);
|
||||
expect(allText(tester), contains(typed));
|
||||
expect(
|
||||
_leaf(tester, 'https://example.com/md').recognizer,
|
||||
isA<TapGestureRecognizer>(),
|
||||
);
|
||||
expect(_leaf(tester, 'https://example.com/bare').recognizer, isNotNull);
|
||||
expect(
|
||||
spansOf(tester, 'https://code.com')
|
||||
.where((span) => span.text?.contains('https://code.com') ?? false)
|
||||
.single
|
||||
.recognizer,
|
||||
isNull,
|
||||
);
|
||||
await _tapText(tester, 'https://example.com/bare');
|
||||
expect(opened.map((uri) => '$uri'), ['https://example.com/bare']);
|
||||
}
|
||||
});
|
||||
|
||||
testWidgets('an operator message without a link stays SelectableText', (
|
||||
tester,
|
||||
) async {
|
||||
await phoneViewport(tester);
|
||||
await tester.pumpWidget(
|
||||
_host(const ChatLinkText('no links, just example.com text'), []),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.byType(SelectableText), findsOneWidget);
|
||||
expect(find.byType(SelectionArea), findsNothing);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:pipelines_app/features/chat/ui/transcript/chat_markdown.dart';
|
||||
|
||||
List<String> _targets(String text) => [
|
||||
for (final link in findTextLinks(text)) link.target,
|
||||
];
|
||||
|
||||
void main() {
|
||||
group('bare URL detection', () {
|
||||
test('finds http, https and www. links in prose', () {
|
||||
expect(
|
||||
_targets('a http://x.com/a b https://y.org/b?q=1#h c www.z.net/c'),
|
||||
['http://x.com/a', 'https://y.org/b?q=1#h', 'www.z.net/c'],
|
||||
);
|
||||
});
|
||||
|
||||
test('trims trailing sentence punctuation', () {
|
||||
for (final suffix in ['.', ',', ';', ':', '!', '?', '...', '."', "'"]) {
|
||||
expect(_targets('see https://x.com/a$suffix'), [
|
||||
'https://x.com/a',
|
||||
], reason: suffix);
|
||||
}
|
||||
});
|
||||
|
||||
test('trims an unbalanced closing bracket but keeps a balanced one', () {
|
||||
expect(_targets('(see https://x.com/a)'), ['https://x.com/a']);
|
||||
expect(_targets('[https://x.com/a]'), ['https://x.com/a']);
|
||||
expect(_targets('https://en.wikipedia.org/wiki/Dart_(language).'), [
|
||||
'https://en.wikipedia.org/wiki/Dart_(language)',
|
||||
]);
|
||||
expect(_targets('(https://x.com/Foo_(bar))'), [
|
||||
'https://x.com/Foo_(bar)',
|
||||
]);
|
||||
});
|
||||
|
||||
test('reports exact ranges', () {
|
||||
const text = 'go to www.example.com.';
|
||||
expect(findTextLinks(text), [
|
||||
const ChatTextLink(6, 21, 'www.example.com'),
|
||||
]);
|
||||
});
|
||||
|
||||
test('never starts inside a word, path or address', () {
|
||||
expect(_targets('xhttps://x.com'), isEmpty);
|
||||
expect(_targets('mail@www.example.com'), isEmpty);
|
||||
expect(_targets('a/www.example.com'), isEmpty);
|
||||
expect(_targets('node.www.example.com'), isEmpty);
|
||||
});
|
||||
|
||||
test('rejects a scheme or www. without a host', () {
|
||||
expect(_targets('https:// and http://'), isEmpty);
|
||||
expect(_targets('www. and www.example'), isEmpty);
|
||||
});
|
||||
|
||||
test('skips inline code and fenced code', () {
|
||||
expect(_targets('run `curl https://x.com/a` then https://y.com/b'), [
|
||||
'https://y.com/b',
|
||||
]);
|
||||
expect(_targets('```\ncurl https://x.com/a\n```\nhttps://y.com/b'), [
|
||||
'https://y.com/b',
|
||||
]);
|
||||
expect(_targets('```\nunclosed https://x.com'), isEmpty);
|
||||
});
|
||||
|
||||
test('a markdown link in plain text links its target in place', () {
|
||||
const text = '[docs](https://x.com/d)';
|
||||
expect(findTextLinks(text), [
|
||||
const ChatTextLink(7, 22, 'https://x.com/d'),
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
group('scheme filter', () {
|
||||
test('allows http, https, mailto and www. hosts', () {
|
||||
expect(chatLinkUri('https://x.com')?.toString(), 'https://x.com');
|
||||
expect(chatLinkUri('HTTP://x.com')?.host, 'x.com');
|
||||
expect(chatLinkUri('mailto:a@b.com')?.scheme, 'mailto');
|
||||
expect(chatLinkUri('www.x.com/a')?.toString(), 'https://www.x.com/a');
|
||||
});
|
||||
|
||||
test('neutralises every other scheme or a missing host', () {
|
||||
for (final unsafe in [
|
||||
'javascript:alert(1)',
|
||||
'JavaScript:alert(1)',
|
||||
'data:text/html,<h1>x</h1>',
|
||||
'file:///etc/passwd',
|
||||
'ftp://x.com',
|
||||
'vbscript:msgbox',
|
||||
'mailto:',
|
||||
'https://',
|
||||
'//x.com',
|
||||
'/artifacts/a.txt',
|
||||
'x.com',
|
||||
]) {
|
||||
expect(chatLinkUri(unsafe), isNull, reason: unsafe);
|
||||
expect(isSafeMarkdownLink(unsafe), isFalse, reason: unsafe);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
group('markdown inline links', () {
|
||||
List<MarkdownLink> links(String text) =>
|
||||
parseInline(text).whereType<MarkdownLink>().toList();
|
||||
|
||||
test('angle-bracket autolinks show their body without brackets', () {
|
||||
final found = links('<https://x.com/a> and <me@x.com> and <b>');
|
||||
expect(found.map((link) => link.url), [
|
||||
'https://x.com/a',
|
||||
'mailto:me@x.com',
|
||||
]);
|
||||
expect(
|
||||
(found.first.spans.single as MarkdownPlain).text,
|
||||
'https://x.com/a',
|
||||
);
|
||||
});
|
||||
|
||||
test(
|
||||
'a markdown destination keeps balanced parentheses and drops a title',
|
||||
() {
|
||||
expect(
|
||||
links(
|
||||
'[w](https://x.org/Dart_(language)) and [t](https://x.com "T")',
|
||||
).map((link) => link.url),
|
||||
['https://x.org/Dart_(language)', 'https://x.com'],
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
test('bare www. and trimmed URLs become links outside inline code', () {
|
||||
final spans = parseInline(
|
||||
'see www.x.com, `https://code.com` (https://y.com).',
|
||||
);
|
||||
expect(spans.whereType<MarkdownLink>().map((link) => link.url), [
|
||||
'www.x.com',
|
||||
'https://y.com',
|
||||
]);
|
||||
expect(
|
||||
spans.whereType<MarkdownInlineCode>().single.text,
|
||||
'https://code.com',
|
||||
);
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/gestures.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:pipelines_app/features/chat/ui/transcript/chat_link_launcher.dart';
|
||||
import 'package:pipelines_app/features/chat/ui/transcript/chat_markdown_view.dart';
|
||||
|
||||
void main() {
|
||||
@@ -107,19 +108,26 @@ void main() {
|
||||
});
|
||||
|
||||
testWidgets(
|
||||
'an unchanged link invokes the latest callback and becomes inert when disabled',
|
||||
'an unchanged link invokes the latest callback, else the scope launcher',
|
||||
(tester) async {
|
||||
final version = ValueNotifier<int>(0);
|
||||
addTearDown(version.dispose);
|
||||
final opened = <int>[];
|
||||
final launched = <Uri>[];
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(
|
||||
home: Scaffold(
|
||||
body: ValueListenableBuilder<int>(
|
||||
valueListenable: version,
|
||||
builder: (_, value, _) => ChatMarkdownView(
|
||||
text: '[Link](https://example.test)',
|
||||
onOpenLink: value == 2 ? null : (_) => opened.add(value),
|
||||
ChatLinkScope(
|
||||
launcher: (uri) async {
|
||||
launched.add(uri);
|
||||
return true;
|
||||
},
|
||||
child: MaterialApp(
|
||||
home: Scaffold(
|
||||
body: ValueListenableBuilder<int>(
|
||||
valueListenable: version,
|
||||
builder: (_, value, _) => ChatMarkdownView(
|
||||
text: '[Link](https://example.test)',
|
||||
onOpenLink: value == 2 ? null : (_) => opened.add(value),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
@@ -143,9 +151,13 @@ void main() {
|
||||
await tester.pump();
|
||||
link()!.onTap!();
|
||||
expect(opened, [0, 1]);
|
||||
expect(launched, isEmpty);
|
||||
version.value = 2;
|
||||
await tester.pump();
|
||||
expect(link(), isNull);
|
||||
link()!.onTap!();
|
||||
await tester.pump();
|
||||
expect(opened, [0, 1]);
|
||||
expect(launched, [Uri.parse('https://example.test')]);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
@@ -11,7 +11,9 @@
|
||||
// `?live=N` 3 s after a chat subscribes, N text deltas stream into a
|
||||
// new reply, one every 60 ms;
|
||||
// `?tasks=N` the history ends with N consecutive background-task notices
|
||||
// in the server's wording (every third one failed).
|
||||
// in the server's wording (every third one failed);
|
||||
// `?links=1` answers and operator turns carry a markdown link, an
|
||||
// autolink, a bare URL and URLs inside code (never linkified).
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:pipelines_app/core/api_gateway.dart';
|
||||
@@ -21,6 +23,7 @@ Map<String, String> _params = const {};
|
||||
void configureChatScrollFixture(Map<String, String> params) => _params = params;
|
||||
|
||||
bool get _rich => _params['rich'] == '1';
|
||||
bool get _links => _params['links'] == '1';
|
||||
bool get _older => _params['older'] == '1';
|
||||
int get _live => int.tryParse(_params['live'] ?? '') ?? 0;
|
||||
int get _tasks => int.tryParse(_params['tasks'] ?? '') ?? 0;
|
||||
@@ -72,9 +75,19 @@ String _answer(int i) {
|
||||
: '';
|
||||
return '## Answer $i\n\nSome **bold** text with `code`.\n\n'
|
||||
'```dart\n${List.generate(8, (l) => 'final v$l = $i * $l;').join('\n')}'
|
||||
'\n```\n$wide\n- one\n- two\n';
|
||||
'\n```\n$wide\n- one\n- two\n${_links ? _answerLinks : ''}';
|
||||
}
|
||||
|
||||
const _answerLinks =
|
||||
'\nRead [the release notes](https://example.com/releases/v2) or '
|
||||
'<https://example.com/auto>; the bare https://example.com/bare/path. '
|
||||
'and www.example.org work too. Not `https://example.com/inline`:\n\n'
|
||||
'```sh\ncurl https://example.com/fenced\n```\n';
|
||||
|
||||
const _questionLinks =
|
||||
' See https://example.com/question?id=1, [md](https://example.com/md) '
|
||||
'and `https://example.com/code`.';
|
||||
|
||||
JsonMap _message(String chat, int i) {
|
||||
final id = '$chat-m$i';
|
||||
if (_rich && i % 10 == 5) {
|
||||
@@ -114,7 +127,7 @@ JsonMap _message(String chat, int i) {
|
||||
'name': 'shot$i.png',
|
||||
'uri': _png,
|
||||
},
|
||||
{'type': 'text', 'text': 'Question $i'},
|
||||
{'type': 'text', 'text': 'Question $i${_links ? _questionLinks : ''}'},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user