fix(mobile): offer the mention chooser while editing a message

The edit sheet was a plain text field: typing ` cc @bo` opened nothing,
and the only way to mention someone from an edit was to type the name
exactly (scenario 08). The sheet now mounts the composer's `@` chooser
with the same rules, as buzz-app's edit box does (recommendation 9):
the same trigger, ranking, folded matching, directory search, Space and
closing-punctuation selection, suffix boundary, chip binding and focus
handling. A pick inserts the same bound `@Label` chip, and the message's
existing mentions open as chips, each bound to the person its tags name
(`@Name` or `@Name (<key>)` for exactly one tagged person; a name two
tagged people share stays text).

An edit replaces prose only, following buzz-app's edit rule: the saved
edit event carries the tags the edit path wrote before (`h`, `e` and the
custom-emoji tags) and never a `p` tag for a pick, so nobody is notified
from an edit. Save, Cancel and the sheet layout are otherwise unchanged;
the body scrolls so the field, the chooser and the keyboard fit together
on a small phone. A hardware Enter keeps inserting a newline while no
chooser row is shown.

The chooser's state moves out of the composer widget into a shared
`_useMentionChooser` hook in `mention_chooser.dart` (query, opening,
shown rows, chip insertion and the per-edit tracking that also performs
terminator selection); the composer and the new `message_edit_sheet.dart`
part both use it, so no rule is copied. The hook exposes the live query
for hardware keys that arrive before the next frame. The hardware-key
helper takes an optional `send`, which the edit sheet leaves out.

Tests: a new edit sheet journey opens a message with an existing Alice
mention and sees her chip, types `@bo` and taps Bob into a chip, sees the
chooser leave and return with the field's focus, selects `@alice,` with a
comma, picks Quinn from a directory search, and saves content with the
picks and no `p` tag; an unchanged or emptied edit saves nothing; and the
sheet fits a small phone with the keyboard and the chooser open. The
journey fails when the sheet stops tracking the query or stops seeding
chips. `dart format`, `flutter analyze`, `just file-size-check` and the
full mobile `flutter test` suite pass.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Signed-off-by: Matt Toohey <contact@matttoohey.com>
This commit is contained in:
Matt Toohey
2026-11-19 13:18:34 +11:00
parent e008151c6c
commit 1996069693
7 changed files with 829 additions and 203 deletions

View File

@@ -89,6 +89,7 @@ part 'compose_bar/hardware_keyboard.dart';
part 'compose_bar/dock.dart'; part 'compose_bar/dock.dart';
part 'compose_bar/share_delivery.dart'; part 'compose_bar/share_delivery.dart';
part 'compose_bar/compose_bar_widget.dart'; part 'compose_bar/compose_bar_widget.dart';
part 'compose_bar/message_edit_sheet.dart';
/// Callback used by channels and threads to submit composer content. /// Callback used by channels and threads to submit composer content.
typedef ComposeBarOnSend = typedef ComposeBarOnSend =

View File

