From e033e36a1e8e1c0afffb8169cc4d05d1645e53aa Mon Sep 17 00:00:00 2001 From: Evie Gauthier Date: Tue, 17 Mar 2026 15:17:37 -0400 Subject: [PATCH] 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. --- src/app/components/editor/autocomplete/AutocompleteMenu.tsx | 6 ++++-- src/app/features/room/RoomInput.tsx | 2 +- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/src/app/components/editor/autocomplete/AutocompleteMenu.tsx b/src/app/components/editor/autocomplete/AutocompleteMenu.tsx index 0b82001b..def55c2f 100644 --- a/src/app/components/editor/autocomplete/AutocompleteMenu.tsx +++ b/src/app/components/editor/autocomplete/AutocompleteMenu.tsx @@ -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('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(() => { diff --git a/src/app/features/room/RoomInput.tsx b/src/app/features/room/RoomInput.tsx index be7a468b..84036812 100644 --- a/src/app/features/room/RoomInput.tsx +++ b/src/app/features/room/RoomInput.tsx @@ -833,7 +833,7 @@ export const RoomInput = forwardRef( if (isKeyHotkey('enter', evt) && !isComposing(evt)) { const selectedItem = - autocompleteMenu.querySelector('button[data-selected]') ?? +autocompleteMenu.querySelector('button[data-selected="true"]') ?? autocompleteMenu.querySelector('button'); if (selectedItem) {