mirror of
https://github.com/block/buzz.git
synced 2026-11-26 19:21:50 +00:00
## Summary The mobile composer ignored Tab and Enter from hardware keyboards. Tab and Enter now accept the first selectable mention or channel suggestion while its picker is visible. Otherwise Enter or numpad Enter sends the message when attachment controls are closed. Enter leaves the draft untouched while an attachment surface is open. Tab leaves the draft unchanged while the picker is hidden or the field is read-only. A visible picker with no selectable row consumes Tab and Enter without sending. Only unmodified Tab accepts suggestions. Native attachment and emoji pickers own keyboard input until dismissal. Keyboard suggestion acceptance and sending use the same selection haptic as touch. Modified Enter and active IME composition retain normal text-field handling. Android IMEs can emit Enter as a key event too. Sending requires a mapped physical Enter key on Android, so scan-code-free IME Enter keeps newline handling. ### Related issue None found. ### Testing The composer widget regressions reproduce ignored Tab/Enter before the feature and an unintended send from Android IME Enter before its guard. The picker regressions cover Enter accepting a visible suggestion, Enter and numpad Enter retaining an Android draft while the attachment menu is open, and Tab leaving hidden or read-only suggestions untouched. They verify suggestion acceptance, error-only picker handling, native attachment popover ownership, modified Tab, sending, software Return and Android physical-key handling. Rapid Enter while member scanning is pending sends only once through the existing draft revision guard. Native validation and screenshots use an isolated Android API 28 ComposeBar harness at `09fb673f9`, with an observed send callback and a test-only native key injector. Physical Enter sends once and clears the draft; IME Enter inserts a newline without sending. Native validation of picker acceptance, visibility and read-only handling remains outstanding. ### Screenshots | Physical Enter sends and clears the draft | IME Enter keeps a newline without sending | | --- | --- | |  |  | | Mention suggestions | Tab accepts the suggestion | | --- | --- | |  |  | --------- Signed-off-by: John Tennant <jtennant@squareup.com> Signed-off-by: Tom Brow <tomb@squareup.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Oliver <e78152627ea32fbacb070e5047afcfb8e409fa3343d9e618227baacca5b5e607@buzz.block.builderlab.xyz> Co-authored-by: Tom Brow <tomb@squareup.com> Co-authored-by: studio <dc2fc481343672df31a689840c09299972e704dac592e0da6f18486646a7ee3e@buzz.block.builderlab.xyz>
868 lines
28 KiB
Dart
868 lines
28 KiB
Dart
part of '../compose_bar.dart';
|
|
|
|
String _composerDraftIdentity(WidgetRef ref) =>
|
|
'${ref.watch(relayConfigProvider).baseUrl}'
|
|
':${ref.watch(myPubkeyProvider) ?? 'anon'}';
|
|
|
|
void _useComposerFocusRestorer({
|
|
required ValueChanged<VoidCallback>? onChanged,
|
|
required ValueNotifier<bool> isExpanded,
|
|
required FocusNode focusNode,
|
|
required VoidCallback expand,
|
|
}) {
|
|
useEffect(() {
|
|
if (onChanged == null) return null;
|
|
|
|
var isCurrent = true;
|
|
void restoreFocus() {
|
|
if (!isCurrent) return;
|
|
if (isExpanded.value) {
|
|
focusNode.requestFocus();
|
|
} else {
|
|
expand();
|
|
}
|
|
}
|
|
|
|
onChanged(restoreFocus);
|
|
return () => isCurrent = false;
|
|
}, [onChanged, focusNode]);
|
|
}
|
|
|
|
void _useComposerChannelNames(
|
|
_MarkdownEditingController controller,
|
|
AsyncValue<List<Channel>> channelsAsync,
|
|
) {
|
|
// The composer rebuilds on every keystroke and keyboard frame, so build the
|
|
// name map and its key only when the channel list itself changes.
|
|
final channels = channelsAsync.asData?.value;
|
|
final (:channelNames, :channelNamesKey) = useMemoized(() {
|
|
final names = {
|
|
for (final channel in channels ?? const <Channel>[])
|
|
channel.name.toLowerCase(): channel.id,
|
|
};
|
|
final key = names.entries
|
|
.map((entry) => '${entry.key}\u0000${entry.value}')
|
|
.join('\u0001');
|
|
return (channelNames: names, channelNamesKey: key);
|
|
}, [channels]);
|
|
useEffect(() {
|
|
controller.setChannelNames(channelNames);
|
|
return null;
|
|
}, [controller, channelNamesKey]);
|
|
}
|
|
|
|
const _typingThrottleMs = 3000;
|
|
|
|
/// How long a keyboard that was up before an inactive spell may take to come
|
|
/// back after the app resumes. iOS restores it natively a few hundred
|
|
/// milliseconds after `resumed` (flutter/flutter#189051 logs about 0.4 s).
|
|
const _composerKeyboardRestoreGrace = Duration(seconds: 1);
|
|
|
|
// Keyboard show/hide drives Android IME lift and collapses on hide.
|
|
void _useComposerKeyboardMetrics({
|
|
required BuildContext context,
|
|
required FocusNode focusNode,
|
|
required _ComposerVoiceNote voiceNote,
|
|
required ObjectRef<Timer?> androidImeFallbackTimer,
|
|
required ValueNotifier<bool> androidImeTransitionStarted,
|
|
required VoidCallback collapseComposer,
|
|
}) {
|
|
final appView = View.of(context);
|
|
useEffect(() {
|
|
final observer = _ComposerKeyboardMetricsObserver(
|
|
view: appView,
|
|
onKeyboardShown: () {
|
|
androidImeFallbackTimer.value?.cancel();
|
|
androidImeTransitionStarted.value = true;
|
|
},
|
|
onKeyboardHidden: () {
|
|
androidImeFallbackTimer.value?.cancel();
|
|
if (defaultTargetPlatform == TargetPlatform.android) {
|
|
androidImeTransitionStarted.value = false;
|
|
}
|
|
voiceNote.onKeyboardHidden();
|
|
collapseComposer();
|
|
focusNode.unfocus();
|
|
},
|
|
);
|
|
WidgetsBinding.instance.addObserver(observer);
|
|
return () {
|
|
WidgetsBinding.instance.removeObserver(observer);
|
|
observer.dispose();
|
|
};
|
|
}, [appView, focusNode, voiceNote.isPreparing]);
|
|
}
|
|
|
|
class _ComposerKeyboardMetricsObserver with WidgetsBindingObserver {
|
|
final FlutterView view;
|
|
final VoidCallback onKeyboardShown;
|
|
final VoidCallback onKeyboardHidden;
|
|
bool _wasVisible;
|
|
Timer? _restoreGrace;
|
|
|
|
_ComposerKeyboardMetricsObserver({
|
|
required this.view,
|
|
required this.onKeyboardShown,
|
|
required this.onKeyboardHidden,
|
|
}) : _wasVisible = view.viewInsets.bottom > 0;
|
|
|
|
// iOS drops the keyboard inset while the app is inactive (Control Center,
|
|
// the app switcher) and restores the keyboard natively after it resumes.
|
|
// Treating that drop as a dismissal collapsed the composer and left the
|
|
// restored keyboard attached to no field. So ignore metrics until the app
|
|
// resumes, and give a keyboard that was up the restore grace to return
|
|
// before deciding it was dismissed.
|
|
@override
|
|
void didChangeMetrics() {
|
|
final lifecycle = WidgetsBinding.instance.lifecycleState;
|
|
if (lifecycle != null && lifecycle != AppLifecycleState.resumed) return;
|
|
if (_restoreGrace != null) {
|
|
if (view.viewInsets.bottom <= 0) return;
|
|
_cancelRestoreGrace();
|
|
}
|
|
_reconcile();
|
|
}
|
|
|
|
@override
|
|
void didChangeAppLifecycleState(AppLifecycleState state) {
|
|
if (state != AppLifecycleState.resumed) {
|
|
_cancelRestoreGrace();
|
|
return;
|
|
}
|
|
if (_wasVisible && view.viewInsets.bottom <= 0) {
|
|
_restoreGrace ??= Timer(_composerKeyboardRestoreGrace, () {
|
|
_restoreGrace = null;
|
|
_reconcile();
|
|
});
|
|
return;
|
|
}
|
|
_reconcile();
|
|
}
|
|
|
|
void dispose() => _cancelRestoreGrace();
|
|
|
|
void _cancelRestoreGrace() {
|
|
_restoreGrace?.cancel();
|
|
_restoreGrace = null;
|
|
}
|
|
|
|
void _reconcile() {
|
|
final isVisible = view.viewInsets.bottom > 0;
|
|
if (!_wasVisible && isVisible) onKeyboardShown();
|
|
if (_wasVisible && !isVisible) onKeyboardHidden();
|
|
_wasVisible = isVisible;
|
|
}
|
|
}
|
|
|
|
void _runComposerAction(VoidCallback action) {
|
|
unawaited(HapticFeedback.selectionClick());
|
|
action();
|
|
}
|
|
|
|
void _showComposerEmojiPicker(
|
|
BuildContext context,
|
|
ValueChanged<String> onSelect,
|
|
VoidCallback onDismiss,
|
|
) {
|
|
showEmojiPicker(
|
|
context: context,
|
|
onSelect: (emoji) => _runComposerAction(() => onSelect(emoji)),
|
|
onDismiss: onDismiss,
|
|
);
|
|
}
|
|
|
|
void _dismissComposerKeyboard(FocusNode focusNode) {
|
|
focusNode.unfocus();
|
|
unawaited(SystemChannels.textInput.invokeMethod<void>('TextInput.hide'));
|
|
}
|
|
|
|
void _chooseComposerAttachment(
|
|
BuildContext context,
|
|
ValueNotifier<_AttachmentSurface> attachmentSurface,
|
|
ValueNotifier<String?> uploadError,
|
|
Future<void> Function() choose, {
|
|
String? errorMessage,
|
|
}) {
|
|
attachmentSurface.value = _AttachmentSurface.closed;
|
|
unawaited(() async {
|
|
try {
|
|
await choose();
|
|
} catch (error) {
|
|
if (context.mounted) {
|
|
uploadError.value = errorMessage ?? _formatUploadError(error);
|
|
}
|
|
}
|
|
}());
|
|
}
|
|
|
|
Duration _composerMotionDuration(
|
|
bool reducedMotion,
|
|
_AttachmentSurface surface,
|
|
) => reducedMotion
|
|
? Duration.zero
|
|
: Duration(
|
|
milliseconds:
|
|
surface == _AttachmentSurface.camera ||
|
|
surface == _AttachmentSurface.photos
|
|
? 320
|
|
: 250,
|
|
);
|
|
|
|
void _expandComposer({
|
|
required BuildContext context,
|
|
required ValueNotifier<bool> isExpanded,
|
|
required ValueNotifier<_AttachmentSurface> attachmentSurface,
|
|
required VoidCallback? onFocusRequested,
|
|
required FocusNode focusNode,
|
|
required FlutterView view,
|
|
required ValueNotifier<bool> androidImeTransitionStarted,
|
|
required ObjectRef<Timer?> androidImeFallbackTimer,
|
|
}) {
|
|
if (isExpanded.value) return;
|
|
attachmentSurface.value = _AttachmentSurface.closed;
|
|
onFocusRequested?.call();
|
|
isExpanded.value = true;
|
|
// Attach the editor before requesting focus so native restoration cannot
|
|
// reopen a composer behind a popped route.
|
|
WidgetsBinding.instance.addPostFrameCallback((_) {
|
|
if (context.mounted && isExpanded.value) focusNode.requestFocus();
|
|
});
|
|
if (defaultTargetPlatform != TargetPlatform.android) return;
|
|
androidImeFallbackTimer.value?.cancel();
|
|
if (view.viewInsets.bottom > 0) {
|
|
androidImeTransitionStarted.value = true;
|
|
return;
|
|
}
|
|
androidImeTransitionStarted.value = false;
|
|
androidImeFallbackTimer.value = Timer(const Duration(milliseconds: 250), () {
|
|
if (context.mounted && isExpanded.value) {
|
|
androidImeTransitionStarted.value = true;
|
|
}
|
|
});
|
|
}
|
|
|
|
Widget _composerSuggestionPanel({
|
|
required List<Channel> channelSuggestions,
|
|
required List<MentionCandidate> mentionSuggestions,
|
|
required Set<String> unavailableMentions,
|
|
required bool mentionSearchFailed,
|
|
required bool reserveMentionHeight,
|
|
required bool mentionSearching,
|
|
required VoidCallback onMentionSearchRetry,
|
|
required Map<String, UserProfile> userCache,
|
|
required String? currentPubkey,
|
|
required bool isDmChannel,
|
|
required ValueChanged<Channel> onChannelSelect,
|
|
required ValueChanged<MentionCandidate> onMentionSelect,
|
|
}) => channelSuggestions.isNotEmpty
|
|
? KeyedSubtree(
|
|
key: const ValueKey('channel-suggestions'),
|
|
child: _ChannelSuggestions(
|
|
suggestions: channelSuggestions,
|
|
onSelect: onChannelSelect,
|
|
),
|
|
)
|
|
: mentionSuggestions.isNotEmpty || mentionSearchFailed
|
|
? KeyedSubtree(
|
|
key: const ValueKey('mention-suggestions'),
|
|
child: _MentionSuggestions(
|
|
suggestions: mentionSuggestions,
|
|
unavailable: unavailableMentions,
|
|
searchFailed: mentionSearchFailed,
|
|
reserveHeight: reserveMentionHeight,
|
|
searching: mentionSearching,
|
|
onRetry: onMentionSearchRetry,
|
|
userCache: userCache,
|
|
currentPubkey: currentPubkey,
|
|
isDmChannel: isDmChannel,
|
|
onSelect: onMentionSelect,
|
|
),
|
|
)
|
|
: const SizedBox.shrink(key: ValueKey('no-suggestions'));
|
|
|
|
Widget _composerAttachmentPanel({
|
|
required _AttachmentSurface surface,
|
|
required Widget suggestionPanel,
|
|
required VoidCallback onBack,
|
|
required VoidCallback onCamera,
|
|
required VoidCallback onPhotos,
|
|
required VoidCallback onVideo,
|
|
required VoidCallback onVoiceNote,
|
|
required VoidCallback onFiles,
|
|
required Future<void> Function(XFile image) onCapture,
|
|
required Future<List<XFile>> Function() onPickAllPhotos,
|
|
required Future<void> Function(List<XFile> photos) onChoosePhotos,
|
|
required Future<void> Function(List<XFile> photos) onChooseAllPhotos,
|
|
required Future<void> Function(Future<void> Function()) preparePhotos,
|
|
}) => _AttachmentSurfacePanel(
|
|
key: ValueKey(
|
|
surface == _AttachmentSurface.closed
|
|
? 'composer-suggestions'
|
|
: 'attachment-surface',
|
|
),
|
|
surface: surface,
|
|
suggestionPanel: suggestionPanel,
|
|
onBack: onBack,
|
|
onCamera: onCamera,
|
|
onPhotos: onPhotos,
|
|
onVideo: onVideo,
|
|
onVoiceNote: onVoiceNote,
|
|
onFiles: onFiles,
|
|
onCapture: onCapture,
|
|
onPickAllPhotos: onPickAllPhotos,
|
|
onChoosePhotos: onChoosePhotos,
|
|
onChooseAllPhotos: onChooseAllPhotos,
|
|
preparePhotos: preparePhotos,
|
|
);
|
|
|
|
const _pastedImageMimeTypes = <String>[
|
|
'image/jpeg',
|
|
'image/jpg',
|
|
'image/png',
|
|
'image/webp',
|
|
];
|
|
|
|
/// Walk backward from [cursor] looking for [trigger] (e.g. `@` or `#`) at a
|
|
/// word boundary. Returns the index of the trigger character, or `null` if none
|
|
/// is found.
|
|
///
|
|
/// When [stopAtSpace] is `true` the walk stops at both spaces and newlines —
|
|
/// appropriate for `#channel` names which are kebab-case slugs without spaces.
|
|
/// When `false`, only newlines stop the walk, allowing multi-word queries like
|
|
/// `@Alice Smith` to match members with multi-word display names.
|
|
@visibleForTesting
|
|
int? findTrigger(
|
|
String text,
|
|
int cursor,
|
|
String trigger, {
|
|
bool stopAtSpace = true,
|
|
}) {
|
|
for (var i = cursor - 1; i >= 0; i--) {
|
|
final ch = text[i];
|
|
if (ch == '\n') break;
|
|
if (stopAtSpace && ch == ' ') break;
|
|
if (ch == trigger) {
|
|
if (i == 0 || text[i - 1] == ' ' || text[i - 1] == '\n') {
|
|
return i;
|
|
}
|
|
break;
|
|
}
|
|
}
|
|
return null;
|
|
}
|
|
|
|
/// Replace the range `[start, cursor)` with [replacement] and move the cursor
|
|
/// to the end of the replacement. Used by both mention and channel insertion.
|
|
@visibleForTesting
|
|
void spliceAndMoveCursor(
|
|
TextEditingController controller,
|
|
FocusNode focusNode, {
|
|
required int start,
|
|
required String replacement,
|
|
}) {
|
|
final text = controller.text;
|
|
final cursor =
|
|
(controller.selection.isValid
|
|
? controller.selection.baseOffset
|
|
: text.length)
|
|
.clamp(start, text.length);
|
|
|
|
final before = text.substring(0, start);
|
|
final after = text.substring(cursor);
|
|
controller.value = TextEditingValue(
|
|
text: '$before$replacement$after',
|
|
selection: TextSelection.collapsed(offset: start + replacement.length),
|
|
);
|
|
focusNode.requestFocus();
|
|
}
|
|
|
|
/// Channel members as the send resolves typed names: loaded members, or the
|
|
/// cached roster while they load.
|
|
List<MentionCandidate> _typedMemberCandidates({
|
|
required AsyncValue<List<ChannelMember>> membersAsync,
|
|
required SessionStatus sessionStatus,
|
|
required List<ChannelMember> cachedMembers,
|
|
required Map<String, UserProfile> userCache,
|
|
required Map<String, String>? agentOwners,
|
|
}) => buildMentionCandidates(
|
|
members: channelMembersForAutocomplete(
|
|
membersAsync: membersAsync,
|
|
sessionStatus: sessionStatus,
|
|
cachedMembers: cachedMembers,
|
|
),
|
|
relayAgents: const [],
|
|
sharedChannelIds: const {},
|
|
userCache: userCache,
|
|
ownerByAgentPubkey: agentOwners ?? const {},
|
|
);
|
|
|
|
/// Qualify earlier namesake mentions outside code, keeping the cursor in
|
|
/// place, and rebind [mentions] before the text changes. A key with any
|
|
/// plain occurrence left, by the presence rule draft persistence uses (code
|
|
/// formatting ignored), stays bound beside its qualified label. Returns
|
|
/// [start] shifted by the edits before it. Call it before tracking the new
|
|
/// selection: persistence prunes keys absent from the text. [competitors] are
|
|
/// the typed member labels the send resolves: a longer one keeps its
|
|
/// occurrence instead of losing its prefix to a rename.
|
|
int _requalifyNamesakes(
|
|
_MarkdownEditingController controller,
|
|
Map<String, MentionCandidate> mentions,
|
|
MentionCandidate candidate,
|
|
int start,
|
|
Iterable<String> competitors,
|
|
) {
|
|
final renames = namesakeRequalifications(candidate.label, candidate.pubkey, {
|
|
for (final entry in mentions.entries) entry.key: entry.value.pubkey,
|
|
});
|
|
if (renames.isEmpty) return start;
|
|
final text = controller.text;
|
|
final cursor = controller.selection.isValid
|
|
? controller.selection.baseOffset
|
|
: text.length;
|
|
final code = controller._styledCodeRanges(text);
|
|
// Selected keys first, so an equal-length duplicate stays the selection's.
|
|
final selected = {for (final key in mentions.keys) key.toLowerCase()};
|
|
final labels = [
|
|
...mentions.keys,
|
|
...competitors.where((label) => !selected.contains(label.toLowerCase())),
|
|
];
|
|
final result = renameMentions(
|
|
text,
|
|
labels,
|
|
renames,
|
|
start,
|
|
// Exactly what the editor draws as code stays as typed.
|
|
excluded: (from, to) => code.any((c) => c.start < from && to < c.end),
|
|
);
|
|
// Backtick-adjacent code is no occurrence, but persistence still keeps it.
|
|
final remaining = mentionOccurrences(
|
|
result.text.replaceAll('`', ' '),
|
|
labels,
|
|
).map((range) => range.label).toSet().intersection(result.renamed);
|
|
for (final key in result.renamed) {
|
|
mentions[renames[key]!] =
|
|
result.kept.contains(key) || remaining.contains(key)
|
|
? mentions[key]!
|
|
: mentions.remove(key)!;
|
|
}
|
|
controller.value = TextEditingValue(
|
|
text: result.text,
|
|
selection: TextSelection.collapsed(offset: cursor + result.offset - start),
|
|
);
|
|
return result.offset;
|
|
}
|
|
|
|
/// Insert [trigger] (e.g. `@` or `#`) at the cursor position, prefixed with
|
|
/// a space if needed for word separation. Used by `triggerMention` and
|
|
/// `triggerChannel`.
|
|
void _insertTriggerAtCursor(
|
|
TextEditingController controller,
|
|
FocusNode focusNode,
|
|
String trigger,
|
|
) {
|
|
final text = controller.text;
|
|
final cursor = controller.selection.isValid
|
|
? controller.selection.baseOffset
|
|
: text.length;
|
|
final needsSpace =
|
|
cursor > 0 && text[cursor - 1] != ' ' && text[cursor - 1] != '\n';
|
|
final insert = needsSpace ? ' $trigger' : trigger;
|
|
final before = text.substring(0, cursor);
|
|
final after = text.substring(cursor);
|
|
controller.value = TextEditingValue(
|
|
text: '$before$insert$after',
|
|
selection: TextSelection.collapsed(offset: cursor + insert.length),
|
|
);
|
|
focusNode.requestFocus();
|
|
}
|
|
|
|
/// Outcome of the non-member mention prompt. `null` (dialog dismissed)
|
|
/// cancels the send and keeps the draft.
|
|
enum _NonMemberMentionChoice { invite, sendWithoutInviting }
|
|
|
|
/// User-facing text for a failed add or send.
|
|
String _composeSendErrorMessage(Object error) {
|
|
if (error is AddMembersException) return error.message;
|
|
return error.toString().replaceFirst('Exception: ', '');
|
|
}
|
|
|
|
/// Ask whether to invite mentioned humans who aren't channel members, or
|
|
/// send without inviting them. Mirrors desktop's `NonMemberMentionDialog`.
|
|
/// [canInvite] false (a private channel the sender doesn't own/administer)
|
|
/// drops the Invite action — the relay rejects that add, so offering it would
|
|
/// only produce an error.
|
|
Future<_NonMemberMentionChoice?> _promptNonMemberMention(
|
|
BuildContext context, {
|
|
required List<String> names,
|
|
required bool canInvite,
|
|
}) {
|
|
final verb = names.length == 1 ? 'is' : 'are';
|
|
return showBuzzDialog<_NonMemberMentionChoice>(
|
|
context: context,
|
|
builder: (dialogContext) => AlertDialog(
|
|
title: const Text('Mention people outside this channel?'),
|
|
content: Text(
|
|
canInvite
|
|
? '${names.join(', ')} $verb not in this channel. Invite them to '
|
|
'the channel, or send without inviting them.'
|
|
: '${names.join(', ')} $verb not in this channel. '
|
|
'$privateChannelAddDeniedMessage You can still send without '
|
|
'inviting them.',
|
|
),
|
|
actions: [
|
|
TextButton(
|
|
onPressed: () => Navigator.of(
|
|
dialogContext,
|
|
).pop(_NonMemberMentionChoice.sendWithoutInviting),
|
|
child: Text(canInvite ? 'Do nothing' : 'Send anyway'),
|
|
),
|
|
if (canInvite)
|
|
TextButton(
|
|
onPressed: () =>
|
|
Navigator.of(dialogContext).pop(_NonMemberMentionChoice.invite),
|
|
child: const Text('Invite'),
|
|
),
|
|
],
|
|
),
|
|
);
|
|
}
|
|
|
|
/// Send a typing indicator over the WebSocket (fire-and-forget).
|
|
///
|
|
/// Desktop sends these as `["EVENT", signedEvent]` over the WebSocket — not
|
|
/// via HTTP. Ephemeral events like typing indicators are broadcast-only and
|
|
/// the relay doesn't persist them, so the HTTP `/api/events` endpoint may
|
|
/// silently discard them.
|
|
void _sendTypingIndicator(
|
|
WidgetRef ref, {
|
|
required String channelId,
|
|
String? threadHeadId,
|
|
String? rootId,
|
|
}) {
|
|
try {
|
|
final config = ref.read(relayConfigProvider);
|
|
final nsec = config.nsec;
|
|
if (nsec == null || nsec.isEmpty) return;
|
|
|
|
final privkeyHex = nostr.Nip19.decode(payload: nsec).data;
|
|
if (privkeyHex.isEmpty) return;
|
|
|
|
final tags = <List<String>>[
|
|
['h', channelId],
|
|
if (threadHeadId != null && rootId != null && rootId != threadHeadId) ...[
|
|
['e', rootId, '', 'root'],
|
|
['e', threadHeadId, '', 'reply'],
|
|
] else if (threadHeadId != null)
|
|
['e', threadHeadId, '', 'reply'],
|
|
];
|
|
|
|
final event = signNostrEvent(
|
|
kind: EventKind.typingIndicator,
|
|
content: '',
|
|
tags: tags,
|
|
secretKey: privkeyHex,
|
|
);
|
|
|
|
// Send directly over WebSocket — fire-and-forget, matching desktop.
|
|
final session = ref.read(relaySessionProvider.notifier);
|
|
session.sendRaw(['EVENT', event.toMap()]);
|
|
} catch (_) {
|
|
// Fire-and-forget — typing indicator failure is non-fatal.
|
|
}
|
|
}
|
|
|
|
/// Reports a send that was cancelled because the active community changed.
|
|
///
|
|
/// The send path is fire-and-forget, so a `StateError` escaping it would be
|
|
/// silent. The composer's own error line cannot carry this message either: the
|
|
/// identity change that causes the failure also resets that state on the next
|
|
/// frame, so [messenger] must be resolved before the send's first `await`.
|
|
void _reportSendCancelledByCommunitySwitch(ScaffoldMessengerState? messenger) {
|
|
messenger?.showFeedbackSnackBar(
|
|
const SnackBar(content: Text('Not sent. Community changed.')),
|
|
kind: ToastKind.error,
|
|
);
|
|
}
|
|
|
|
/// What an add attempt left undone: who is still a non-member, and why.
|
|
@immutable
|
|
class _NonMemberAddOutcome {
|
|
final List<String> notAdded;
|
|
final List<String> errors;
|
|
|
|
const _NonMemberAddOutcome({required this.notAdded, required this.errors});
|
|
|
|
static const empty = _NonMemberAddOutcome(notAdded: [], errors: []);
|
|
}
|
|
|
|
/// Adds mentioned non-members to the channel before a send.
|
|
///
|
|
/// Agents are added silently with the `bot` role; humans are only passed here
|
|
/// after they have been explicitly invited from the mention prompt.
|
|
///
|
|
/// A rejection is reported, never thrown: the send is fire-and-forget, so an
|
|
/// escaping error would drop the message with nothing shown. [StateError] still
|
|
/// propagates — a community switch must cancel the whole send.
|
|
Future<_NonMemberAddOutcome> _addMentionedNonMembers(
|
|
ChannelActions channelActions, {
|
|
required String channelId,
|
|
required List<String> agentPubkeys,
|
|
required List<String> humanPubkeys,
|
|
required bool canAddMembers,
|
|
}) async {
|
|
final pending = [
|
|
if (agentPubkeys.isNotEmpty) (agentPubkeys, 'bot'),
|
|
if (humanPubkeys.isNotEmpty) (humanPubkeys, 'member'),
|
|
];
|
|
if (pending.isEmpty) return _NonMemberAddOutcome.empty;
|
|
|
|
// A non-member cannot add anyone to a private channel: skip the doomed
|
|
// kind:9000 rather than trading it for a relay rejection.
|
|
if (!canAddMembers) {
|
|
return _NonMemberAddOutcome(
|
|
notAdded: [for (final (pubkeys, _) in pending) ...pubkeys],
|
|
errors: const [privateChannelAddDeniedMessage],
|
|
);
|
|
}
|
|
|
|
final notAdded = <String>[];
|
|
final errors = <String>[];
|
|
for (final (pubkeys, role) in pending) {
|
|
try {
|
|
await channelActions.addMembers(
|
|
channelId: channelId,
|
|
pubkeys: pubkeys,
|
|
role: role,
|
|
);
|
|
} on StateError {
|
|
rethrow;
|
|
} catch (error) {
|
|
notAdded.addAll(
|
|
error is AddMembersException ? error.failures.keys : pubkeys,
|
|
);
|
|
errors.add(_composeSendErrorMessage(error));
|
|
}
|
|
}
|
|
return _NonMemberAddOutcome(notAdded: notAdded, errors: errors);
|
|
}
|
|
|
|
/// Mentioned identities that aren't in the channel yet, plus whether the sender
|
|
/// is allowed to add them at all.
|
|
@immutable
|
|
class _NonMemberMentionScan {
|
|
final String channelId;
|
|
|
|
/// Mentioned people and agents outside the channel, in draft order.
|
|
final List<MentionCandidate> outside;
|
|
final bool canAddMembers;
|
|
|
|
/// Whether the destination is a DM. Nobody can be added to a DM, so its
|
|
/// outside people are sent as references without a prompt.
|
|
final bool isDm;
|
|
|
|
const _NonMemberMentionScan({
|
|
required this.channelId,
|
|
required this.outside,
|
|
required this.canAddMembers,
|
|
required this.isDm,
|
|
});
|
|
}
|
|
|
|
/// Resolves which mentioned identities are non-members, and whether this
|
|
/// identity may add them (see [Channel.canAddMembers]). A DM's participant set
|
|
/// is fixed at creation, so nobody outside it can be added.
|
|
Future<_NonMemberMentionScan> _scanNonMemberMentions(
|
|
WidgetRef ref, {
|
|
required String channelId,
|
|
required List<MentionCandidate> selectedMentions,
|
|
required String? currentPubkey,
|
|
}) async {
|
|
final none = _NonMemberMentionScan(
|
|
channelId: channelId,
|
|
outside: const [],
|
|
canAddMembers: true,
|
|
isDm: false,
|
|
);
|
|
if (selectedMentions.isEmpty) return none;
|
|
|
|
// A DM opened ahead of a reloading list is found without waiting for it.
|
|
final channel =
|
|
ref.read(channelsProvider.notifier).channelById(channelId) ??
|
|
(await ref.read(
|
|
channelsProvider.future,
|
|
)).firstWhere((candidate) => candidate.id == channelId);
|
|
|
|
// A DM decides who is inside it the way its send does: by current
|
|
// membership, or by the channel metadata when membership is unavailable.
|
|
// A channel needs its membership; a failure here reaches the send, which
|
|
// reports it and keeps the draft.
|
|
List<ChannelMember> members;
|
|
if (channel.isDm) {
|
|
try {
|
|
members = await ref.read(channelMembersProvider(channelId).future);
|
|
} catch (_) {
|
|
members = const [];
|
|
}
|
|
} else {
|
|
members = await ref.read(channelMembersProvider(channelId).future);
|
|
}
|
|
final memberPubkeys = {
|
|
if (channel.isDm)
|
|
for (final pubkey in dmParticipantPubkeys(channel, members))
|
|
pubkey.toLowerCase()
|
|
else
|
|
for (final member in members) member.pubkey.toLowerCase(),
|
|
};
|
|
String? selfRole;
|
|
if (currentPubkey != null) {
|
|
final self = currentPubkey.toLowerCase();
|
|
for (final member in members) {
|
|
if (member.pubkey.toLowerCase() == self) {
|
|
selfRole = member.role;
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
|
|
final outside = <MentionCandidate>[];
|
|
final seen = <String>{};
|
|
for (final candidate in selectedMentions) {
|
|
final pubkey = candidate.pubkey.toLowerCase();
|
|
if (memberPubkeys.contains(pubkey) || !seen.add(pubkey)) continue;
|
|
outside.add(candidate);
|
|
}
|
|
|
|
return _NonMemberMentionScan(
|
|
channelId: channelId,
|
|
outside: outside,
|
|
canAddMembers: channel.canAddMembers(selfRole),
|
|
isDm: channel.isDm,
|
|
);
|
|
}
|
|
|
|
/// The p-tags and `mention` reference tags an outgoing message should carry.
|
|
///
|
|
/// Anyone who ends up *not* added is demoted from a p-tag to a reference tag so
|
|
/// their name still renders without notifying a non-member — mirrors desktop's
|
|
/// `mergeOutgoingTagsWithReferenceMentions`.
|
|
class _OutgoingMentions {
|
|
List<String> pubkeys;
|
|
final List<List<String>> referenceTags = [];
|
|
List<MentionCandidate> _invited = const [];
|
|
|
|
_OutgoingMentions(List<MentionCandidate> selectedMentions)
|
|
: pubkeys = LinkedHashSet<String>.from(
|
|
selectedMentions.map((candidate) => candidate.pubkey.toLowerCase()),
|
|
).toList();
|
|
|
|
void demote(Iterable<String> demoted) {
|
|
final excluded = {for (final pubkey in demoted) pubkey.toLowerCase()};
|
|
if (excluded.isEmpty) return;
|
|
pubkeys = [
|
|
for (final pubkey in pubkeys)
|
|
if (!excluded.contains(pubkey)) pubkey,
|
|
];
|
|
referenceTags.addAll([
|
|
for (final pubkey in excluded) ['mention', pubkey],
|
|
]);
|
|
}
|
|
|
|
/// Applies the mention prompt's outcome: invite everyone outside, or send
|
|
/// with them as references. Agents and people are treated the same.
|
|
void resolveOutsideChoice(
|
|
_NonMemberMentionChoice choice,
|
|
List<MentionCandidate> outside,
|
|
) {
|
|
switch (choice) {
|
|
case _NonMemberMentionChoice.invite:
|
|
_invited = outside;
|
|
case _NonMemberMentionChoice.sendWithoutInviting:
|
|
demote([for (final candidate in outside) candidate.pubkey]);
|
|
}
|
|
}
|
|
|
|
/// Adds the scanned non-members, demoting and reporting whatever didn't land.
|
|
Future<void> addNonMembers(
|
|
ChannelActions channelActions, {
|
|
required _NonMemberMentionScan scan,
|
|
required ScaffoldMessengerState? messenger,
|
|
}) async {
|
|
final outcome = await _addMentionedNonMembers(
|
|
channelActions,
|
|
channelId: scan.channelId,
|
|
agentPubkeys: [
|
|
for (final candidate in _invited)
|
|
if (candidate.isAgent) candidate.pubkey.toLowerCase(),
|
|
],
|
|
humanPubkeys: [
|
|
for (final candidate in _invited)
|
|
if (!candidate.isAgent) candidate.pubkey.toLowerCase(),
|
|
],
|
|
canAddMembers: scan.canAddMembers,
|
|
);
|
|
demote(outcome.notAdded);
|
|
if (outcome.errors.isNotEmpty) {
|
|
messenger?.showFeedbackSnackBar(
|
|
SnackBar(content: Text(outcome.errors.join(' '))),
|
|
kind: ToastKind.error,
|
|
);
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Insert an emoji at the cursor without replacing the draft.
|
|
void _insertComposerEmoji(
|
|
TextEditingController controller,
|
|
FocusNode focusNode,
|
|
String emoji,
|
|
) {
|
|
final text = controller.text;
|
|
final selection = controller.selection;
|
|
final cursor = selection.isValid
|
|
? selection.baseOffset.clamp(0, text.length)
|
|
: text.length;
|
|
controller.value = TextEditingValue(
|
|
text: text.replaceRange(cursor, cursor, emoji),
|
|
selection: TextSelection.collapsed(offset: cursor + emoji.length),
|
|
);
|
|
focusNode.requestFocus();
|
|
}
|
|
|
|
// Wrap or insert markdown formatting around the current selection.
|
|
void _applyComposerFormat(
|
|
TextEditingController controller,
|
|
FocusNode focusNode,
|
|
ObjectRef<bool> isModifyingText,
|
|
String prefix,
|
|
String? suffix,
|
|
) {
|
|
suffix ??= prefix;
|
|
final text = controller.text;
|
|
final sel = controller.selection;
|
|
if (!sel.isValid) return;
|
|
|
|
isModifyingText.value = true;
|
|
try {
|
|
if (sel.isCollapsed) {
|
|
final offset = sel.baseOffset;
|
|
final updated =
|
|
'${text.substring(0, offset)}$prefix$suffix${text.substring(offset)}';
|
|
controller.text = updated;
|
|
controller.selection = TextSelection.collapsed(
|
|
offset: offset + prefix.length,
|
|
);
|
|
} else {
|
|
final selected = text.substring(sel.start, sel.end);
|
|
final updated =
|
|
'${text.substring(0, sel.start)}$prefix$selected$suffix${text.substring(sel.end)}';
|
|
controller.text = updated;
|
|
controller.selection = TextSelection.collapsed(
|
|
offset: sel.start + prefix.length + selected.length + suffix.length,
|
|
);
|
|
}
|
|
} finally {
|
|
isModifyingText.value = false;
|
|
}
|
|
focusNode.requestFocus();
|
|
}
|