Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions mobile/lib/features/channels/compose_bar.dart
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,9 @@ import 'channel.dart';
import 'channel_management_provider.dart';
import 'channels_provider.dart';
import 'timeline_message.dart';
import '../../shared/custom_emoji/custom_emoji_render.dart';
import '../../shared/emoji/emoji_data_provider.dart';
import '../../shared/emoji/emoji_search.dart';
import '../../shared/emoji/emoji_picker.dart';
import 'message_content/markdown_link_mentions.dart';
import 'mentions/mention_candidates.dart';
Expand Down
123 changes: 99 additions & 24 deletions mobile/lib/features/channels/compose_bar/compose_bar_widget.dart
Original file line number Diff line number Diff line change
Expand Up @@ -213,6 +213,7 @@ class ComposeBar extends HookConsumerWidget {
);

// Channel autocomplete state ----------------------------------------------
final emojiQuery = useState<String?>(null);
final channelQuery = useState<String?>(null);
final channelStartIdx = useState(-1);
final channelsAsync = ref.watch(channelsProvider);
Expand Down Expand Up @@ -353,8 +354,12 @@ class ComposeBar extends HookConsumerWidget {
void listener() {
final editingValue = controller.value;
final previousValue = lastObservedEditingValue.value;
// A notify without an edit, such as new channel names, must not
// reopen a query the user dismissed.
if (editingValue == previousValue) return;
lastObservedEditingValue.value = editingValue;
if (isModifyingText.value || editingValue == previousValue) return;
emojiQuery.value = _emojiQuery(editingValue);
if (isModifyingText.value) return;
final text = editingValue.text;
final sel = editingValue.selection;
final textChanged = text != previousValue.text;
Expand Down Expand Up @@ -404,6 +409,52 @@ class ComposeBar extends HookConsumerWidget {
final channels = channelsAsync.asData?.value ?? <Channel>[];
final channelSuggestions = filterChannels(channels, channelQuery.value);

// Load the catalog on the first colon query, then keep it so the next
// token reuses the index instead of rebuilding it.
final emojiIndexWanted = useRef(false);
if (emojiQuery.value != null) emojiIndexWanted.value = true;
final dataset = emojiIndexWanted.value
? ref.watch(emojiDatasetOrEmptyProvider)
: null;
final emojiIndex = useMemoized(
() => dataset == null
? null
: ShortcodeIndex<_EmojiChoice>([
for (final entry in customEmoji)
(
code: entry.shortcode,
text: ':${entry.shortcode}:',
url: entry.url,
),
for (final entry in dataset.all)
if (entry.skinIndex == 0)
(code: entry.id, text: entry.native, url: null),
], (entry) => entry.code),
[dataset, customEmoji],
);
final emojiSuggestions = useMemoized(() {
final query = emojiQuery.value;
if (query == null || emojiIndex == null) return const <_EmojiChoice>[];
return emojiIndex.rank(query, limit: _emojiSuggestionLimit);
}, [emojiQuery.value, emojiIndex]);

void selectEmoji(_EmojiChoice choice) {
final query = _emojiQuery(controller.value);
if (query == null || query != emojiQuery.value) return;
final caret = controller.selection.end;
final start = caret - query.length - 1;
final suffix = _emojiSuffix.matchAsPrefix(controller.text, caret)!;
_replaceComposerRange(
controller,
start: start,
end: suffix.end,
replacement: choice.text,
caret: start + choice.text.length,
);
focusNode.requestFocus();
emojiQuery.value = null;
}

// Insert a selected channel into the text field.
void insertChannel(Channel channel) {
final start = channelStartIdx.value.clamp(0, controller.text.length);
Expand Down Expand Up @@ -869,7 +920,8 @@ class ComposeBar extends HookConsumerWidget {
// can be edited.
final pickerVisible =
chooserOpen &&
(channelSuggestions.isNotEmpty ||
(emojiSuggestions.isNotEmpty ||
channelSuggestions.isNotEmpty ||
suggestions.isNotEmpty ||
mentionRows.searchFailed) &&
attachmentSurface.value == _AttachmentSurface.closed &&
Expand All @@ -878,16 +930,22 @@ class ComposeBar extends HookConsumerWidget {
final topMention = suggestions
.where((s) => !mentionRows.unavailable.contains(s.pubkey))
.firstOrNull;
final pickerQuery = (mentionChooser.query, channelQuery.value);
String? activeQuery() =>
emojiQuery.value == null ? channelQuery.value : ':${emojiQuery.value}';
final pickerQuery = (mentionChooser.query, activeQuery());
KeyEventResult handleHardwareKey(FocusNode _, KeyEvent event) =>
_handleComposerHardwareKey(
event,
controller,
inputOwned: iosAttachmentPopover.isActive || isEmojiPickerOpen.value,
query: (mentionChooser.liveQuery.value, channelQuery.value),
query: (mentionChooser.liveQuery.value, activeQuery()),
renderedQuery: pickerQuery,
pickerVisible: pickerVisible,
acceptSuggestion: topChannel != null
acceptSuggestion: emojiSuggestions.isNotEmpty
? () => _runComposerAction(
() => selectEmoji(emojiSuggestions.first),
)
: topChannel != null
? () => _runComposerAction(() => insertChannel(topChannel))
: topMention != null
? () => _runComposerAction(() => insertMention(topMention))
Expand All @@ -898,24 +956,37 @@ class ComposeBar extends HookConsumerWidget {
},
);

final suggestionPanel = _composerSuggestionPanel(
channelSuggestions: chooserOpen ? channelSuggestions : const [],
mentionSuggestions: chooserOpen ? suggestions : const [],
unavailableMentions: mentionRows.unavailable,
mentionSearchFailed: chooserOpen && mentionRows.searchFailed,
reserveMentionHeight: mentionRows.reserveHeight,
mentionSearching: mentionRows.searching,
onMentionSearchRetry: () {
if (mentionChooser.query case final query?) {
ref.invalidate(mentionUserSearchProvider(query));
}
},
userCache: userCache,
currentPubkey: currentPubkey,
isDmChannel: isDmChannel,
onChannelSelect: insertChannel,
onMentionSelect: insertMention,
);
final suggestionPanel = chooserOpen && emojiSuggestions.isNotEmpty
? TextFieldTapRegion(
child: _ComposerSearchSuggestions<_EmojiChoice>(
surfaceKey: const ValueKey('emoji-suggestions-popover'),
suggestions: emojiSuggestions,
label: (entry) => ':${entry.code}:',
horizontalTitleGap: 8,
singleLineLabel: true,
labelStyle: context.textTheme.bodyLarge?.copyWith(fontSize: 14),
leading: _emojiSuggestionPreview,
onSelect: selectEmoji,
),
)
: _composerSuggestionPanel(
channelSuggestions: chooserOpen ? channelSuggestions : const [],
mentionSuggestions: chooserOpen ? suggestions : const [],
unavailableMentions: mentionRows.unavailable,
mentionSearchFailed: chooserOpen && mentionRows.searchFailed,
reserveMentionHeight: mentionRows.reserveHeight,
mentionSearching: mentionRows.searching,
onMentionSearchRetry: () {
if (mentionChooser.query case final query?) {
ref.invalidate(mentionUserSearchProvider(query));
}
},
userCache: userCache,
currentPubkey: currentPubkey,
isDmChannel: isDmChannel,
onChannelSelect: insertChannel,
onMentionSelect: insertMention,
);
_AttachmentSurfacePanel buildOverlayPanel(_AttachmentSurface surface) {
return _composerAttachmentPanel(
preparePhotos: prepare,
Expand Down Expand Up @@ -1021,10 +1092,14 @@ class ComposeBar extends HookConsumerWidget {
defaultTargetPlatform == TargetPlatform.iOS &&
!interactionLocked &&
!voiceNote.isRecording,
suggestions: mentionChooser.query != null || channelQuery.value != null
suggestions:
(chooserOpen && emojiSuggestions.isNotEmpty) ||
mentionChooser.query != null ||
channelQuery.value != null
? suggestionPanel
: null,
onDismissSuggestions: () {
emojiQuery.value = null;
mentionChooser.close();
channelQuery.value = null;
},
Expand Down
9 changes: 8 additions & 1 deletion mobile/lib/features/channels/compose_bar/helpers.dart
Original file line number Diff line number Diff line change
Expand Up @@ -344,7 +344,14 @@ Widget _composerSuggestionPanel({
? KeyedSubtree(
key: const ValueKey('channel-suggestions'),
child: TextFieldTapRegion(
child: _ChannelSuggestions(
child: _ComposerSearchSuggestions<Channel>(
surfaceKey: const ValueKey('channel-suggestions-popover'),
leading: (context, _) => Icon(
BuzzIcons.hash,
size: 20,
color: context.colors.onSurfaceVariant,
),
label: (channel) => channel.name,
suggestions: channelSuggestions,
onSelect: onChannelSelect,
),
Expand Down
104 changes: 90 additions & 14 deletions mobile/lib/features/channels/compose_bar/suggestions.dart
Original file line number Diff line number Diff line change
Expand Up @@ -242,19 +242,94 @@ List<Channel> filterChannels(List<Channel> channels, String? query) {
.toList();
}

class _ChannelSuggestions extends StatelessWidget {
final List<Channel> suggestions;
final void Function(Channel) onSelect;
typedef _EmojiChoice = ({String code, String text, String? url});

const _ChannelSuggestions({
// Enough rows to scroll through without ranking the whole catalog into a list.
const _emojiSuggestionLimit = 50;

final _emojiToken = RegExp(r'(?:^|[\s(\[{]):([a-zA-Z0-9_+-]{2,64})$');

final _emojiSuffix = RegExp(r'[a-zA-Z0-9_+-]*:?');

String? _emojiQuery(TextEditingValue value) {
final caret = value.selection;
if (!caret.isValid || !caret.isCollapsed || caret.end > value.text.length) {
return null;
}
return _emojiToken.firstMatch(value.text.substring(0, caret.end))?.group(1);
}

Widget _emojiSuggestionPreview(BuildContext context, _EmojiChoice entry) =>
entry.url == null
? ExcludeSemantics(
child: Text(entry.text, style: const TextStyle(fontSize: 26)),
)
: _CachedCustomEmojiPreview(
shortcode: entry.code,
url: entry.url!,
size: 26,
);

/// A custom emoji in the suggestion list, drawn only from bytes another
/// surface already downloaded. Typing a shortcode starts no image request: an
/// emoji not seen yet shows the placeholder. The row's label already reads
/// the shortcode, so the preview adds nothing for screen readers.
class _CachedCustomEmojiPreview extends ConsumerWidget {
final String shortcode;
final String url;
final double size;

const _CachedCustomEmojiPreview({
required this.shortcode,
required this.url,
required this.size,
});

@override
Widget build(BuildContext context, WidgetRef ref) {
final bytes = ref.watch(customEmojiBytesCacheProvider).lookup(url);
return ExcludeSemantics(
child: bytes == null
? CustomEmojiPlaceholder(shortcode: shortcode, size: size)
: Image.memory(
bytes,
width: size,
height: size,
cacheWidth: (size * MediaQuery.devicePixelRatioOf(context))
.ceil(),
fit: BoxFit.contain,
filterQuality: FilterQuality.medium,
),
);
}
}

class _ComposerSearchSuggestions<T> extends StatelessWidget {
final Key surfaceKey;
final List<T> suggestions;
final void Function(T) onSelect;

final Widget Function(BuildContext, T) leading;
final String Function(T) label;
final TextStyle? labelStyle;
final double horizontalTitleGap;
final bool singleLineLabel;

const _ComposerSearchSuggestions({
required this.surfaceKey,
required this.leading,
required this.label,
this.labelStyle,
this.horizontalTitleGap = 0,
this.singleLineLabel = false,
required this.suggestions,
required this.onSelect,
});

@override
Widget build(BuildContext context) {
return Material(
key: const ValueKey('channel-suggestions-popover'),
key: surfaceKey,
type: MaterialType.card,
color: _ComposerGlassScope.of(context)
? Colors.transparent
Expand All @@ -272,21 +347,22 @@ class _ChannelSuggestions extends StatelessWidget {
itemCount: suggestions.length,
separatorBuilder: (_, _) => const SizedBox.shrink(),
itemBuilder: (context, index) {
final channel = suggestions[index];
final item = suggestions[index];
return ListTile(
dense: true,
visualDensity: VisualDensity.compact,
horizontalTitleGap: 0,
horizontalTitleGap: horizontalTitleGap,
leading: SizedBox.square(
dimension: 36,
child: Icon(
BuzzIcons.hash,
size: 20,
color: context.colors.onSurfaceVariant,
),
child: Center(child: leading(context, item)),
),
title: Text(
label(item),
style: labelStyle ?? context.textTheme.bodyLarge,
maxLines: singleLineLabel ? 1 : null,
overflow: singleLineLabel ? TextOverflow.ellipsis : null,
),
title: Text(channel.name, style: context.textTheme.bodyLarge),
onTap: () => _runComposerAction(() => onSelect(channel)),
onTap: () => _runComposerAction(() => onSelect(item)),
);
},
),
Expand Down
Loading
Loading