mirror of
https://github.com/block/buzz.git
synced 2026-11-25 02:31:36 +00:00
## Summary The mobile composer's @mention typing was an older port of the mention rules that [block/buzz-app](https://github.com/block/buzz-app) follows (`src/bundled/mentions/README.md` there), and it trailed buzz-app in nine places. Most of them came from one difference: mobile tied a picked person to the `@Label` text and looked for that text again at send time, while buzz-app keeps the recipient on an atomic chip. Several of the gaps meant a picked person was silently not notified. This PR fixes all nine. Every change is in `mobile/`; no relay, CLI or desktop code is touched, and the event payloads mobile writes keep the same shape. ### Commits | Commit | Fixes | What it changes | |---|---|---| |9152e91fe| 1, 2 | Picked people are atomic chips, as agents already were. The recipient comes from the chips, so a pick after `(`, `[` or `{` notifies. Backspace removes the trailing space, then the whole chip; arrows step over a chip. | |2cbdabdae| 3, 4 | A chip is bound to its recipient by its position in the draft and keeps it through punctuation, apostrophes, hyphens and slashes. Namesake chips read `@Sam · a1b2`, and the draft text never holds a public key. | |c4d3f2072| 5 | A chip's `@` never opens a query, so prose typed after a pick sends no directory searches. A query that found nobody refutes every longer query that continues it. | |4e4ac3efd| 6 | Name matching folds accents, full-width letters and ligatures, and breaks words on hyphens and apostrophes. The vendored contract fixture moves from version 1 to version 4, and all 125 cases pass. | |38e8f2e1e| 7 | Closing punctuation (`. , ! ? ; :`, `)`, `]`, `}` and closing quotes) selects an exact, unique name as Space does, and the character stays after the chip. | |e008151c6| 8 | The chooser is shown only while the text field has focus. The query and its rows are kept while hidden, so refocusing shows the same rows without a new search. | |199606969| 9 | The edit sheet mounts the composer's chooser through a shared hook. A pick inserts a chip, and the saved edit adds no `p` tag. | |a1e4d69fa| 3 | The message renderer ends a mention where the composer does, so a sent `@Honey's report` draws Honey's pill with the suffix as text. | |bf34af139| 2 | iOS reports one Backspace as two editing updates (select the character, then delete the selection). The controller recognises that pair and removes the whole chip and its binding. | ### How to read the videos Each video has three columns that follow the same numbered steps with the same people and the same typed text: mobile before this PR on the left, mobile on this branch in the middle, and buzz-app on the right. The bar across the top names the current step, and a column that finishes a step early holds its frame until the others catch up. The dark panel on each phone is a readout added for the recording. Its `p tags (notified)` line shows who a sent message would notify, and `directory searches sent` counts requests to the directory. The readout under the buzz-app composer shows the same facts. ### 1. A mention picked after a bracket keeps its recipient `see (@Honey) please` went out with nobody notified, because the send-time scan did not accept the brackets the chooser did. The recipient now comes from the chip, and the typed-name fallback accepts `(`, `[` and `{` too. https://github.com/user-attachments/assets/b1f1c76b-b991-4f90-9079-a435c4475c2b ### 2. People mentions are atomic chips A second Backspace used to leave plain `@Hone` (and `@Scou` for the agent), which sent with no recipient. Now the first Backspace removes the trailing space and the second removes the whole chip, and the arrow keys step over a chip as one unit. https://github.com/user-attachments/assets/a198656c-d735-46a7-a954-9e0aa4af7dc3 ### 3. A suffix after a mention keeps the recipient `@Honey's report` and `@Honey-bot is back` notified nobody. A chip now survives an apostrophe (straight or curly), a hyphen, a slash or punctuation typed against it, and the sent bubble draws the pill with the suffix as text. Only a letter, mark, digit or underscore typed against the chip unbinds it. https://github.com/user-attachments/assets/c481110d-1633-4c01-9810-a8d750ce2ae2 ### 4. No raw public key in the composer Picking two people with the same name filled the draft with two 64-character keys. Each pick is now a chip with a short label, the draft text stays `@Honey`, and each namesake gets their own `p` tag. The key suffixes on the labels differ between the apps only because each recording generated its own keys. https://github.com/user-attachments/assets/4f56cddd-a96f-43cb-820b-511eb965a77b ### 5. No directory search while typing prose Every character of a sentence typed after a pick was sent to the directory as a name search: 20 searches in this clip. The count now stays at 1, the same as buzz-app. A short query with no local match still searches, so a person outside the channel is still found. https://github.com/user-attachments/assets/3575b2cf-e3a6-42f1-9779-6e1401f00dfc ### 6. Accent folding and contract fixture version 4 `@jose` could not find José María, so `@jose maria` went out as plain text. Names now fold accents, the row stays listed, and the pick is a chip that notifies José María. The vendored fixture is version 4 of the shared contract, copied unchanged, with no case skipped. https://github.com/user-attachments/assets/362f6b4b-a09c-4f69-910e-8903408be77e ### 7. Closing punctuation selects an exact name A comma typed straight after `@Honey` or `@Outside Person` joined the query and closed the chooser; for a person outside the channel the message went out with no recipient and no prompt. The comma now selects the exact name, and Send shows the outside-channel prompt, where Invite adds the person and sends with their `p` tag. https://github.com/user-attachments/assets/b43a0663-489f-4ae3-ae36-7a2a92443f9e ### 8. The chooser follows the field's focus Dragging the keyboard away collapsed the composer but left the chooser row floating above it. The chooser now hides when the field loses focus and returns with the same rows when focus comes back. Step 1 of the mobile columns is sped up three times, because the on-screen keyboard is slow to drive in the simulator. https://github.com/user-attachments/assets/2ce0093d-03d0-4792-9b05-fb28980830fc ### 9. The chooser works in the edit sheet The edit sheet was a plain text field with no chooser. It now uses the composer's chooser with the same rules, and existing mentions open as chips. The saved edit adds no `p` tag, matching buzz-app's rule that an edit notifies nobody. https://github.com/user-attachments/assets/e54d5620-ae2d-49b5-8cce-99536b8d81db ### Known gaps left for follow-up - **Typed, unpicked names.** Mobile still notifies a typed name that equals exactly one member and refuses to send an ambiguous one. buzz-app does not do either, and the shared contract has not settled which is right. - **Directory-only names selected before the search finishes.** Space or closing punctuation selects a directory-only name as soon as it is in the ranked rows. buzz-app waits until that query's search has finished. This predates the PR for Space and now also applies to punctuation. - **Undo does not restore a chip.** After a letter typed against a chip unbinds it, Undo restores the text but not the chip. iOS shake-to-undo also bypasses the new undo detection. - **Edits drop existing tags.** The timeline reads mention tags from the edit event, so editing a message that already tagged someone still loses that pill. Carrying the original tags through an edit is a separate change. - **`_@Name_` italics.** `_` now counts as a name character, as in buzz-app, so `_@Honey_` no longer draws a pill. ### Related issue N/A. None found; #9008 made the relay's name search accent-insensitive, and fix 6 does the same for matching on the device. ### Testing - `dart format`, `flutter analyze`, `just file-size-check` and the full mobile `flutter test` suite passed on every commit. Two timing-sensitive tests unrelated to mentions (relay socket liveness, community snapshot cleanup) each failed once under full-suite load and passed solo. - Each fix has a widget-test journey through the real composer, chooser and send path, and each was shown to fail with its fix removed. The shared contract fixture runs in full. - The videos are harness recordings on an iPhone 17 simulator (iOS 27.2): the real channel page, composer, chooser, edit sheet and send path on an in-memory relay, not the app against a live community. The buzz-app column is a headless WebKit recording of buzz-app's fixture pages. - Android and physical devices were not exercised. - The branch was pushed with `--no-verify`, so the pre-push lanes did not run locally. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: Matt Toohey <contact@matttoohey.com> Signed-off-by: Tom Brow <tomb@block.xyz> Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com> Co-authored-by: Tom Brow <tomb@block.xyz> Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@buzz.block.builderlab.xyz>
1204 lines
42 KiB
Dart
1204 lines
42 KiB
Dart
import 'message_reply_drag_target.dart';
|
|
|
|
import 'package:buzz/shared/widgets/feedback_snackbar.dart';
|
|
|
|
import 'dart:async';
|
|
import 'dart:convert';
|
|
|
|
import '../../shared/widgets/ios_media_carousel.dart';
|
|
import '../../shared/widgets/message_attachment_corners.dart';
|
|
|
|
import 'dart:io';
|
|
import 'dart:math' as math;
|
|
|
|
import 'package:flutter/gestures.dart';
|
|
import 'package:flutter/material.dart';
|
|
import 'package:flutter/foundation.dart';
|
|
import 'package:flutter/services.dart';
|
|
import 'package:flutter/rendering.dart';
|
|
import 'package:flutter_hooks/flutter_hooks.dart';
|
|
import 'package:hooks_riverpod/hooks_riverpod.dart';
|
|
import 'package:gpt_markdown/gpt_markdown.dart';
|
|
import 'package:buzz/shared/theme/buzz_icons.dart';
|
|
import 'package:open_filex/open_filex.dart';
|
|
import 'package:path_provider/path_provider.dart';
|
|
import 'package:share_plus/share_plus.dart';
|
|
import 'package:url_launcher/url_launcher.dart';
|
|
|
|
import '../../shared/clipboard_utils.dart';
|
|
import '../../shared/widgets/media_loading_placeholder.dart';
|
|
import '../../shared/widgets/modal_presentation.dart';
|
|
import '../../shared/widgets/sheet_action_section.dart';
|
|
import '../../shared/mentions/mention_bindings.dart';
|
|
import '../../shared/mentions/mention_tags.dart';
|
|
import '../../shared/deeplink/deep_link.dart';
|
|
import '../../shared/deeplink/pending_deep_link_provider.dart';
|
|
import '../../shared/relay/relay.dart';
|
|
import '../../shared/syntax_highlight.dart';
|
|
import '../../shared/theme/theme.dart';
|
|
import '../../shared/custom_emoji/custom_emoji.dart';
|
|
import '../../shared/custom_emoji/custom_emoji_provider.dart';
|
|
import '../../shared/custom_emoji/custom_emoji_render.dart';
|
|
import '../../shared/emoji/emoji_data_provider.dart';
|
|
import '../../shared/emoji/emoji_only.dart';
|
|
import 'channel_ids_by_name_provider.dart';
|
|
import 'local_send_bubble_surface.dart';
|
|
import 'media_viewer_page.dart';
|
|
import 'native_photo_zoom_preview.dart';
|
|
import 'native_video_files.dart';
|
|
import 'message_content/link_normalizer.dart';
|
|
import 'message_content/markdown_escapes.dart';
|
|
import 'message_content/markdown_tables.dart';
|
|
import 'message_content/preview_text.dart';
|
|
import 'message_media.dart';
|
|
import 'message_content/bubble_segments.dart';
|
|
import 'message_content/edited_marker.dart';
|
|
import 'message_content/buzz_link_label.dart';
|
|
import 'message_content/channel_token_pattern.dart';
|
|
import 'message_mention_pill.dart';
|
|
import 'message_gallery.dart';
|
|
import 'message_gallery_frame.dart';
|
|
import 'message_long_press_region.dart';
|
|
import 'message_media_avatar.dart';
|
|
import 'message_media_geometry.dart';
|
|
import 'voice_note_attachment.dart';
|
|
|
|
part 'message_content/media_carousel.dart';
|
|
part 'message_content/mention_markdown.dart';
|
|
part 'message_content/media_stack.dart';
|
|
part 'message_content/media_stack_tuning.dart';
|
|
part 'message_content/message_preview.dart';
|
|
part 'message_content/bubble_shape.dart';
|
|
part 'message_content/inline_components.dart';
|
|
part 'message_content/token_pill.dart';
|
|
part 'message_content/video_preview.dart';
|
|
part 'message_content/link_actions.dart';
|
|
|
|
typedef OpenDownloadedFile =
|
|
Future<void> Function(
|
|
String url,
|
|
Map<String, String> headers,
|
|
String filename,
|
|
);
|
|
|
|
final openDownloadedFileProvider = Provider<OpenDownloadedFile>((ref) {
|
|
final client = ref.watch(mediaHttpClientProvider);
|
|
return (url, headers, filename) async {
|
|
final response = await client.get(Uri.parse(url), headers: headers);
|
|
if (response.statusCode < 200 || response.statusCode >= 300) {
|
|
throw HttpException(
|
|
'Attachment download failed (${response.statusCode})',
|
|
uri: Uri.parse(url),
|
|
);
|
|
}
|
|
|
|
final directory = await getTemporaryDirectory();
|
|
final safeName = _safeDownloadedFilename(filename);
|
|
final file = File(
|
|
'${directory.path}${Platform.pathSeparator}'
|
|
'${DateTime.now().microsecondsSinceEpoch}-$safeName',
|
|
);
|
|
await file.writeAsBytes(response.bodyBytes, flush: true);
|
|
final result = await OpenFilex.open(file.path);
|
|
if (result.type != ResultType.done) {
|
|
throw FileSystemException(result.message, file.path);
|
|
}
|
|
};
|
|
});
|
|
|
|
String _safeDownloadedFilename(String filename) {
|
|
final safe = filename
|
|
.split(RegExp(r'[/\\]'))
|
|
.last
|
|
.replaceAll(RegExp(r'[\x00-\x1F\x7F]'), '')
|
|
.trim();
|
|
return safe.isEmpty ? 'attachment' : safe;
|
|
}
|
|
|
|
/// Renders message content with markdown formatting, @mentions, #channel links,
|
|
/// and media-aware markdown images/videos.
|
|
class MessageContent extends HookConsumerWidget {
|
|
final String content;
|
|
|
|
/// Paint conversation text bubbles while keeping attachments on the page.
|
|
final bool bubble;
|
|
|
|
/// Space reclaimed from an omitted sender avatar and its gutter.
|
|
final double additionalTextWidth;
|
|
|
|
/// Distinguishes messages authored by the signed-in identity.
|
|
final bool ownMessage;
|
|
|
|
/// Lets an adjacent day divider own spacing after the final text segment.
|
|
final bool trimTrailingSpacing;
|
|
|
|
/// Marks the final message in a sender run for rounded corners and dots.
|
|
final bool bubbleEnd;
|
|
|
|
/// Marks the first message in a sender run for rounded top corners.
|
|
final bool bubbleStart;
|
|
|
|
/// Reserves room above overlapping reactions.
|
|
final bool hasReactions;
|
|
|
|
/// Display names for mentioned pubkeys, extracted from event p-tags.
|
|
/// Keys are lowercase pubkeys, values are display names.
|
|
final Map<String, String> mentionNames;
|
|
|
|
/// Contextual display labels for mentioned pubkeys (lowercase keys).
|
|
///
|
|
/// Presentation only: text still binds through [mentionNames], so a
|
|
/// disambiguated label never changes which signed text names whom.
|
|
final Map<String, String> mentionLabels;
|
|
|
|
/// Mentioned pubkeys that resolve to agents. Agent chips use the desktop
|
|
/// robot treatment instead of an `@` prefix.
|
|
final Set<String> agentMentionPubkeys;
|
|
|
|
/// Known channel names for #channel links. Keys are lowercase channel
|
|
/// names, values are channel IDs.
|
|
final Map<String, String> channelNames;
|
|
|
|
/// Raw event tags, used for `imeta` media metadata lookups.
|
|
final List<List<String>> tags;
|
|
|
|
/// Called when a #channel link is tapped.
|
|
final void Function(String channelId)? onChannelTap;
|
|
|
|
/// Called when an @mention of a known user is tapped, with the
|
|
/// mentioned user's pubkey.
|
|
final void Function(String pubkey)? onMentionTap;
|
|
|
|
/// Opens the message's thread from the full-screen image viewer.
|
|
final VoidCallback? onMediaReply;
|
|
|
|
/// Opens message-specific actions for an image in the full-screen viewer.
|
|
final MediaViewerMoreAction? onMediaMore;
|
|
final NativePhotoActions? nativePhotoActions;
|
|
|
|
final TextStyle? baseStyle;
|
|
|
|
/// Alignment applied to rendered markdown text.
|
|
final TextAlign? textAlign;
|
|
|
|
final int? maxLines;
|
|
|
|
/// Render a body that is nothing but emoji at [kEmojiOnlyFontSize], the way
|
|
/// desktop's `MessageRow` does. Off by default: previews, search hits, and
|
|
/// notification rows want a message to occupy its usual line height whatever
|
|
/// it contains.
|
|
final bool scaleEmojiOnly;
|
|
|
|
/// Marks the body as replaced by an edit, after its last line: inline after
|
|
/// prose, else on its own line after a closing block or trailing media.
|
|
final bool edited;
|
|
|
|
/// Allows a multi-image carousel to reclaim leading space reserved by the
|
|
/// surrounding message layout, while keeping its image count aligned with
|
|
/// the message body.
|
|
final double mediaCarouselLeadingOverflow;
|
|
|
|
/// Allows a multi-image carousel to continue through the trailing page
|
|
/// gutter while keeping its first image and count aligned with the body.
|
|
final double mediaCarouselTrailingOverflow;
|
|
|
|
const MessageContent({
|
|
super.key,
|
|
required this.content,
|
|
this.bubble = false,
|
|
this.additionalTextWidth = 0,
|
|
this.ownMessage = false,
|
|
this.trimTrailingSpacing = false,
|
|
this.bubbleEnd = true,
|
|
this.bubbleStart = true,
|
|
this.hasReactions = false,
|
|
this.mentionNames = const {},
|
|
this.mentionLabels = const {},
|
|
this.agentMentionPubkeys = const {},
|
|
this.channelNames = const {},
|
|
this.tags = const [],
|
|
this.onChannelTap,
|
|
this.onMentionTap,
|
|
this.onMediaReply,
|
|
this.onMediaMore,
|
|
this.nativePhotoActions,
|
|
this.baseStyle,
|
|
this.textAlign,
|
|
this.maxLines,
|
|
this.scaleEmojiOnly = false,
|
|
this.edited = false,
|
|
this.mediaCarouselLeadingOverflow = 0,
|
|
this.mediaCarouselTrailingOverflow = 0,
|
|
});
|
|
|
|
@override
|
|
Widget build(BuildContext context, WidgetRef ref) {
|
|
final markdownTheme = GptMarkdownTheme.of(context);
|
|
final resolvedChatColors = ChatColors.of(context);
|
|
// The fallback palette is newly allocated; keep the nested theme stable so
|
|
// unchanged messages do not reparse their Markdown on parent rebuilds.
|
|
final chatColors = useMemoized(() => resolvedChatColors, [
|
|
resolvedChatColors.outgoing,
|
|
resolvedChatColors.foreground,
|
|
]);
|
|
final ownTextColor = chatColors.foreground;
|
|
// Own-bubble links share the bubble ink; markdown marks them by underline.
|
|
final linkColor = ownMessage ? ownTextColor : context.colors.tertiary;
|
|
final bubbleInk = ownMessage ? ownTextColor : context.colors.onSurface;
|
|
final onSurface = context.colors.onSurface;
|
|
// GptMarkdownTheme notifies its dependents whenever the data object
|
|
// changes (the data has no value equality), and each notification makes
|
|
// every GptMarkdown below re-parse its text. Reuse one bubble theme while
|
|
// its inputs are unchanged so an ordinary rebuild does not re-parse.
|
|
final bubbleMarkdownTheme = useMemoized(
|
|
() => markdownTheme.copyWith(
|
|
linkColor: linkColor,
|
|
// A neutral chip would put white ink on a light fill; tint the accent
|
|
// instead.
|
|
inlineCode: ownMessage
|
|
? markdownTheme.inlineCode.copyWith(
|
|
color: ownTextColor,
|
|
backgroundColor: chatCodeTint(ownTextColor, 0.18),
|
|
borderColor: ownTextColor.withValues(alpha: 0.3),
|
|
)
|
|
: null,
|
|
h1: markdownTheme.h1?.copyWith(color: bubbleInk),
|
|
h2: markdownTheme.h2?.copyWith(color: bubbleInk),
|
|
h3: markdownTheme.h3?.copyWith(color: bubbleInk),
|
|
h4: markdownTheme.h4?.copyWith(color: bubbleInk),
|
|
h5: markdownTheme.h5?.copyWith(color: bubbleInk),
|
|
h6: markdownTheme.h6?.copyWith(color: bubbleInk),
|
|
),
|
|
[markdownTheme, linkColor, ownMessage, ownTextColor, onSurface],
|
|
);
|
|
final baseTextStyle =
|
|
(baseStyle ??
|
|
context.textTheme.bodyMedium?.copyWith(
|
|
color: context.colors.onSurface,
|
|
))
|
|
?.copyWith(color: bubble && ownMessage ? ownTextColor : null);
|
|
final resolvedMentionNames = mentionNames;
|
|
final signedMentionPubkeys = mentionedPubkeysFromTags(tags);
|
|
final mentionBindings = renderedMentionBindings(
|
|
content,
|
|
mentionNames,
|
|
signedMentionPubkeys,
|
|
);
|
|
final resolvedAgentMentionPubkeys = {
|
|
...agentMentionPubkeys.map((pubkey) => pubkey.toLowerCase()),
|
|
};
|
|
final resolvedChannelNames = channelNames.isNotEmpty
|
|
? channelNames
|
|
: ref.watch(channelIdsByNameProvider);
|
|
final channelHandler = useRef(onChannelTap)..value = onChannelTap;
|
|
final resolvedChannelTap = useMemoized(
|
|
() => (String channelId) {
|
|
final handler = channelHandler.value;
|
|
if (handler != null) {
|
|
handler(channelId);
|
|
} else {
|
|
ref
|
|
.read(pendingDeepLinkProvider.notifier)
|
|
.open(Uri(scheme: 'buzz', host: 'channel', path: channelId));
|
|
}
|
|
},
|
|
const [],
|
|
);
|
|
final replyHandler = useRef(onMediaReply)..value = onMediaReply;
|
|
final moreHandler = useRef(onMediaMore)..value = onMediaMore;
|
|
final mediaReply = useMemoized(
|
|
() =>
|
|
() => replyHandler.value?.call(),
|
|
const [],
|
|
);
|
|
final mediaMore = useMemoized(
|
|
() =>
|
|
(BuildContext context, String url) =>
|
|
moreHandler.value?.call(context, url),
|
|
const [],
|
|
);
|
|
final channelPresentationKey = [
|
|
for (final entry
|
|
in (resolvedChannelNames.entries.toList()
|
|
..sort((a, b) => a.key.compareTo(b.key))))
|
|
'${entry.key}\u0000${entry.value}',
|
|
].join('\u0001');
|
|
final imetaByUrl = {
|
|
for (final entry in parseImetaTags(tags).entries)
|
|
normalizeMarkdownDestination(entry.key): entry.value,
|
|
};
|
|
final normalizedContent = useMemoized(() => normalizeBareLinks(content), [
|
|
content,
|
|
]);
|
|
final trailingGallery = maxLines == null
|
|
? extractTrailingImageGallery(
|
|
normalizedContent,
|
|
imetaByUrl,
|
|
includeVideos: bubble,
|
|
)
|
|
: null;
|
|
final galleryText = trailingGallery?.content ?? normalizedContent;
|
|
final markdownContent = useMemoized(
|
|
() => separateMarkdownTables(escapeMarkdownLiterals(galleryText)),
|
|
[galleryText],
|
|
);
|
|
final customEmoji = _mergeCustomEmoji(
|
|
customEmojiFromTags(tags),
|
|
ref.watch(customEmojiListProvider),
|
|
);
|
|
final mentionPresentationKey = [
|
|
for (final entry
|
|
in (resolvedMentionNames.entries.toList()
|
|
..sort((a, b) => a.key.compareTo(b.key))))
|
|
'${entry.key}\u0000${entry.value}',
|
|
...(resolvedAgentMentionPubkeys.toList()..sort()),
|
|
...(signedMentionPubkeys.toList()..sort()),
|
|
].join('\u0001');
|
|
|
|
// Decided here rather than by the caller: this is where the event's own
|
|
// emoji tags and the community palette have already been merged, and a
|
|
// `:shortcode:` only counts as emoji if it resolves against that palette.
|
|
final emojiOnly =
|
|
scaleEmojiOnly &&
|
|
isEmojiOnlyMessage(
|
|
markdownContent,
|
|
nativeEmoji: ref.watch(nativeEmojiGlyphsProvider),
|
|
customEmoji: customEmoji,
|
|
);
|
|
final style = emojiOnly
|
|
? baseTextStyle?.copyWith(
|
|
fontSize: kEmojiOnlyFontSize,
|
|
height: kEmojiOnlyHeight,
|
|
)
|
|
: baseTextStyle;
|
|
final inlineCustomEmojiSize = emojiOnly
|
|
? kEmojiOnlyCustomEmojiSize
|
|
: kCustomEmojiInlineSize;
|
|
|
|
// A new pool per message text, so an edit retires the old links'
|
|
// recognizers (and any hold under way on them) with the old text.
|
|
final pressedLink = useValueNotifier<_LinkTextRecognizer?>(null);
|
|
final linkRecognizers = useMemoized(
|
|
() => _LinkTextRecognizers(pressedLink),
|
|
[markdownContent],
|
|
);
|
|
useEffect(() => linkRecognizers.dispose, [linkRecognizers]);
|
|
|
|
final finalContent = useMemoized(() {
|
|
// Replace spaces with non-breaking spaces inside known mention names
|
|
// so _MentionMd's pattern matches multi-word names as one token, in
|
|
// the authored case. Code, inline or fenced, is left as written.
|
|
return mapMarkdownProse(markdownContent, (segment) {
|
|
for (final range in mentionOccurrences(
|
|
segment,
|
|
mentionBindings.keys,
|
|
).reversed) {
|
|
segment = segment.replaceRange(
|
|
range.start,
|
|
range.end,
|
|
'@${_markdownMentionName(segment.substring(range.start + 1, range.end))}',
|
|
);
|
|
}
|
|
return segment;
|
|
});
|
|
}, [markdownContent, mentionPresentationKey]);
|
|
|
|
final inlinePatterns = _useMessageInlinePatterns(
|
|
ownBubble: bubble && ownMessage,
|
|
content: content,
|
|
finalContent: finalContent,
|
|
mentionNames: resolvedMentionNames,
|
|
mentionLabels: mentionLabels,
|
|
bindings: mentionBindings,
|
|
agentPubkeys: resolvedAgentMentionPubkeys,
|
|
channelNames: resolvedChannelNames,
|
|
customEmoji: customEmoji,
|
|
emojiSize: inlineCustomEmojiSize,
|
|
tags: tags,
|
|
hasMediaReply: onMediaReply != null,
|
|
hasMediaMore: onMediaMore != null,
|
|
onMentionTap: onMentionTap,
|
|
onChannelTap: resolvedChannelTap,
|
|
);
|
|
final editedStyle = editedMarkerStyle(context, own: bubble && ownMessage);
|
|
// An authored slot is drawn as written; the marker takes its own line.
|
|
final markerSlot = edited && !finalContent.contains(editedSlot);
|
|
final components = useMemoized(
|
|
() => [
|
|
if (markerSlot) editedMarkerPattern(editedStyle),
|
|
...inlinePatterns,
|
|
escapedSigilPattern,
|
|
],
|
|
[inlinePatterns, editedStyle, markerSlot],
|
|
);
|
|
|
|
Widget renderMarkdown(String text) => KeyedSubtree(
|
|
key: ValueKey(
|
|
'$text\u0000$mentionPresentationKey\u0000$channelPresentationKey',
|
|
),
|
|
child: _LinkPressHighlight(
|
|
pressed: pressedLink,
|
|
child: GptMarkdown(
|
|
text,
|
|
style: style,
|
|
styleSheet: bubble
|
|
? GptMarkdownStyleSheet(
|
|
blockQuote: BlockQuoteStyle(barColor: bubbleInk),
|
|
hr: HrStyle(color: bubbleInk.withValues(alpha: 0.3)),
|
|
table: TableStyle(
|
|
borderColor: bubbleInk.withValues(alpha: 0.3),
|
|
headerBackground: Colors.transparent,
|
|
headerTextStyle: TextStyle(color: bubbleInk),
|
|
),
|
|
)
|
|
: null,
|
|
followLinkColor: false,
|
|
// normalizeBareLinks() already turns bare URLs into Markdown links;
|
|
// gpt_markdown autolinks by default, so both would run.
|
|
autolink: false,
|
|
// Desktop has no GitHub alerts: a `> [!NOTE]` quote stays a quote.
|
|
alertBuilder: (_, alert) => alert.asBlockQuote(),
|
|
codeBuilder: (context, name, code, closed) => _MessageCodeBlock(
|
|
name: name,
|
|
code: code,
|
|
bubble: bubble,
|
|
ink: bubble && ownMessage ? ownTextColor : null,
|
|
),
|
|
// Chips, media links and taps are handled in _buildLink, so the
|
|
// package's own tap is not used.
|
|
inlineLinkBuilder: (link) => _buildMentionOrLink(
|
|
link,
|
|
ref,
|
|
unmaskInlinePatterns(link.url),
|
|
style,
|
|
resolvedChannelTap,
|
|
resolvedChannelNames,
|
|
linkRecognizers,
|
|
imetaByUrl,
|
|
),
|
|
imageBuilder: (context, maskedUrl, _, _) {
|
|
final imageUrl = unmaskInlinePatterns(maskedUrl);
|
|
return _buildMedia(
|
|
context,
|
|
imageUrl,
|
|
imetaByUrl[imageUrl],
|
|
onReply: onMediaReply == null ? null : mediaReply,
|
|
onMore: onMediaMore == null ? null : mediaMore,
|
|
);
|
|
},
|
|
textAlign: textAlign ?? (bubble ? TextAlign.start : null),
|
|
maxLines: maxLines,
|
|
inlinePatterns: components,
|
|
),
|
|
),
|
|
);
|
|
final segments = bubble
|
|
? messageBubbleSegments(finalContent, imetaByUrl)
|
|
: const <({String text, bool attachment})>[];
|
|
// Media that closes the body takes the marker after it instead.
|
|
final editedInBody =
|
|
edited &&
|
|
trailingGallery == null &&
|
|
(bubble
|
|
? segments.isNotEmpty && !segments.last.attachment
|
|
: finalContent.trim().isNotEmpty);
|
|
Widget renderBody(String text, {required bool last}) => editedInBody && last
|
|
? markedEditedBody(text, renderMarkdown, editedStyle, slot: markerSlot)
|
|
: renderMarkdown(text);
|
|
final markdown = bubble
|
|
? Column(
|
|
crossAxisAlignment: ownMessage
|
|
? CrossAxisAlignment.end
|
|
: CrossAxisAlignment.start,
|
|
mainAxisSize: MainAxisSize.min,
|
|
children: [
|
|
for (final (index, segment) in segments.indexed)
|
|
if (segment.attachment)
|
|
MessageReplyDragTarget(
|
|
child: MessageAttachmentCorners(
|
|
borderRadius: _attachmentCorners(
|
|
start: bubbleStart && index == 0,
|
|
end:
|
|
bubbleEnd &&
|
|
trailingGallery == null &&
|
|
index == segments.length - 1,
|
|
),
|
|
child: renderMarkdown(segment.text),
|
|
),
|
|
)
|
|
else
|
|
Padding(
|
|
key: ValueKey('message-text-bubble-$index'),
|
|
padding: EdgeInsets.only(
|
|
bottom:
|
|
trimTrailingSpacing &&
|
|
trailingGallery == null &&
|
|
index == segments.length - 1
|
|
? 0
|
|
: Grid.quarter,
|
|
),
|
|
child: ConstrainedBox(
|
|
constraints: BoxConstraints(
|
|
maxWidth:
|
|
MediaQuery.sizeOf(context).width *
|
|
messageTextMaxWidthFraction +
|
|
additionalTextWidth,
|
|
),
|
|
child: MessageReplyDragTarget(
|
|
child: LocalSendBubbleSurface(
|
|
color: ownMessage
|
|
? chatColors.outgoing
|
|
: receivedMessageSurface(
|
|
context.colors.brightness,
|
|
),
|
|
shape: const _MessageBubbleShape(),
|
|
child: Padding(
|
|
padding: EdgeInsets.fromLTRB(
|
|
Grid.xs,
|
|
Grid.xxs,
|
|
Grid.xs,
|
|
hasReactions && index == segments.length - 1
|
|
? Grid.xs
|
|
: Grid.xxs,
|
|
),
|
|
child: Theme(
|
|
data: Theme.of(context).copyWith(
|
|
extensions: [
|
|
...Theme.of(context).extensions.values,
|
|
chatColors,
|
|
],
|
|
colorScheme: context.colors.copyWith(
|
|
primary: linkColor,
|
|
),
|
|
),
|
|
child: GptMarkdownTheme(
|
|
gptThemeData: bubbleMarkdownTheme,
|
|
child: renderBody(
|
|
segment.text,
|
|
last: index == segments.length - 1,
|
|
),
|
|
),
|
|
),
|
|
),
|
|
),
|
|
),
|
|
),
|
|
),
|
|
],
|
|
)
|
|
: renderBody(finalContent, last: true);
|
|
if (trailingGallery == null) {
|
|
return edited && !editedInBody
|
|
? withEditedMarkerBelow(markdown, end: ownMessage)
|
|
: markdown;
|
|
}
|
|
|
|
return Column(
|
|
crossAxisAlignment: ownMessage
|
|
? CrossAxisAlignment.end
|
|
: CrossAxisAlignment.start,
|
|
mainAxisSize: MainAxisSize.min,
|
|
children: [
|
|
if (bubble) _MessageImageStackCount(items: trailingGallery.items),
|
|
if (trailingGallery.content.trim().isNotEmpty) markdown,
|
|
MessageReplyDragTarget(
|
|
// The photo stack is narrower than the row it aligns itself in, so
|
|
// it marks its own deck for the long press.
|
|
opensActions: !bubble,
|
|
child: MessageAttachmentCorners(
|
|
borderRadius: _attachmentCorners(
|
|
start: bubbleStart && trailingGallery.content.trim().isEmpty,
|
|
end: bubbleEnd,
|
|
),
|
|
child: bubble
|
|
? _MessageImageStack(
|
|
key: ValueKey(
|
|
trailingGallery.items
|
|
.map((item) => item.url)
|
|
.join('\u0000'),
|
|
),
|
|
items: trailingGallery.items,
|
|
mirrored: ownMessage,
|
|
nativeActions: nativePhotoActions,
|
|
onReply: onMediaReply,
|
|
onMore: onMediaMore,
|
|
)
|
|
: _MessageImageCarousel(
|
|
key: ValueKey(
|
|
trailingGallery.items
|
|
.map((item) => item.url)
|
|
.join('\u0000'),
|
|
),
|
|
items: trailingGallery.items,
|
|
mirrored: ownMessage,
|
|
leadingOverflow: mediaCarouselLeadingOverflow,
|
|
trailingOverflow: mediaCarouselTrailingOverflow,
|
|
onReply: onMediaReply,
|
|
onMore: onMediaMore,
|
|
),
|
|
),
|
|
),
|
|
if (edited) const EditedMarkerBelow(),
|
|
],
|
|
);
|
|
}
|
|
|
|
Widget _buildMedia(
|
|
BuildContext context,
|
|
String imageUrl,
|
|
ImetaEntry? imeta, {
|
|
VoidCallback? onReply,
|
|
MediaViewerMoreAction? onMore,
|
|
}) {
|
|
final mediaKind = classifyMediaUrl(imageUrl, imeta: imeta);
|
|
if (mediaKind == MessageMediaKind.audio) {
|
|
return Padding(
|
|
padding: const EdgeInsets.only(top: Grid.half),
|
|
child: VoiceNoteAttachment.remote(
|
|
url: imageUrl,
|
|
duration: Duration(
|
|
milliseconds: ((imeta?.duration ?? 0) * 1000).round(),
|
|
),
|
|
),
|
|
);
|
|
}
|
|
if (mediaKind == MessageMediaKind.video) {
|
|
return _MessageVideoPreview(
|
|
url: imageUrl,
|
|
imeta: imeta,
|
|
onReply: onReply,
|
|
);
|
|
}
|
|
return _MessageImagePreview(
|
|
url: imageUrl,
|
|
imeta: imeta,
|
|
semanticLabel: imeta?.alt ?? 'Message image',
|
|
onReply: onReply,
|
|
onMore: onMore,
|
|
);
|
|
}
|
|
|
|
/// A link as text that wraps with the sentence, or as a widget for chips,
|
|
/// audio and repository links.
|
|
InlineSpan _buildLink(
|
|
LinkBuildDetails link,
|
|
WidgetRef ref,
|
|
String url,
|
|
TextStyle? fallbackStyle,
|
|
void Function(String channelId) resolvedChannelTap,
|
|
Map<String, String> resolvedChannelNames,
|
|
_LinkTextRecognizers recognizers,
|
|
Map<String, ImetaEntry> imetaByUrl,
|
|
) {
|
|
final context = link.context;
|
|
final linkText = TextSpan(children: link.labelSpans);
|
|
final imeta = imetaByUrl[url];
|
|
String text = '';
|
|
linkText.visitChildren((span) {
|
|
if (span is TextSpan && span.text != null) {
|
|
text += span.text!;
|
|
}
|
|
return true;
|
|
});
|
|
|
|
final baseStyle = fallbackStyle ?? link.style;
|
|
if (imeta != null &&
|
|
classifyMediaUrl(url, imeta: imeta) == MessageMediaKind.audio) {
|
|
return link.asWidgetSpan(_buildMedia(context, url, imeta));
|
|
}
|
|
final uri = Uri.tryParse(url);
|
|
final buzzLink = uri?.scheme == 'buzz'
|
|
? parseBuzzDeepLink(uri!) ?? parseEntityDeepLink(uri)
|
|
: null;
|
|
final isBuzzLink =
|
|
buzzLink is ChannelDeepLink ||
|
|
buzzLink is MessageDeepLink ||
|
|
buzzLink is EntityDeepLink;
|
|
final isCanonicalBuzzLabel = isBuzzLink && text == url;
|
|
String? channelName(String id) =>
|
|
_channelNameForId(resolvedChannelNames, id);
|
|
final buzzLabel = buzzLinkLabel(buzzLink, channelName);
|
|
final buzzPresentation = switch (buzzLink) {
|
|
ChannelDeepLink() => (
|
|
icon: BuzzIcons.hash,
|
|
label: buzzLabel!,
|
|
semanticLabel: 'Open channel $buzzLabel',
|
|
interactive: true,
|
|
),
|
|
MessageDeepLink(:final channelId, :final messageId) => (
|
|
icon: BuzzIcons.messageSquare,
|
|
label: buzzLabel!,
|
|
semanticLabel:
|
|
'Open message ${shortBuzzId(messageId)} in channel ${buzzChannelLabel(channelId, channelName)}',
|
|
interactive: true,
|
|
),
|
|
EntityDeepLink(:final type, :final repository, :final eventId) => (
|
|
icon: switch (type) {
|
|
'repo' => BuzzIcons.folderGit2,
|
|
'pr' => BuzzIcons.gitPullRequest,
|
|
_ => BuzzIcons.circleDot,
|
|
},
|
|
label: buzzLabel!,
|
|
semanticLabel: switch (type) {
|
|
'repo' => 'Repository $repository',
|
|
'pr' =>
|
|
'Pull request ${shortBuzzId(eventId ?? '')} in repository $repository',
|
|
_ => 'Issue ${shortBuzzId(eventId ?? '')} in repository $repository',
|
|
},
|
|
interactive: false,
|
|
),
|
|
_ => null,
|
|
};
|
|
|
|
final authoredLinkStyle = baseStyle.copyWith(
|
|
color: context.colors.primary,
|
|
decoration: TextDecoration.underline,
|
|
decorationColor: context.colors.primary,
|
|
);
|
|
final canonicalLabelStyle = baseStyle.copyWith(
|
|
color: context.colors.primary,
|
|
fontWeight: FontWeight.w600,
|
|
);
|
|
final chip = isCanonicalBuzzLabel && buzzPresentation != null
|
|
? _TokenPill(
|
|
key: ValueKey('buzz-link-chip:$url'),
|
|
icon: buzzPresentation.icon,
|
|
interactive: buzzPresentation.interactive,
|
|
semanticLabel: buzzPresentation.semanticLabel,
|
|
text: buzzPresentation.label,
|
|
textStyle: baseStyle.copyWith(fontWeight: FontWeight.w600),
|
|
)
|
|
: null;
|
|
|
|
final highlightColor = (baseStyle.color ?? context.colors.primary)
|
|
.withValues(alpha: 0.2);
|
|
|
|
// Mobile has no repo/PR/issue destination yet, so these chips have no tap
|
|
// and no Open action, but a hold still copies or shares the link.
|
|
// The container keeps the chip's label its own node; without it, the
|
|
// non-interactive chip merges into the surrounding paragraph's label.
|
|
if (buzzLink is EntityDeepLink) {
|
|
return link.asWidgetSpan(
|
|
Semantics(
|
|
container: true,
|
|
child: _LinkLongPress(
|
|
url: url,
|
|
onOpen: null,
|
|
highlightColor: highlightColor,
|
|
child:
|
|
chip ??
|
|
Text.rich(
|
|
TextSpan(
|
|
style: isCanonicalBuzzLabel
|
|
? canonicalLabelStyle
|
|
: authoredLinkStyle,
|
|
children: [linkText],
|
|
),
|
|
),
|
|
),
|
|
),
|
|
);
|
|
}
|
|
|
|
Future<void> openLink() async {
|
|
final uri = Uri.tryParse(url);
|
|
if (uri == null) return;
|
|
|
|
// Rendered channel URLs must use the same callback as `#channel`
|
|
// references so detail-page callers can suppress self-navigation.
|
|
// Message and join links still need the top-level authenticated
|
|
// dispatcher.
|
|
if (uri.scheme == 'buzz') {
|
|
final deepLink = parseBuzzDeepLink(uri);
|
|
if (deepLink case ChannelDeepLink(:final channelId)) {
|
|
resolvedChannelTap(channelId);
|
|
} else if (deepLink is MessageDeepLink || deepLink is InviteDeepLink) {
|
|
ref.read(pendingDeepLinkProvider.notifier).open(uri);
|
|
}
|
|
return;
|
|
}
|
|
if (uri.scheme != 'http' && uri.scheme != 'https') return;
|
|
|
|
final auth = ref.read(mediaGetAuthServiceProvider);
|
|
if (!auth.isRelayMediaUrl(url)) {
|
|
await launchUrl(uri, mode: LaunchMode.externalApplication);
|
|
return;
|
|
}
|
|
|
|
try {
|
|
await ref.read(openDownloadedFileProvider)(
|
|
url,
|
|
auth.headersFor(url),
|
|
text,
|
|
);
|
|
} catch (_) {
|
|
if (!context.mounted) return;
|
|
ScaffoldMessenger.maybeOf(context)?.showFeedbackSnackBar(
|
|
const SnackBar(content: Text('Could not open attachment')),
|
|
kind: ToastKind.error,
|
|
);
|
|
}
|
|
}
|
|
|
|
// openLink handles only these schemes; the sheet hides Open for others.
|
|
final scheme = Uri.tryParse(url)?.scheme;
|
|
final canOpen = scheme == 'buzz' || scheme == 'http' || scheme == 'https';
|
|
void showActions() => _showLinkActions(
|
|
context,
|
|
url: url,
|
|
onOpen: canOpen ? () => unawaited(openLink()) : null,
|
|
);
|
|
if (chip != null) {
|
|
return link.asWidgetSpan(
|
|
_LinkLongPress(
|
|
url: url,
|
|
onOpen: canOpen ? () => unawaited(openLink()) : null,
|
|
highlightColor: highlightColor,
|
|
child: GestureDetector(onTap: openLink, child: chip),
|
|
),
|
|
);
|
|
}
|
|
|
|
// Text, not a widget, so a long label wraps mid-label and the words after
|
|
// it continue on the same line.
|
|
// The recognizer outlives this link when an edit removes it, so a tap or
|
|
// hold already under way checks that the link is still on screen.
|
|
// A link nothing can open shows its actions on a tap, so it isn't dead
|
|
// for screen reader users, who can't reach the hold.
|
|
final recognizer = recognizers.forLink(url, text)
|
|
..onTap = (() {
|
|
if (!context.mounted) return;
|
|
canOpen ? unawaited(openLink()) : showActions();
|
|
})
|
|
..onHold = () {
|
|
if (context.mounted) showActions();
|
|
}
|
|
..highlightColor = highlightColor;
|
|
// A canonical label is drawn as its plain text, as before; an authored
|
|
// label keeps its parsed spans (bold, code) in the link style.
|
|
if (isCanonicalBuzzLabel) {
|
|
return TextSpan(
|
|
text: text,
|
|
style: canonicalLabelStyle,
|
|
recognizer: recognizer,
|
|
);
|
|
}
|
|
return TextSpan(
|
|
style: authoredLinkStyle,
|
|
children: _withLinkRecognizer(link.labelSpans, recognizer),
|
|
);
|
|
}
|
|
}
|
|
|
|
List<CustomEmoji> _mergeCustomEmoji(
|
|
List<CustomEmoji> eventEmoji,
|
|
List<CustomEmoji> paletteEmoji,
|
|
) {
|
|
if (eventEmoji.isEmpty) return paletteEmoji;
|
|
if (paletteEmoji.isEmpty) return eventEmoji;
|
|
final seen = <String>{};
|
|
final merged = <CustomEmoji>[];
|
|
for (final emoji in [...eventEmoji, ...paletteEmoji]) {
|
|
if (seen.add(emoji.shortcode)) merged.add(emoji);
|
|
}
|
|
return merged;
|
|
}
|
|
|
|
class _MessageImagePreview extends HookConsumerWidget {
|
|
final String url;
|
|
final ImetaEntry? imeta;
|
|
final String semanticLabel;
|
|
final VoidCallback? onReply;
|
|
final MediaViewerMoreAction? onMore;
|
|
|
|
const _MessageImagePreview({
|
|
required this.url,
|
|
required this.imeta,
|
|
required this.semanticLabel,
|
|
required this.onReply,
|
|
required this.onMore,
|
|
});
|
|
|
|
@override
|
|
Widget build(BuildContext context, WidgetRef ref) {
|
|
final heroTag = useMemoized(() => Object());
|
|
final layout = _resolveImagePreviewLayout(context, imeta?.aspectRatio);
|
|
final previewDecodeWidth = layout.width ?? messageMediaMaxWidth(context);
|
|
|
|
return Padding(
|
|
padding: const EdgeInsets.only(top: Grid.half),
|
|
child: GestureDetector(
|
|
onTap: () => openImageViewer(
|
|
context,
|
|
imageUrl: url,
|
|
heroTag: heroTag,
|
|
semanticLabel: semanticLabel,
|
|
previewDecodeWidth: previewDecodeWidth,
|
|
aspectRatio: imeta?.aspectRatio,
|
|
onReply: onReply,
|
|
onMore: onMore,
|
|
),
|
|
child: _MessageMediaPreviewFrame(
|
|
previewKey: ValueKey('message-media-image-preview:$url'),
|
|
backgroundColor: context.colors.surfaceContainerHighest,
|
|
width: layout.width,
|
|
height: layout.height,
|
|
child: MediaViewerHero(
|
|
tag: heroTag,
|
|
child: ClipRRect(
|
|
borderRadius:
|
|
MessageAttachmentCorners.of(context) ??
|
|
BorderRadius.circular(Radii.md),
|
|
child: MediaImage(
|
|
url: url,
|
|
decodeWidth: previewDecodeWidth,
|
|
fit: layout.fit,
|
|
semanticLabel: semanticLabel,
|
|
frameBuilder: (context, child, frame, synchronous) =>
|
|
frame != null || synchronous
|
|
? child
|
|
: const MediaLoadingPlaceholder(label: 'Loading image'),
|
|
errorBuilder: (_, _, _) => _MediaPreviewFallback(
|
|
icon: BuzzIcons.imageOff,
|
|
label: 'Image unavailable',
|
|
),
|
|
),
|
|
),
|
|
),
|
|
),
|
|
),
|
|
);
|
|
}
|
|
}
|
|
|
|
class _MessageMediaPreviewFrame extends StatelessWidget {
|
|
final Key previewKey;
|
|
final Color backgroundColor;
|
|
final double? width;
|
|
final double? height;
|
|
final Widget child;
|
|
|
|
const _MessageMediaPreviewFrame({
|
|
required this.previewKey,
|
|
required this.backgroundColor,
|
|
this.width,
|
|
this.height,
|
|
required this.child,
|
|
});
|
|
|
|
@override
|
|
Widget build(BuildContext context) {
|
|
final resolvedWidth = width ?? messageMediaMaxWidth(context);
|
|
|
|
return Container(
|
|
key: previewKey,
|
|
width: resolvedWidth,
|
|
height: height,
|
|
clipBehavior: Clip.antiAlias,
|
|
decoration: BoxDecoration(
|
|
color: backgroundColor,
|
|
borderRadius:
|
|
MessageAttachmentCorners.of(context) ??
|
|
BorderRadius.circular(Radii.md),
|
|
border: Border.all(color: context.colors.outlineVariant),
|
|
),
|
|
child: child,
|
|
);
|
|
}
|
|
}
|
|
|
|
_ImagePreviewLayout _resolveImagePreviewLayout(
|
|
BuildContext context,
|
|
double? aspectRatio,
|
|
) {
|
|
final previewSize = messageImagePreviewSize(context, aspectRatio);
|
|
return _ImagePreviewLayout(
|
|
width: previewSize.width,
|
|
height: previewSize.height,
|
|
fit: aspectRatio == null ? BoxFit.contain : BoxFit.cover,
|
|
);
|
|
}
|
|
|
|
class _ImagePreviewLayout {
|
|
final double? width;
|
|
final double? height;
|
|
final BoxFit fit;
|
|
|
|
const _ImagePreviewLayout({this.width, this.height, required this.fit});
|
|
}
|
|
|
|
class _MediaPreviewFallback extends StatelessWidget {
|
|
final IconData icon;
|
|
final String label;
|
|
|
|
const _MediaPreviewFallback({required this.icon, required this.label});
|
|
|
|
@override
|
|
Widget build(BuildContext context) {
|
|
return ColoredBox(
|
|
color: context.colors.surfaceContainerHighest,
|
|
child: Center(
|
|
child: Column(
|
|
mainAxisSize: MainAxisSize.min,
|
|
children: [
|
|
Icon(icon, color: context.colors.onSurfaceVariant),
|
|
const SizedBox(height: Grid.quarter),
|
|
Text(
|
|
label,
|
|
style: context.textTheme.labelSmall?.copyWith(
|
|
color: context.colors.onSurfaceVariant,
|
|
),
|
|
textAlign: TextAlign.center,
|
|
),
|
|
],
|
|
),
|
|
),
|
|
);
|
|
}
|
|
}
|
|
|
|
const _codeCopyButtonSize = 28.0;
|
|
|
|
class _MessageCodeBlock extends HookWidget {
|
|
final String name;
|
|
final String code;
|
|
|
|
/// Whether the block sits inside a message bubble.
|
|
final bool bubble;
|
|
|
|
/// Text color on an accent bubble; null keeps the neutral highlighted card.
|
|
final Color? ink;
|
|
|
|
const _MessageCodeBlock({
|
|
required this.name,
|
|
required this.code,
|
|
this.bubble = false,
|
|
this.ink,
|
|
});
|
|
|
|
@override
|
|
Widget build(BuildContext context) {
|
|
final isCopied = useState(false);
|
|
|
|
Future<void> handleCopy() async {
|
|
await copyToClipboard(context, code, message: 'Code copied');
|
|
if (!context.mounted) return;
|
|
isCopied.value = true;
|
|
Future.delayed(const Duration(seconds: 2), () {
|
|
if (context.mounted) isCopied.value = false;
|
|
});
|
|
}
|
|
|
|
final ink = this.ink;
|
|
// A fence's closing newline would otherwise render as a blank last line.
|
|
final shownCode = code.trimRight();
|
|
final codeBaseStyle = TextStyle(
|
|
fontFamily: CodeStyle.fontFamily,
|
|
fontSize: CodeStyle.fontSize,
|
|
height: CodeStyle.lineHeight,
|
|
color: ink ?? context.colors.onSurface,
|
|
);
|
|
final isDark = context.theme.brightness == Brightness.dark;
|
|
final codeTheme = isDark ? highlightDarkTheme : highlightLightTheme;
|
|
// Syntax colors are tuned for neutral cards and lose contrast on accents.
|
|
final codeSpans = useMemoized(
|
|
() => ink == null
|
|
? highlightCode(shownCode, name, codeTheme, codeBaseStyle)
|
|
: [TextSpan(text: shownCode)],
|
|
[code, name, isDark, ink],
|
|
);
|
|
// Opaque, so the copy button can share it and hide code scrolled beneath.
|
|
// An inked block sits on the outgoing fill, so its tint is blended there.
|
|
final surface = ink == null
|
|
? CodeStyle.background(context.colors)
|
|
: Color.alphaBlend(
|
|
chatCodeTint(ink, 0.14),
|
|
ChatColors.of(context).outgoing,
|
|
);
|
|
return Container(
|
|
// In a bubble, the vertical margin brings the bubble's 8px vertical
|
|
// padding up to its 16px side padding, so the block is inset evenly and
|
|
// its corners stay concentric with the bubble's.
|
|
margin: bubble
|
|
? const EdgeInsets.symmetric(vertical: Grid.xs - Grid.xxs)
|
|
: const EdgeInsets.only(top: Grid.half),
|
|
decoration: BoxDecoration(
|
|
color: surface,
|
|
borderRadius: BorderRadius.circular(
|
|
bubble ? Radii.container - Grid.xs : 12,
|
|
),
|
|
border: Border.all(
|
|
color:
|
|
ink?.withValues(alpha: 0.24) ?? CodeStyle.border(context.colors),
|
|
),
|
|
),
|
|
child: Stack(
|
|
children: [
|
|
// As on desktop, the code scrolls under the copy button rather than
|
|
// beside it, and its end padding keeps every line end reachable.
|
|
Column(
|
|
crossAxisAlignment: CrossAxisAlignment.stretch,
|
|
mainAxisSize: MainAxisSize.min,
|
|
children: [
|
|
if (name.isNotEmpty)
|
|
Padding(
|
|
padding: const EdgeInsets.fromLTRB(
|
|
Grid.twelve,
|
|
Grid.twelve,
|
|
Grid.twelve + _codeCopyButtonSize,
|
|
Grid.half,
|
|
),
|
|
child: Text(
|
|
name,
|
|
style: context.textTheme.labelSmall?.copyWith(
|
|
color: ink ?? context.colors.onSurfaceVariant,
|
|
),
|
|
),
|
|
),
|
|
SingleChildScrollView(
|
|
scrollDirection: Axis.horizontal,
|
|
padding: EdgeInsets.fromLTRB(
|
|
Grid.twelve,
|
|
name.isEmpty ? Grid.twelve : 0,
|
|
Grid.twelve + _codeCopyButtonSize,
|
|
Grid.twelve,
|
|
),
|
|
child: RichText(
|
|
softWrap: false,
|
|
text: TextSpan(style: codeBaseStyle, children: codeSpans),
|
|
),
|
|
),
|
|
],
|
|
),
|
|
Positioned(
|
|
top: Grid.half + Grid.quarter,
|
|
right: Grid.half + Grid.quarter,
|
|
child: SizedBox(
|
|
width: _codeCopyButtonSize,
|
|
height: _codeCopyButtonSize,
|
|
child: IconButton(
|
|
onPressed: handleCopy,
|
|
padding: EdgeInsets.zero,
|
|
visualDensity: VisualDensity.compact,
|
|
style: IconButton.styleFrom(
|
|
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
|
|
backgroundColor: surface,
|
|
),
|
|
icon: Icon(
|
|
isCopied.value ? BuzzIcons.check : BuzzIcons.copy,
|
|
size: 14,
|
|
color:
|
|
ink ??
|
|
(isCopied.value
|
|
? context.colors.primary
|
|
: context.colors.onSurfaceVariant),
|
|
),
|
|
),
|
|
),
|
|
),
|
|
],
|
|
),
|
|
);
|
|
}
|
|
}
|