Fix the autocomplete "dropdown" menus (#487)
<!-- Please read https://github.com/SableClient/Sable/blob/dev/CONTRIBUTING.md before submitting your pull request --> ### Description This PR seeks to fix the issues around the autocomplete for emoji, room, command, and people. The issues fixed by this PR are: the autocomplete menu not scrolling, not rollovering (ie when you were at the top you couldnt go back to the bottom or vice versa), and when editing a message and trying to select an emoji the arrow buttons not working. #### Type of change - [x] Bug fix (non-breaking change which fixes an issue) - [ ] New feature (non-breaking change which adds functionality) - [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected) - [ ] This change requires a documentation update ### Checklist: - [x] My code follows the style guidelines of this project - [x] I have performed a self-review of my own code - [x] I have commented my code, particularly in hard-to-understand areas - [x] I have made corresponding changes to the documentation - [x] My changes generate no new warnings ### AI disclosure: - [ ] Partially AI assisted (clarify which code was AI assisted and briefly explain what it does). - [ ] Fully AI generated (explain what all the generated code does in moderate detail). <!-- Write any explanation required here, but do not generate the explanation using AI!! You must prove you understand what the code in this PR does. --> Written with all the natural stupidity possible in one so-called human
This commit is contained in:
8 files changed
+55
-249
No files matched your search
@@ -0,0 +1,5 @@
|
||||
---
|
||||
default: patch
|
||||
---
|
||||
|
||||
Fixed text autocomplete issues
|
||||
@@ -1,193 +0,0 @@
|
||||
import { type ReactNode } from 'react';
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { render, act } from '@testing-library/react';
|
||||
import {
|
||||
AutocompleteMenu,
|
||||
AUTOCOMPLETE_NAVIGATE_EVENT,
|
||||
type AutocompleteNavigateDetail,
|
||||
} from './AutocompleteMenu';
|
||||
|
||||
// ── Mocks ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
vi.mock('focus-trap-react', () => ({
|
||||
default: ({ children }: { children: ReactNode }) => <>{children}</>,
|
||||
}));
|
||||
|
||||
vi.mock('folds', () => ({
|
||||
Header: ({ children }: { children: ReactNode }) => <div>{children}</div>,
|
||||
Menu: ({ children }: { children: ReactNode }) => <div>{children}</div>,
|
||||
Scroll: ({ children, onKeyDown }: { children: ReactNode; onKeyDown?: unknown }) => (
|
||||
// eslint-disable-next-line jsx-a11y/no-static-element-interactions
|
||||
<div onKeyDown={onKeyDown as React.KeyboardEventHandler}>{children}</div>
|
||||
),
|
||||
config: { space: { S200: '8px' } },
|
||||
Icons: {},
|
||||
}));
|
||||
|
||||
vi.mock('$utils/keyboard', () => ({
|
||||
preventScrollWithArrowKey: vi.fn(),
|
||||
stopPropagation: vi.fn(() => true),
|
||||
}));
|
||||
|
||||
vi.mock('$hooks/useAlive', () => ({
|
||||
useAlive: () => () => true,
|
||||
}));
|
||||
|
||||
// ── Helpers ───────────────────────────────────────────────────────────────────
|
||||
|
||||
function dispatchNavigate(container: HTMLElement, direction: 1 | -1) {
|
||||
const menu = container.querySelector('[data-autocomplete-menu]');
|
||||
if (!menu) throw new Error('data-autocomplete-menu element not found');
|
||||
menu.dispatchEvent(
|
||||
new CustomEvent<AutocompleteNavigateDetail>(AUTOCOMPLETE_NAVIGATE_EVENT, {
|
||||
bubbles: true,
|
||||
detail: { direction },
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
function renderMenu(children: ReactNode) {
|
||||
return render(
|
||||
<AutocompleteMenu headerContent={<span>header</span>} requestClose={() => {}}>
|
||||
{children}
|
||||
</AutocompleteMenu>
|
||||
);
|
||||
}
|
||||
|
||||
// ── Tests ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
describe('AutocompleteMenu — data-selected stamping', () => {
|
||||
it('stamps the first button with data-selected="true" on initial render', () => {
|
||||
const { container } = renderMenu(
|
||||
<>
|
||||
<button type="button">Item 0</button>
|
||||
<button type="button">Item 1</button>
|
||||
<button type="button">Item 2</button>
|
||||
</>
|
||||
);
|
||||
|
||||
const buttons = container.querySelectorAll<HTMLButtonElement>('button');
|
||||
expect(buttons[0].getAttribute('data-selected')).toBe('true');
|
||||
expect(buttons[1].getAttribute('data-selected')).toBe('false');
|
||||
expect(buttons[2].getAttribute('data-selected')).toBe('false');
|
||||
});
|
||||
|
||||
it('stamps buttons when children load after initial render (async results)', async () => {
|
||||
// Start with no children (empty search, buttons not yet present)
|
||||
const { container, rerender } = renderMenu(null);
|
||||
|
||||
// Simulate async search results arriving
|
||||
await act(async () => {
|
||||
rerender(
|
||||
<AutocompleteMenu headerContent={<span>header</span>} requestClose={() => {}}>
|
||||
<button type="button">Result A</button>
|
||||
<button type="button">Result B</button>
|
||||
</AutocompleteMenu>
|
||||
);
|
||||
});
|
||||
|
||||
const buttons = container.querySelectorAll<HTMLButtonElement>('button');
|
||||
expect(buttons).toHaveLength(2);
|
||||
// First button must be marked selected — this was the bug: with the old
|
||||
// [selectedIndex] dep array the effect didn't re-run when buttons appeared.
|
||||
expect(buttons[0].getAttribute('data-selected')).toBe('true');
|
||||
expect(buttons[1].getAttribute('data-selected')).toBe('false');
|
||||
});
|
||||
|
||||
it('resets selection to the first button when the item list changes', async () => {
|
||||
const { container } = renderMenu(
|
||||
<>
|
||||
<button type="button">Item 0</button>
|
||||
<button type="button">Item 1</button>
|
||||
</>
|
||||
);
|
||||
|
||||
// Navigate to the second item
|
||||
act(() => dispatchNavigate(container, 1));
|
||||
|
||||
const before = container.querySelectorAll<HTMLButtonElement>('button');
|
||||
expect(before[1].getAttribute('data-selected')).toBe('true');
|
||||
|
||||
// Re-render with a completely different set of buttons (new search results)
|
||||
await act(async () => {
|
||||
render(
|
||||
<AutocompleteMenu headerContent={<span>header</span>} requestClose={() => {}}>
|
||||
<button type="button">New A</button>
|
||||
<button type="button">New B</button>
|
||||
<button type="button">New C</button>
|
||||
</AutocompleteMenu>,
|
||||
{ container: container.firstElementChild?.parentElement ?? document.body }
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('AutocompleteMenu — keyboard navigation', () => {
|
||||
it('moves selection forward with direction +1', () => {
|
||||
const { container } = renderMenu(
|
||||
<>
|
||||
<button type="button">Item 0</button>
|
||||
<button type="button">Item 1</button>
|
||||
<button type="button">Item 2</button>
|
||||
</>
|
||||
);
|
||||
|
||||
act(() => dispatchNavigate(container, 1));
|
||||
|
||||
const buttons = container.querySelectorAll<HTMLButtonElement>('button');
|
||||
expect(buttons[0].getAttribute('data-selected')).toBe('false');
|
||||
expect(buttons[1].getAttribute('data-selected')).toBe('true');
|
||||
expect(buttons[2].getAttribute('data-selected')).toBe('false');
|
||||
});
|
||||
|
||||
it('moves selection backward with direction -1', () => {
|
||||
const { container } = renderMenu(
|
||||
<>
|
||||
<button type="button">Item 0</button>
|
||||
<button type="button">Item 1</button>
|
||||
<button type="button">Item 2</button>
|
||||
</>
|
||||
);
|
||||
|
||||
// Go to last item first
|
||||
act(() => dispatchNavigate(container, 1));
|
||||
act(() => dispatchNavigate(container, 1));
|
||||
|
||||
act(() => dispatchNavigate(container, -1));
|
||||
|
||||
const buttons = container.querySelectorAll<HTMLButtonElement>('button');
|
||||
expect(buttons[0].getAttribute('data-selected')).toBe('false');
|
||||
expect(buttons[1].getAttribute('data-selected')).toBe('true');
|
||||
expect(buttons[2].getAttribute('data-selected')).toBe('false');
|
||||
});
|
||||
|
||||
it('clamps selection at the first item when navigating backward at index 0', () => {
|
||||
const { container } = renderMenu(
|
||||
<>
|
||||
<button type="button">Item 0</button>
|
||||
<button type="button">Item 1</button>
|
||||
</>
|
||||
);
|
||||
|
||||
act(() => dispatchNavigate(container, -1));
|
||||
|
||||
const buttons = container.querySelectorAll<HTMLButtonElement>('button');
|
||||
expect(buttons[0].getAttribute('data-selected')).toBe('true');
|
||||
});
|
||||
|
||||
it('clamps selection at the last item when navigating forward past the end', () => {
|
||||
const { container } = renderMenu(
|
||||
<>
|
||||
<button type="button">Item 0</button>
|
||||
<button type="button">Item 1</button>
|
||||
</>
|
||||
);
|
||||
|
||||
act(() => dispatchNavigate(container, 1));
|
||||
act(() => dispatchNavigate(container, 1)); // attempt to go past the end
|
||||
|
||||
const buttons = container.querySelectorAll<HTMLButtonElement>('button');
|
||||
expect(buttons[0].getAttribute('data-selected')).toBe('false');
|
||||
expect(buttons[1].getAttribute('data-selected')).toBe('true');
|
||||
});
|
||||
});
|
||||
@@ -1,25 +1,29 @@
|
||||
import { ReactNode, useEffect, useLayoutEffect, useRef, useState } from 'react';
|
||||
import { ReactNode, useEffect, useRef, useState } from 'react';
|
||||
import FocusTrap from 'focus-trap-react';
|
||||
import { isKeyHotkey } from 'is-hotkey';
|
||||
import { Header, Menu, Scroll, config } from 'folds';
|
||||
|
||||
import { preventScrollWithArrowKey, stopPropagation } from '$utils/keyboard';
|
||||
import { useAlive } from '$hooks/useAlive';
|
||||
import { Editor } from 'slate';
|
||||
import { ReactEditor } from 'slate-react';
|
||||
import * as css from './AutocompleteMenu.css';
|
||||
import { BaseAutocompleteMenu } from './BaseAutocompleteMenu';
|
||||
|
||||
export const AUTOCOMPLETE_NAVIGATE_EVENT = 'autocomplete-navigate';
|
||||
export type AutocompleteNavigateDetail = { direction: 1 | -1 };
|
||||
|
||||
type AutocompleteMenuProps = {
|
||||
requestClose: () => void;
|
||||
headerContent: ReactNode;
|
||||
children: ReactNode;
|
||||
editor: Editor;
|
||||
};
|
||||
export function AutocompleteMenu({ headerContent, requestClose, children }: AutocompleteMenuProps) {
|
||||
export function AutocompleteMenu({
|
||||
headerContent,
|
||||
requestClose,
|
||||
children,
|
||||
editor,
|
||||
}: AutocompleteMenuProps) {
|
||||
const alive = useAlive();
|
||||
const itemsRef = useRef<HTMLDivElement>(null);
|
||||
const [selectedIndex, setSelectedIndex] = useState(0);
|
||||
const prevButtonCountRef = useRef(-1);
|
||||
|
||||
const handleDeactivate = () => {
|
||||
if (alive()) {
|
||||
@@ -27,69 +31,42 @@ export function AutocompleteMenu({ headerContent, requestClose, children }: Auto
|
||||
requestClose();
|
||||
}
|
||||
};
|
||||
|
||||
// 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).
|
||||
// setSelectedIndex is a stable React setter; the conditional call never
|
||||
// triggers an infinite update chain (it only fires when button count changes).
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
useLayoutEffect(() => {
|
||||
const buttons = Array.from(
|
||||
itemsRef.current?.querySelectorAll<HTMLButtonElement>('button') ?? []
|
||||
);
|
||||
const count = buttons.length;
|
||||
|
||||
let idx = selectedIndex;
|
||||
if (count !== prevButtonCountRef.current) {
|
||||
prevButtonCountRef.current = count;
|
||||
idx = 0;
|
||||
if (selectedIndex !== 0) setSelectedIndex(0);
|
||||
}
|
||||
|
||||
const safeIdx = Math.max(0, Math.min(idx, count - 1));
|
||||
buttons.forEach((btn, i) => {
|
||||
btn.setAttribute('data-selected', String(i === safeIdx));
|
||||
});
|
||||
});
|
||||
|
||||
// Listen for navigation events dispatched by the editor key handler
|
||||
useEffect(() => {
|
||||
const container = itemsRef.current?.closest('[data-autocomplete-menu]');
|
||||
if (!container) return undefined;
|
||||
const handler = (e: Event) => {
|
||||
const { direction } = (e as CustomEvent<AutocompleteNavigateDetail>).detail;
|
||||
setSelectedIndex((prev) => {
|
||||
const buttons = itemsRef.current?.querySelectorAll('button') ?? [];
|
||||
return Math.max(0, Math.min(prev + direction, buttons.length - 1));
|
||||
});
|
||||
};
|
||||
container.addEventListener(AUTOCOMPLETE_NAVIGATE_EVENT, handler);
|
||||
return () => container.removeEventListener(AUTOCOMPLETE_NAVIGATE_EVENT, handler);
|
||||
}, []);
|
||||
const [isActive, setIsActive] = useState(true);
|
||||
useEffect(() => ReactEditor.focus(editor), [editor, isActive]);
|
||||
function handleInput(evt: any) {
|
||||
if (!evt) return;
|
||||
if (
|
||||
isKeyHotkey('arrowdown', evt) ||
|
||||
isKeyHotkey('arrowup', evt) ||
|
||||
isKeyHotkey('tab', evt) ||
|
||||
isKeyHotkey('esc', evt) ||
|
||||
isKeyHotkey('Enter', evt)
|
||||
)
|
||||
return;
|
||||
setIsActive(false);
|
||||
}
|
||||
|
||||
return (
|
||||
<BaseAutocompleteMenu>
|
||||
<FocusTrap
|
||||
active={isActive}
|
||||
focusTrapOptions={{
|
||||
initialFocus: false,
|
||||
onPostDeactivate: handleDeactivate,
|
||||
returnFocusOnDeactivate: false,
|
||||
clickOutsideDeactivates: true,
|
||||
allowOutsideClick: true,
|
||||
isKeyForward: (evt: KeyboardEvent) => isKeyHotkey('arrowdown', evt),
|
||||
isKeyBackward: (evt: KeyboardEvent) => isKeyHotkey('arrowup', evt),
|
||||
escapeDeactivates: stopPropagation,
|
||||
}}
|
||||
>
|
||||
<Menu className={css.AutocompleteMenu}>
|
||||
<Menu className={css.AutocompleteMenu} onKeyDown={(evt) => handleInput(evt)}>
|
||||
<Header className={css.AutocompleteMenuHeader} size="400">
|
||||
{headerContent}
|
||||
</Header>
|
||||
<Scroll style={{ flexGrow: 1 }} onKeyDown={preventScrollWithArrowKey}>
|
||||
<div
|
||||
ref={itemsRef}
|
||||
className={css.AutocompleteMenuItems}
|
||||
style={{ padding: config.space.S200 }}
|
||||
>
|
||||
<div ref={itemsRef} style={{ padding: config.space.S200 }}>
|
||||
{children}
|
||||
</div>
|
||||
</Scroll>
|
||||
|
||||
@@ -106,6 +106,7 @@ export function EmoticonAutocomplete({
|
||||
<AutocompleteMenu
|
||||
headerContent={<Text size="L400">{title ?? 'Emojis'}</Text>}
|
||||
requestClose={requestClose}
|
||||
editor={editor}
|
||||
>
|
||||
{autoCompleteEmoticon.map((emoticon) => {
|
||||
const isCustomEmoji = 'url' in emoticon;
|
||||
|
||||
@@ -135,7 +135,11 @@ export function RoomMentionAutocomplete({
|
||||
});
|
||||
|
||||
return (
|
||||
<AutocompleteMenu headerContent={<Text size="L400">Rooms</Text>} requestClose={requestClose}>
|
||||
<AutocompleteMenu
|
||||
headerContent={<Text size="L400">Rooms</Text>}
|
||||
requestClose={requestClose}
|
||||
editor={editor}
|
||||
>
|
||||
{autoCompleteRoomIds.length === 0 ? (
|
||||
<UnknownRoomMentionItem query={query} handleAutocomplete={handleAutocomplete} />
|
||||
) : (
|
||||
|
||||
@@ -143,7 +143,11 @@ export function UserMentionAutocomplete({
|
||||
});
|
||||
|
||||
return (
|
||||
<AutocompleteMenu headerContent={<Text size="L400">Mentions</Text>} requestClose={requestClose}>
|
||||
<AutocompleteMenu
|
||||
headerContent={<Text size="L400">Mentions</Text>}
|
||||
requestClose={requestClose}
|
||||
editor={editor}
|
||||
>
|
||||
{query.text === 'room' && (
|
||||
<UnknownMentionItem
|
||||
userId={roomAliasOrId}
|
||||
|
||||
@@ -78,6 +78,7 @@ export function CommandAutocomplete({
|
||||
</Box>
|
||||
}
|
||||
requestClose={requestClose}
|
||||
editor={editor}
|
||||
>
|
||||
{autoCompleteNames.map((commandName) => (
|
||||
<MenuItem
|
||||
|
||||
@@ -280,6 +280,13 @@ export const MessageEditor = as<'div', MessageEditorProps>(
|
||||
(isKeyHotkey('mod+enter', evt) || (!enterForNewline && isKeyHotkey('enter', evt))) &&
|
||||
!isComposing(evt)
|
||||
) {
|
||||
const prevWordRange = getPrevWorldRange(editor);
|
||||
if (
|
||||
prevWordRange &&
|
||||
getAutocompleteQuery(editor, prevWordRange, ANYWHERE_AUTOCOMPLETE_PREFIXES)
|
||||
)
|
||||
return;
|
||||
|
||||
evt.preventDefault();
|
||||
handleSave();
|
||||
}
|
||||
@@ -288,7 +295,7 @@ export const MessageEditor = as<'div', MessageEditorProps>(
|
||||
onCancel();
|
||||
}
|
||||
},
|
||||
[onCancel, handleSave, enterForNewline, isComposing]
|
||||
[enterForNewline, isComposing, editor, handleSave, onCancel]
|
||||
);
|
||||
|
||||
const handleKeyUp: KeyboardEventHandler = useCallback(
|
||||
|
||||
Reference in new issue
Block a user