Chat: highlighted, clickable links in messages
Markdown links, autolinks and bare http(s)/www. URLs open externally through url_launcher (http, https and mailto only) in assistant markdown and operator messages; code is never linkified. Links use the host primary colour with an underline that thickens on hover, and offer Copy link on long press and right-click without breaking text selection.
This commit is contained in:
@@ -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)));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user