fix(autocomplete): Enter always selects first item; first item not highlighted

Two related bugs in the mention/room/emoji autocomplete:

1. Enter key always inserted the first suggestion instead of the highlighted one.
   Cause: querySelector('[data-selected]') matched ALL buttons since every button
   has the attribute set to either 'true' or 'false'. The first button in DOM
   order was always returned.
   Fix: use '[data-selected="true"]' to select only the active item.

2. The first item had no visual highlight on initial open (the CSS rule requires
   data-selected='true', but the useLayoutEffect responsible for stamping that
   attribute only re-ran when selectedIndex changed -- not when buttons first
   appeared after async search results loaded).
   Fix: remove the dep array so the effect runs after every render; newly-loaded
   buttons are stamped immediately.
This commit is contained in:
Evie Gauthier committed 2026-03-17 16:17:32 -04:00
1 parent ab138a11b5
commit e033e36a1e
2 files changed
+5 -3

No files matched your search

@@ -28,7 +28,9 @@ export function AutocompleteMenu({ headerContent, requestClose, children }: Auto
}
};
// Sync data-selected to DOM; reset to index 0 when the item list changes
// Sync data-selected to DOM; reset to index 0 when the item list changes.
// No dep array — runs after every render so newly-loaded buttons are stamped
// immediately (buttons arrive async when search results load).
useLayoutEffect(() => {
const buttons = Array.from(
itemsRef.current?.querySelectorAll<HTMLButtonElement>('button') ?? []
@@ -46,7 +48,7 @@ export function AutocompleteMenu({ headerContent, requestClose, children }: Auto
buttons.forEach((btn, i) => {
btn.setAttribute('data-selected', String(i === safeIdx));
});
}, [selectedIndex]);
});
// Listen for navigation events dispatched by the editor key handler
useEffect(() => {
+1 -1
View File
@@ -833,7 +833,7 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
if (isKeyHotkey('enter', evt) && !isComposing(evt)) {
const selectedItem =
autocompleteMenu.querySelector<HTMLButtonElement>('button[data-selected]') ??
autocompleteMenu.querySelector<HTMLButtonElement>('button[data-selected="true"]') ??
autocompleteMenu.querySelector<HTMLButtonElement>('button');
if (selectedItem) {