@@ -200,22 +200,6 @@ class ComposeBar extends HookConsumerWidget {
clipboardHasImage: clipboardHasImage, clipboardHasImage: clipboardHasImage,
); );
// Mention state --------------------------------------------------------
final mentionQuery = useState<String?>(null);
final mentionStartIdx = useState(-1);
// Counts chooser openings: a new `@` starts fresh rows and searches.
final mentionOpening = useRef(0);
final shownMentions = useRef<_MentionRows>((
rows: const [],
unavailable: const {},
searchFailed: false,
reserveHeight: false,
searching: false,
));
// Map of displayName → selected mention candidate built as the user selects
// mentions. Used to pass resolved pubkeys directly to onSend and to attach
// selected non-member agents before the message is published.
// Channel autocomplete state ---------------------------------------------- // Channel autocomplete state ----------------------------------------------
final channelQuery = useState<String?>(null); final channelQuery = useState<String?>(null);
final channelStartIdx = useState(-1); final channelStartIdx = useState(-1);
@@ -295,33 +279,16 @@ class ComposeBar extends HookConsumerWidget {
final isModifyingText = useRef(false); final isModifyingText = useRef(false);
final lastObservedEditingValue = useRef(controller.value); final lastObservedEditingValue = useRef(controller.value);
// Insert a selected mention into the text field as a chip bound to it, // The `@` chooser: query, rows and chip insertion, shared with the
// followed by a space or by the closing punctuation that selected it. // message edit sheet.
void insertMention(MentionCandidate candidate, {String separator = ' '}) { final mentionChooser = _useMentionChooser(
ref ref,
.read(mentionHistoryProvider.notifier) channelId: channelId,
.remember(channelId, candidate.pubkey); controller: controller,
final text = controller.text; focusNode: focusNode,
final start = mentionStartIdx.value.clamp(0, text.length); isModifyingText: isModifyingText,
final cursor = viewer: currentPubkey,
(controller.selection.isValid );
? controller.selection.baseOffset
: text.length)
.clamp(start, text.length);
isModifyingText.value = true;
try {
controller.insertMention(
start: start,
end: cursor,
candidate: candidate,
separator: separator,
);
} finally {
isModifyingText.value = false;
}
focusNode.requestFocus();
mentionQuery.value = null;
}
_useAgentMentionPrefill( _useAgentMentionPrefill(
ref: ref, ref: ref,
@@ -360,74 +327,21 @@ class ComposeBar extends HookConsumerWidget {
} }
} }
if (!sel.isValid || !sel.isCollapsed) { // Channel autocomplete detection — only when no @mention is active.
mentionQuery.value = null; if (mentionChooser.track(previousValue, editingValue) ||
!sel.isValid ||
!sel.isCollapsed ||
sel.baseOffset < 1) {
channelQuery.value = null; channelQuery.value = null;
return; return;
} }
final cursor = sel.baseOffset; final cursor = sel.baseOffset;
if (cursor < 1) { final hashPos = findTrigger(text, cursor, '#');
mentionQuery.value = null; if (hashPos != null) {
channelQuery.value = null; channelQuery.value = text
return; .substring(hashPos + 1, cursor)
} .toLowerCase();
channelStartIdx.value = hashPos;
var open = findMentionQuery(text, cursor);
if (open != null &&
_startsSelectedMention(controller.mentions, open.start)) {
open = null;
}
// Space or closing punctuation typed straight after an exact, unique
// name selects it (section 5); the typed character stays after the
// chip. Otherwise the character joins the query.
final previousQuery = mentionQuery.value;
if (open != null &&
previousQuery != null &&
previousQuery.trim().isNotEmpty &&
open.start == mentionStartIdx.value &&
open.query.length == previousQuery.length + 1 &&
open.query.startsWith(previousQuery) &&
text.length == previousValue.text.length + 1) {
final typed = open.query.substring(previousQuery.length);
final chosen = mentionTerminator(typed)
? _spaceMention(
ref,
channelId: channelId,
query: previousQuery,
opening: mentionOpening.value,
shown: shownMentions.value,
viewer: currentPubkey,
)
: null;
if (chosen != null) {
insertMention(chosen, separator: typed);
return;
}
}
if (open != null) {
if (previousQuery == null || mentionStartIdx.value != open.start) {
mentionOpening.value++;
}
mentionQuery.value = open.query;
mentionStartIdx.value = open.start;
channelQuery.value = null;
} else {
mentionQuery.value = null;
}
// Channel autocomplete detection — only when no @mention is active.
if (mentionQuery.value == null) {
final hashPos = findTrigger(text, cursor, '#');
if (hashPos != null) {
channelQuery.value = text
.substring(hashPos + 1, cursor)
.toLowerCase();
channelStartIdx.value = hashPos;
} else {
channelQuery.value = null;
}
} else { } else {
channelQuery.value = null; channelQuery.value = null;
} }
@@ -437,25 +351,9 @@ class ComposeBar extends HookConsumerWidget {
return () => controller.removeListener(listener); return () => controller.removeListener(listener);
}, [controller]); }, [controller]);
// Ranked mention rows; shown rows hold still while the query stays. final mentionRows = mentionChooser.rows;
final mentionRows = _useMentionRows(
ref,
channelId: channelId,
query: mentionQuery.value,
opening: mentionOpening.value,
);
shownMentions.value = mentionRows;
final suggestions = mentionRows.rows; final suggestions = mentionRows.rows;
// Resolve owner names for the visible "managed by …" subtitles.
useEffect(() {
final ownerPubkeys = [for (final s in suggestions) ?s.ownerPubkey];
if (ownerPubkeys.isNotEmpty) {
ref.read(userCacheProvider.notifier).preload(ownerPubkeys);
}
return null;
}, [suggestions.length, mentionQuery.value]);
// Filter channels against the query. // Filter channels against the query.
final channels = channelsAsync.asData?.value ?? <Channel>[]; final channels = channelsAsync.asData?.value ?? <Channel>[];
final channelSuggestions = filterChannels(channels, channelQuery.value); final channelSuggestions = filterChannels(channels, channelQuery.value);
@@ -490,7 +388,7 @@ class ComposeBar extends HookConsumerWidget {
draftRevision.value += 1; draftRevision.value += 1;
controller.replaceDraft(TextEditingValue.empty, mentions: const []); controller.replaceDraft(TextEditingValue.empty, mentions: const []);
attachments.value = []; attachments.value = [];
mentionQuery.value = null; mentionChooser.close();
channelQuery.value = null; channelQuery.value = null;
attachmentSurface.value = _AttachmentSurface.closed; attachmentSurface.value = _AttachmentSurface.closed;
showFormatting.value = false; showFormatting.value = false;
@@ -1001,19 +899,20 @@ class ComposeBar extends HookConsumerWidget {
final topMention = suggestions final topMention = suggestions
.where((s) => !mentionRows.unavailable.contains(s.pubkey)) .where((s) => !mentionRows.unavailable.contains(s.pubkey))
.firstOrNull; .firstOrNull;
final pickerQuery = (mentionQuery.value, channelQuery.value); final pickerQuery = (mentionChooser.query, channelQuery.value);
KeyEventResult handleHardwareKey(FocusNode _, KeyEvent event) => KeyEventResult handleHardwareKey(FocusNode _, KeyEvent event) =>
_handleComposerHardwareKey( _handleComposerHardwareKey(
event, event,
controller, controller,
inputOwned: iosAttachmentPopover.isActive || isEmojiPickerOpen.value, inputOwned: iosAttachmentPopover.isActive || isEmojiPickerOpen.value,
query: (mentionQuery.value, channelQuery.value), query: (mentionChooser.liveQuery.value, channelQuery.value),
renderedQuery: pickerQuery, renderedQuery: pickerQuery,
pickerVisible: pickerVisible, pickerVisible: pickerVisible,
acceptSuggestion: topChannel != null acceptSuggestion: topChannel != null
? () => _runComposerAction(() => insertChannel(topChannel)) ? () => _runComposerAction(() => insertChannel(topChannel))
: topMention != null : topMention != null
? () => _runComposerAction(() => insertMention(topMention)) ? () =>
_runComposerAction(() => mentionChooser.insert(topMention))
: null, : null,
send: () async { send: () async {
if (attachmentSurface.value != _AttachmentSurface.closed) return; if (attachmentSurface.value != _AttachmentSurface.closed) return;
@@ -1029,14 +928,15 @@ class ComposeBar extends HookConsumerWidget {
reserveMentionHeight: mentionRows.reserveHeight, reserveMentionHeight: mentionRows.reserveHeight,
mentionSearching: mentionRows.searching, mentionSearching: mentionRows.searching,
onMentionSearchRetry: () { onMentionSearchRetry: () {
final query = mentionQuery.value; if (mentionChooser.query case final query?) {
if (query != null) ref.invalidate(mentionUserSearchProvider(query)); ref.invalidate(mentionUserSearchProvider(query));
}
}, },
userCache: userCache, userCache: userCache,
currentPubkey: currentPubkey, currentPubkey: currentPubkey,
isDmChannel: isDmChannel, isDmChannel: isDmChannel,
onChannelSelect: insertChannel, onChannelSelect: insertChannel,
onMentionSelect: insertMention, onMentionSelect: mentionChooser.insert,
); );
Widget buildOverlayPanel(_AttachmentSurface surface) { Widget buildOverlayPanel(_AttachmentSurface surface) {
return _composerAttachmentPanel( return _composerAttachmentPanel(

View File

@@ -3,7 +3,9 @@ part of '../compose_bar.dart';
// Hardware keyboards only: software Return keeps its newline. While the // Hardware keyboards only: software Return keeps its newline. While the
// suggestion picker is shown, Tab and Enter accept its first selectable row // suggestion picker is shown, Tab and Enter accept its first selectable row
// (or do nothing when it has none); otherwise Enter sends and Tab traverses. // (or do nothing when it has none); otherwise Enter sends and Tab traverses.
// Shift+Enter leaves newline handling to the field. // Shift+Enter leaves newline handling to the field. An editor with no
// [send], such as the message edit sheet, keeps Enter as a newline whenever
// the picker is not shown.
KeyEventResult _handleComposerHardwareKey( KeyEventResult _handleComposerHardwareKey(
KeyEvent event, KeyEvent event,
TextEditingController controller, { TextEditingController controller, {
@@ -12,7 +14,7 @@ KeyEventResult _handleComposerHardwareKey(
required (String?, String?) renderedQuery, required (String?, String?) renderedQuery,
required bool pickerVisible, required bool pickerVisible,
required VoidCallback? acceptSuggestion, required VoidCallback? acceptSuggestion,
required Future<void> Function() send, required Future<void> Function()? send,
}) { }) {
if (inputOwned) return KeyEventResult.handled; if (inputOwned) return KeyEventResult.handled;
// A new query must render its own rows before a key can select one. // A new query must render its own rows before a key can select one.
@@ -50,10 +52,11 @@ KeyEventResult _handleComposerHardwareKey(
event.physicalKey != PhysicalKeyboardKey.numpadEnter) { event.physicalKey != PhysicalKeyboardKey.numpadEnter) {
return KeyEventResult.ignored; return KeyEventResult.ignored;
} }
if (!pickerVisible && send == null) return KeyEventResult.ignored;
if (event is KeyDownEvent) { if (event is KeyDownEvent) {
if (pickerVisible) { if (pickerVisible) {
acceptSuggestion?.call(); acceptSuggestion?.call();
} else { } else if (send != null) {
unawaited(send()); unawaited(send());
} }
} }

View File

@@ -80,3 +80,170 @@ MentionCandidate? _spaceMention(
if (key == null || shown.unavailable.contains(key)) return null; if (key == null || shown.unavailable.contains(key)) return null;
return shown.rows.where((row) => row.pubkey == key).firstOrNull; return shown.rows.where((row) => row.pubkey == key).firstOrNull;
} }
const _noMentionRows = (
rows: <MentionCandidate>[],
unavailable: <String>{},
searchFailed: false,
reserveHeight: false,
searching: false,
);
/// One editor's `@` chooser: the open query, its shown rows, and the chip a
/// pick or a typed terminator inserts. The composer and the message edit
/// sheet share it, so both follow the same trigger, ranking, search,
/// selection and binding rules.
class _MentionChooser {
/// The open query after its `@`, or null while no chooser is open, as
/// of this build.
final String? query;
/// The query as it is now, ahead of the next frame: a hardware key can
/// arrive after an edit changed the query but before its rows rendered.
final ValueListenable<String?> liveQuery;
final _MentionRows rows;
/// Replaces the open query with a chip bound to [candidate], followed by
/// [separator]: a space, or the closing punctuation that selected it.
final void Function(MentionCandidate candidate, {String separator}) insert;
/// Closes the chooser; the text is untouched.
final VoidCallback close;
/// Follows one editor change. Returns true while a query is open after
/// it, or when the typed character selected a name and the text changed;
/// false when the caret is not at a query.
final bool Function(TextEditingValue previous, TextEditingValue current)
track;
const _MentionChooser({
required this.query,
required this.liveQuery,
required this.rows,
required this.insert,
required this.close,
required this.track,
});
}
_MentionChooser _useMentionChooser(
WidgetRef ref, {
required String channelId,
required _MarkdownEditingController controller,
required FocusNode focusNode,
required ObjectRef<bool> isModifyingText,
required String? viewer,
}) {
final query = useState<String?>(null);
final startIdx = useState(-1);
// Counts chooser openings: a new `@` starts fresh rows and searches.
final opening = useRef(0);
final shown = useRef<_MentionRows>(_noMentionRows);
final viewerRef = useRef(viewer)..value = viewer;
void insert(MentionCandidate candidate, {String separator = ' '}) {
ref
.read(mentionHistoryProvider.notifier)
.remember(channelId, candidate.pubkey);
final text = controller.text;
final start = startIdx.value.clamp(0, text.length);
final cursor =
(controller.selection.isValid
? controller.selection.baseOffset
: text.length)
.clamp(start, text.length);
isModifyingText.value = true;
try {
controller.insertMention(
start: start,
end: cursor,
candidate: candidate,
separator: separator,
);
} finally {
isModifyingText.value = false;
}
focusNode.requestFocus();
query.value = null;
}
bool track(TextEditingValue previous, TextEditingValue current) {
final text = current.text;
final sel = current.selection;
if (!sel.isValid || !sel.isCollapsed || sel.baseOffset < 1) {
query.value = null;
return false;
}
var open = findMentionQuery(text, sel.baseOffset);
if (open != null &&
_startsSelectedMention(controller.mentions, open.start)) {
open = null;
}
// Space or closing punctuation typed straight after an exact, unique
// name selects it (section 5); the typed character stays after the
// chip. Otherwise the character joins the query.
final previousQuery = query.value;
if (open != null &&
previousQuery != null &&
previousQuery.trim().isNotEmpty &&
open.start == startIdx.value &&
open.query.length == previousQuery.length + 1 &&
open.query.startsWith(previousQuery) &&
text.length == previous.text.length + 1) {
final typed = open.query.substring(previousQuery.length);
final chosen = mentionTerminator(typed)
? _spaceMention(
ref,
channelId: channelId,
query: previousQuery,
opening: opening.value,
shown: shown.value,
viewer: viewerRef.value,
)
: null;
if (chosen != null) {
insert(chosen, separator: typed);
return true;
}
}
if (open == null) {
query.value = null;
return false;
}
if (previousQuery == null || startIdx.value != open.start) {
opening.value++;
}
query.value = open.query;
startIdx.value = open.start;
return true;
}
// Ranked rows; shown rows hold still while the query stays.
final rows = _useMentionRows(
ref,
channelId: channelId,
query: query.value,
opening: opening.value,
);
shown.value = rows;
// Resolve owner names for the visible "managed by …" subtitles.
useEffect(() {
final ownerPubkeys = [for (final s in rows.rows) ?s.ownerPubkey];
if (ownerPubkeys.isNotEmpty) {
ref.read(userCacheProvider.notifier).preload(ownerPubkeys);
}
return null;
}, [rows.rows.length, query.value]);
return _MentionChooser(
query: query.value,
liveQuery: query,
rows: rows,
insert: insert,
close: () => query.value = null,
track: track,
);
}

View File

@@ -0,0 +1,340 @@
part of '../compose_bar.dart';
/// Opens the sheet that edits the text of [message] in [channelId].
///
/// The sheet offers the composer's `@` chooser with the same rules, and a
/// pick inserts the same bound chip. An edit replaces prose only: the saved
/// edit event carries the tags the edit path writes today and never a `p`
/// tag for the pick, so nobody is notified from an edit (buzz-app's edit
/// rule; project recommendation 9). The message's existing mentions open
/// as chips.
void showMessageEditSheet({
required BuildContext context,
required TimelineMessage message,
required String channelId,
}) {
showBuzzModalBottomSheet<void>(
context: context,
isScrollControlled: true,
showDragHandle: true,
builder: (_) => _MessageEditSheet(message: message, channelId: channelId),
);
}
class _MessageEditSheet extends HookConsumerWidget {
final TimelineMessage message;
final String channelId;
const _MessageEditSheet({required this.message, required this.channelId});
@override
Widget build(BuildContext context, WidgetRef ref) {
final controller = useMemoized(_MarkdownEditingController.new);
useEffect(() => controller.dispose, [controller]);
final focusNode = useFocusNode();
final isModifyingText = useRef(false);
final lastObservedEditingValue = useRef(controller.value);
final mentions = useListenableSelector(
controller,
() => controller.mentions,
);
final currentPubkey = ref.watch(currentPubkeyProvider);
final userCache = ref.watch(userCacheProvider);
final channelsAsync = ref.watch(channelsProvider);
final membersAsync = ref.watch(channelMembersProvider(channelId));
final sessionStatus = ref.watch(relaySessionProvider).status;
final cachedMembers = channelsAsync.asData == null
? const <ChannelMember>[]
: ref
.read(channelsProvider.notifier)
.cachedMembersForChannel(channelId);
final agentOwners = ref.watch(agentOwnersProvider).asData?.value;
final channel = ref.watch(channelByIdProvider(channelId));
List<MentionCandidate> memberCandidates() => _typedMemberCandidates(
membersAsync: membersAsync,
sessionStatus: sessionStatus,
cachedMembers: cachedMembers,
userCache: userCache,
agentOwners: agentOwners,
);
_useMentionChipQualifiers(
ref: ref,
controller: controller,
mentions: mentions,
members: memberCandidates,
memberKeys: [
membersAsync.asData?.value,
cachedMembers,
userCache,
agentOwners,
],
);
// The message's existing mentions, as the bubble names them, open as
// chips. Names can arrive after the sheet (a profile still loading), so
// the chips are brought up to date while the text is still the original.
final seeded = _editedMessageMentions(
message,
names: _editedMentionNames(
ref,
message: message,
channelId: channelId,
userCache: userCache,
members: channelMembersForAutocomplete(
membersAsync: membersAsync,
sessionStatus: sessionStatus,
cachedMembers: cachedMembers,
),
),
agentPubkeys: ref.watch(agentMentionPubkeysProvider(channelId)),
members: memberCandidates(),
);
final seededKey = [
for (final m in seeded) '${m.start}:${m.end}:${m.pubkey}',
].join(',');
useEffect(() {
final text = message.content;
if (controller.text.isNotEmpty && controller.text != text) return null;
final bound = [for (final m in controller.mentions) (m.range, m.pubkey)];
if (controller.text == text &&
listEquals(bound, [for (final m in seeded) (m.range, m.pubkey)])) {
return null;
}
isModifyingText.value = true;
try {
controller.replaceDraft(
TextEditingValue(
text: text,
selection: controller.selection.isValid
? controller.selection
: TextSelection.collapsed(offset: text.length),
),
mentions: seeded,
);
} finally {
isModifyingText.value = false;
}
return null;
}, [controller, seededKey]);
final chooser = _useMentionChooser(
ref,
channelId: channelId,
controller: controller,
focusNode: focusNode,
isModifyingText: isModifyingText,
viewer: currentPubkey,
);
useEffect(() {
lastObservedEditingValue.value = controller.value;
void listener() {
final editingValue = controller.value;
final previousValue = lastObservedEditingValue.value;
lastObservedEditingValue.value = editingValue;
if (isModifyingText.value || editingValue == previousValue) return;
chooser.track(previousValue, editingValue);
}
controller.addListener(listener);
return () => controller.removeListener(listener);
}, [controller]);
// The chooser belongs to the focused field (recommendation 8).
final chooserOpen = useListenable(focusNode).hasFocus;
final rows = chooser.rows;
final suggestions = chooserOpen ? rows.rows : const <MentionCandidate>[];
final searchFailed = chooserOpen && rows.searchFailed;
final pickerVisible = suggestions.isNotEmpty || searchFailed;
final topMention = suggestions
.where((s) => !rows.unavailable.contains(s.pubkey))
.firstOrNull;
final pickerQuery = (chooser.query, null);
KeyEventResult handleHardwareKey(FocusNode _, KeyEvent event) =>
_handleComposerHardwareKey(
event,
controller,
inputOwned: false,
query: (chooser.liveQuery.value, null),
renderedQuery: pickerQuery,
pickerVisible: pickerVisible,
acceptSuggestion: topMention != null
? () => _runComposerAction(() => chooser.insert(topMention))
: null,
send: null,
);
void save() {
final draft = controller.text;
final text = _qualifiedMentionContent(
draft,
controller.mentions,
code: controller._styledCodeRanges(draft),
).trim();
if (text.isEmpty || text == message.content) {
Navigator.of(context).pop();
return;
}
// Prose only: the edit keeps the tags this path always wrote and adds
// no recipient for a pick.
ref
.read(channelActionsProvider)
.editMessage(
channelId: channelId,
eventId: message.id,
content: text,
mediaTags: buildCustomEmojiTags(
text,
ref.read(customEmojiListProvider),
),
);
Navigator.of(context).pop();
}
return Padding(
padding: EdgeInsets.fromLTRB(
Grid.gutter,
0,
Grid.gutter,
MediaQuery.viewInsetsOf(context).bottom,
),
child: SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
if (pickerVisible)
Padding(
padding: const EdgeInsets.only(bottom: Grid.xxs),
child: _composerSuggestionPanel(
channelSuggestions: const [],
mentionSuggestions: suggestions,
unavailableMentions: rows.unavailable,
mentionSearchFailed: searchFailed,
reserveMentionHeight: rows.reserveHeight,
mentionSearching: rows.searching,
onMentionSearchRetry: () {
if (chooser.query case final query?) {
ref.invalidate(mentionUserSearchProvider(query));
}
},
userCache: userCache,
currentPubkey: currentPubkey,
isDmChannel: channel?.isDm ?? false,
onChannelSelect: (_) {},
onMentionSelect: chooser.insert,
),
),
Actions(
actions: {
UndoTextIntent: _ComposerHistoryAction<UndoTextIntent>(
controller,
),
RedoTextIntent: _ComposerHistoryAction<RedoTextIntent>(
controller,
),
},
child: Focus(
canRequestFocus: false,
skipTraversal: true,
onKeyEvent: handleHardwareKey,
child: TextField(
key: const ValueKey('message-edit-field'),
controller: controller,
focusNode: focusNode,
autofocus: true,
minLines: 1,
maxLines: 5,
inputFormatters: [_ComposerChipEditingFormatter(controller)],
decoration: const InputDecoration(hintText: 'Edit message'),
),
),
),
const SizedBox(height: Grid.xxs),
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
TextButton(
onPressed: () => Navigator.of(context).pop(),
child: const Text('Cancel'),
),
const SizedBox(width: Grid.half),
FilledButton(onPressed: save, child: const Text('Save')),
],
),
],
),
),
);
}
}
/// Names for the people [message] mentions, as the bubble resolves them: the
/// cached profile, the roster's display name, the agent directory, then an
/// agent's fallback label.
Map<String, String> _editedMentionNames(
WidgetRef ref, {
required TimelineMessage message,
required String channelId,
required Map<String, UserProfile> userCache,
required List<ChannelMember> members,
}) {
final profileNames = <String, String>{};
for (final pubkey in message.mentionPubkeys) {
final key = pubkey.toLowerCase();
final name =
userCache[key]?.displayName ??
members
.where((m) => m.pubkey.toLowerCase() == key)
.firstOrNull
?.displayName;
if (name != null && name.trim().isNotEmpty) profileNames[key] = name;
}
final agentPubkeys = ref.watch(agentMentionPubkeysProvider(channelId));
return mentionNamesWithDirectoryLabels(
mentionPubkeys: message.mentionPubkeys,
profileMentionNames: profileNames,
directoryDisplayNames: ref.watch(agentDirectoryDisplayNamesProvider),
agentMentionPubkeys: {
for (final pubkey in message.mentionPubkeys)
if (agentPubkeys.contains(pubkey.toLowerCase())) pubkey.toLowerCase(),
},
);
}
/// The mentions already in [message], bound to the people its tags name,
/// in text order. Each `@Name` or `@Name (<key>)` the content writes for
/// exactly one tagged person becomes a chip; a name two tagged people share
/// stays text, since the text cannot say which one it meant.
List<_ComposerMention> _editedMessageMentions(
TimelineMessage message, {
required Map<String, String> names,
required Set<String> agentPubkeys,
required List<MentionCandidate> members,
}) {
if (names.isEmpty) return const [];
final keysByLabel = <String, Set<String>>{};
for (final MapEntry(key: pubkey, value: name) in names.entries) {
(keysByLabel[name.toLowerCase()] ??= {}).add(pubkey);
keysByLabel['${name.toLowerCase()} ($pubkey)'] = {pubkey};
}
final content = message.content;
return [
for (final range in mentionOccurrences(content, keysByLabel.keys))
if (keysByLabel[range.label.toLowerCase()] case final keys?
when keys.length == 1)
_ComposerMention(
start: range.start,
end: range.end,
candidate:
members
.where((m) => m.pubkey.toLowerCase() == keys.single)
.firstOrNull ??
MentionCandidate(
pubkey: keys.single,
displayName: names[keys.single],
isAgent: agentPubkeys.contains(keys.single),
),
),
];
}

View File

@@ -28,6 +28,7 @@ import '../../shared/reminders/reminder_service.dart';
import 'channel_management_provider.dart'; import 'channel_management_provider.dart';
import 'me/me_page.dart'; import 'me/me_page.dart';
import 'channels_provider.dart'; import 'channels_provider.dart';
import 'compose_bar.dart';
import '../../shared/emoji/emoji_picker.dart'; import '../../shared/emoji/emoji_picker.dart';
import 'reaction_row.dart'; import 'reaction_row.dart';
import '../../shared/emoji/recent_emoji_provider.dart'; import '../../shared/emoji/recent_emoji_provider.dart';
@@ -195,9 +196,8 @@ Future<void> showMessageActions({
title: const Text('Edit message'), title: const Text('Edit message'),
onTap: () { onTap: () {
if (!_selectMessageAction(sheetContext)) return; if (!_selectMessageAction(sheetContext)) return;
_showEditSheet( showMessageEditSheet(
context: context, context: context,
ref: ref,
message: message, message: message,
channelId: channelId, channelId: channelId,
); );
@@ -896,73 +896,6 @@ class _QuickReactionCircle extends StatelessWidget {
} }
} }
void _showEditSheet({
required BuildContext context,
required WidgetRef ref,
required TimelineMessage message,
required String channelId,
}) {
final controller = TextEditingController(text: message.content);
showBuzzModalBottomSheet<void>(
context: context,
isScrollControlled: true,
showDragHandle: true,
builder: (sheetContext) => Padding(
padding: EdgeInsets.fromLTRB(
Grid.gutter,
0,
Grid.gutter,
MediaQuery.viewInsetsOf(sheetContext).bottom,
),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
TextField(
controller: controller,
autofocus: true,
minLines: 1,
maxLines: 5,
decoration: const InputDecoration(hintText: 'Edit message'),
),
const SizedBox(height: Grid.xxs),
Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
TextButton(
onPressed: () => Navigator.of(sheetContext).pop(),
child: const Text('Cancel'),
),
const SizedBox(width: Grid.half),
FilledButton(
onPressed: () {
final text = controller.text.trim();
if (text.isEmpty || text == message.content) {
Navigator.of(sheetContext).pop();
return;
}
ref
.read(channelActionsProvider)
.editMessage(
channelId: channelId,
eventId: message.id,
content: text,
mediaTags: buildCustomEmojiTags(
text,
ref.read(customEmojiListProvider),
),
);
Navigator.of(sheetContext).pop();
},
child: const Text('Save'),
),
],
),
],
),
),
);
}
void _confirmDelete({ void _confirmDelete({
required BuildContext context, required BuildContext context,
required WidgetRef ref, required WidgetRef ref,

View File

@@ -0,0 +1,282 @@
import 'package:buzz/features/channels/channel.dart';
import 'package:buzz/features/channels/channel_management_provider.dart';
import 'package:buzz/features/channels/channels_provider.dart';
import 'package:buzz/features/channels/compose_bar.dart';
import 'package:buzz/features/channels/mentions/mention_candidates_provider.dart';
import 'package:buzz/features/channels/timeline_message.dart';
import 'package:buzz/shared/mentions/agent_identity_provider.dart';
import 'package:buzz/shared/profile/user_profile.dart';
import 'package:buzz/shared/relay/relay.dart';
import 'package:buzz/shared/theme/theme.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:nostr/nostr.dart' as nostr;
import 'package:shared_preferences/shared_preferences.dart';
const _channelId = 'channel-1';
final _bob = 'b' * 64;
final _alice = 'a' * 64;
final _quinn = UserProfile(pubkey: 'c' * 64, displayName: 'Quinn');
final _channel = Channel(
id: _channelId,
name: 'general',
channelType: 'stream',
visibility: 'open',
description: '',
createdBy: 'creator',
createdAt: DateTime(2026),
memberCount: 3,
isMember: true,
);
final _members = [
for (final (key, name) in [(_bob, 'Bob'), (_alice, 'Alice')])
ChannelMember(
pubkey: key,
displayName: name,
role: 'member',
joinedAt: DateTime(2025),
),
];
class _ChannelsNotifier extends ChannelsNotifier {
@override
Future<List<Channel>> build() async => [_channel];
}
class _RelayConfigNotifier extends RelayConfigNotifier {
@override
RelayConfig build() => RelayConfig(
baseUrl: 'http://localhost:3000',
nsec: nostr.Keys.generate().nsec,
);
}
/// Records the edit the sheet saves; the relay write is the production
/// path's, unchanged by this change.
class _RecordingActions implements ChannelActions {
final edits =
<
({
String channelId,
String eventId,
String content,
List<List<String>> tags,
})
>[];
@override
Future<void> editMessage({
required String channelId,
required String eventId,
required String content,
List<List<String>> mediaTags = const [],
}) async {
edits.add((
channelId: channelId,
eventId: eventId,
content: content,
tags: mediaTags,
));
}
@override
dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);
}
TimelineMessage _message(String content, {List<String> mentions = const []}) =>
TimelineMessage(
id: 'msg-1',
pubkey: 'self',
createdAt: 1000,
content: content,
tags: [
for (final key in mentions) ['p', key],
],
mentionPubkeys: mentions,
);
Future<_RecordingActions> _openEditSheet(
WidgetTester tester, {
required TimelineMessage message,
Future<List<UserProfile>> Function(String query)? searchPeople,
}) async {
SharedPreferences.setMockInitialValues({});
final prefs = await SharedPreferences.getInstance();
final actions = _RecordingActions();
await tester.pumpWidget(
ProviderScope(
overrides: [
savedPrefsProvider.overrideWithValue(prefs),
relayConfigProvider.overrideWith(_RelayConfigNotifier.new),
relayClientProvider.overrideWithValue(
RelayClient(baseUrl: 'http://localhost:3000'),
),
currentPubkeyProvider.overrideWith((ref) => 'self'),
channelsProvider.overrideWith(_ChannelsNotifier.new),
channelMembersProvider(
_channelId,
).overrideWith((ref) => Future.value(_members)),
agentDirectoryProvider.overrideWith((ref) async => const []),
agentOwnersProvider.overrideWith((ref) async => const {}),
channelActionsProvider.overrideWithValue(actions),
if (searchPeople != null)
mentionUserSearchProvider.overrideWith((ref, query) async {
await Future<void>.delayed(mentionSearchDebounce);
final people = await searchPeople(query.trim());
ref.read(mentionSearchCacheProvider).put(query.trim(), people);
return people;
}),
],
child: MaterialApp(
theme: AppTheme.light(),
home: Scaffold(
body: Builder(
builder: (context) => TextButton(
onPressed: () => showMessageEditSheet(
context: context,
message: message,
channelId: _channelId,
),
child: const Text('open'),
),
),
),
),
),
);
await tester.tap(find.text('open'));
await tester.pumpAndSettle();
return actions;
}
void main() {
final field = find.byKey(const ValueKey('message-edit-field'));
final personChip = find.byKey(const ValueKey('composer-person-mention-chip'));
final popover = find.byKey(const ValueKey('mention-suggestions-popover'));
Finder row(String name) =>
find.descendant(of: popover, matching: find.text(name));
TextEditingController controllerOf(WidgetTester tester) =>
tester.widget<TextField>(field).controller!;
/// Lets a debounced directory search for the current query fire.
Future<void> pause(WidgetTester tester) async {
await tester.pump();
await tester.pump(mentionSearchDebounce * 2);
}
testWidgets(
'editing a message offers the mention chooser and saves prose only',
(tester) async {
final original = 'The agenda is ready @Alice';
final searched = <String>[];
final actions = await _openEditSheet(
tester,
message: _message(original, mentions: [_alice]),
searchPeople: (query) async {
searched.add(query);
return 'quinn'.startsWith(query.toLowerCase()) ? [_quinn] : [];
},
);
final controller = controllerOf(tester);
// The message's existing mention opens as a chip bound to Alice.
expect(controller.text, original);
expect(personChip, findsOneWidget);
expect(find.text('Edit message'), findsOneWidget);
// Typing `@bo` opens the composer's chooser; a tap inserts a chip.
await tester.enterText(field, '$original cc @bo');
await tester.pumpAndSettle();
expect(row('Bob'), findsOneWidget);
await tester.tap(row('Bob'));
await tester.pumpAndSettle();
expect(controller.text, '$original cc @Bob ');
expect(personChip, findsNWidgets(2));
expect(popover, findsNothing);
// The chooser follows the field's focus (recommendation 8).
await tester.enterText(field, '$original cc @Bob and @al');
await tester.pumpAndSettle();
expect(row('Alice'), findsOneWidget);
tester.widget<TextField>(field).focusNode!.unfocus();
await tester.pumpAndSettle();
expect(popover, findsNothing);
expect(controller.text, '$original cc @Bob and @al');
tester.widget<TextField>(field).focusNode!.requestFocus();
await tester.pumpAndSettle();
expect(row('Alice'), findsOneWidget);
// Closing punctuation selects an exact name as Space does.
await tester.enterText(field, '$original cc @Bob and @alice');
await tester.pump();
await tester.enterText(field, '$original cc @Bob and @alice,');
await tester.pumpAndSettle();
expect(controller.text, '$original cc @Bob and @Alice,');
expect(personChip, findsNWidgets(3));
// A person the directory finds is picked the same way.
await tester.enterText(field, '$original cc @Bob @qu');
await pause(tester);
expect(searched, contains('qu'));
expect(row('Quinn'), findsOneWidget);
expect(row('not in channel'), findsOneWidget);
await tester.tap(row('Quinn'));
await tester.pumpAndSettle();
expect(controller.text, '$original cc @Bob @Quinn ');
expect(personChip, findsNWidgets(3));
// Saving writes the text with the picks and adds no recipient: the
// edit carries the tags this path always wrote, never a `p` tag.
await tester.tap(find.text('Save'));
await tester.pumpAndSettle();
expect(actions.edits, hasLength(1));
final edit = actions.edits.single;
expect(edit.channelId, _channelId);
expect(edit.eventId, 'msg-1');
expect(edit.content, '$original cc @Bob @Quinn');
expect(edit.tags.where((tag) => tag.first == 'p'), isEmpty);
expect(find.text('Edit message'), findsNothing);
},
);
testWidgets('an unchanged or emptied edit saves nothing', (tester) async {
final actions = await _openEditSheet(
tester,
message: _message('hello @Bob', mentions: [_bob]),
);
expect(personChip, findsOneWidget);
await tester.tap(find.text('Save'));
await tester.pumpAndSettle();
expect(actions.edits, isEmpty);
expect(find.text('Edit message'), findsNothing);
await _openEditSheet(tester, message: _message('hello'));
await tester.enterText(field, ' ');
await tester.tap(find.text('Save'));
await tester.pumpAndSettle();
expect(find.text('Edit message'), findsNothing);
});
testWidgets(
'the sheet fits a small phone with the keyboard and chooser open',
(tester) async {
tester.view.physicalSize = const Size(375, 667);
tester.view.devicePixelRatio = 1;
tester.view.viewInsets = const FakeViewPadding(bottom: 300);
addTearDown(tester.view.reset);
await _openEditSheet(tester, message: _message('one\ntwo\nthree\nfour'));
final controller = controllerOf(tester);
await tester.enterText(field, '${controller.text}\nfive @bo');
await tester.pumpAndSettle();
expect(row('Bob'), findsOneWidget);
expect(tester.takeException(), isNull);
await tester.ensureVisible(find.text('Save'));
await tester.pumpAndSettle();
expect(find.text('Save').hitTestable(), findsOneWidget);
expect(tester.takeException(), isNull);
},
);
}