Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
68 changes: 36 additions & 32 deletions Keas.Mvc/ClientApp/src/components/Shared/AssetFilterBar.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import * as React from 'react';
import { MagnifyingGlassIcon, XMarkIcon } from '@heroicons/react/24/outline';
import { useDropdownDismiss } from './useDropdownDismiss';

export interface AssetFilterCategory {
id: string;
Expand All @@ -20,6 +21,11 @@ export const AssetFilterBar = ({
const [query, setQuery] = React.useState('');
const [open, setOpen] = React.useState(false);
const [active, setActive] = React.useState(-1);
const dismiss = React.useCallback(() => {
setOpen(false);
setActive(-1);
}, []);
const container = useDropdownDismiss(open, dismiss);
const term = query.trim();
const suggestions = categories.flatMap(category => {
const matches = Array.from(new Set(category.options))
Expand Down Expand Up @@ -53,8 +59,29 @@ export const AssetFilterBar = ({
option.category.onChange([...option.category.selected, option.value]);
setQuery('');
setActive(-1);
setOpen(false);
input.current?.focus();
setOpen(false);
};
const handleKeyDown = (event: React.KeyboardEvent<HTMLElement>) => {
if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
event.preventDefault();
setOpen(true);
if (suggestions.length)
setActive(index =>
event.key === 'ArrowDown'
? (index + 1) % suggestions.length
: index <= 0
? suggestions.length - 1
: index - 1
);
} else if (event.key === 'Enter') {
event.preventDefault();
if (open && active >= 0) add(active);
} else if (event.key === 'Escape') {
if (open) event.stopPropagation();
setOpen(false);
setActive(-1);
}
};

React.useEffect(() => {
Expand All @@ -68,13 +95,8 @@ export const AssetFilterBar = ({
<div className='mb-5 space-y-3'>
<div className='flex items-center gap-3'>
<div
ref={container}
className='relative min-w-0 flex-1'
onBlur={event => {
if (!event.currentTarget.contains(event.relatedTarget)) {
setOpen(false);
setActive(-1);
}
}}
>
<label className='input flex w-full items-center gap-3'>
<MagnifyingGlassIcon
Expand Down Expand Up @@ -106,35 +128,17 @@ export const AssetFilterBar = ({
setOpen(true);
setActive(-1);
}}
onKeyDown={event => {
if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
event.preventDefault();
setOpen(true);
if (suggestions.length)
setActive(index =>
event.key === 'ArrowDown'
? (index + 1) % suggestions.length
: index <= 0
? suggestions.length - 1
: index - 1
);
} else if (event.key === 'Enter') {
event.preventDefault();
if (open && active >= 0) add(active);
} else if (event.key === 'Escape') {
if (open) event.stopPropagation();
setOpen(false);
setActive(-1);
}
}}
onKeyDown={handleKeyDown}
/>
</label>
{open && (
<div
id={`${id}-suggestions`}
role='listbox'
tabIndex={-1}
onKeyDown={handleKeyDown}
aria-label='Filter suggestions'
className='absolute inset-x-0 top-full z-30 mt-2 max-h-80 overflow-y-auto rounded-box border border-main-border bg-base-100 p-2 shadow-lg'
className='dropdown-scroll absolute start-0 top-full z-30 mt-2 max-h-80 w-full max-w-[calc(100vw-2rem)] overflow-y-auto rounded-box border border-main-border bg-base-100 p-2 shadow-lg'
>
{suggestions.length === 0 && (
<p className='m-0 px-3 py-4 text-sm text-base-content/60'>
Expand Down Expand Up @@ -164,10 +168,10 @@ export const AssetFilterBar = ({
id={`${id}-option-${option.index}`}
role='option'
aria-selected={active === option.index}
className={`cursor-pointer rounded-sm px-3 py-2 text-sm break-words ${
className={`cursor-pointer rounded-sm px-3 py-2 text-sm break-words active:bg-base-content/15 ${
active === option.index
? 'bg-base-200'
: 'hover:bg-base-200'
? 'bg-base-300'
: 'hover:bg-base-300'
}`}
onMouseDown={event => event.preventDefault()}
onClick={() => add(option.index)}
Expand Down
149 changes: 149 additions & 0 deletions Keas.Mvc/ClientApp/src/components/Shared/DropdownScrolling.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
import { act, cleanup, fireEvent, render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { AssetFilterBar } from './AssetFilterBar';
import { Modal, ModalBody } from './AppModal';
import { SearchCombobox } from './SearchCombobox';

afterEach(cleanup);

const options = Array.from({ length: 40 }, (_, index) => `Tag ${index + 1}`);
const dropdowns = [
{
name: 'search selectors',
renderDropdown: (onChange: (values: string[]) => void) => (
<SearchCombobox id='scroll-tags' options={options} onChange={onChange} multiple />
)
},
{
name: 'asset filters',
renderDropdown: (onChange: (values: string[]) => void) => (
<AssetFilterBar categories={Array.from({ length: 8 }, (_, index) => ({
id: `category-${index}`,
label: `Category ${index}`,
options: options.slice(index * 5, index * 5 + 5),
selected: [],
onChange
}))} />
)
}
];

describe.each(dropdowns)('$name scrolling', ({ renderDropdown }) => {
const setup = () => {
const change = vi.fn();
render(<>
{renderDropdown(change)}
<button type='button'>Outside button</button>
<p>Outside text</p>
</>);
const input = screen.getByRole('combobox');
userEvent.click(input);
return { input, change, list: screen.getByRole('listbox') };
};

it('keeps suggestions open through scrollbar blur, dragging, and scrolling', () => {
const { input, list, change } = setup();
// Do not cancel the native scrollbar's pointer action.
expect(fireEvent.pointerDown(list)).toBe(true);
act(() => input.blur());
fireEvent.pointerMove(document.body);
fireEvent.scroll(list, { target: { scrollTop: 250 } });
fireEvent.pointerUp(document.body);
expect(screen.getByRole('listbox')).toBe(list);
expect(input).toHaveAttribute('aria-expanded', 'true');
expect(change).not.toHaveBeenCalled();

// Selecting after scrolling must close even when the input regains focus.
userEvent.click(screen.getByRole('option', { name: 'Tag 40' }));
expect(change).toHaveBeenCalledWith(['Tag 40']);
expect(input).toHaveFocus();
expect(screen.queryByRole('listbox')).not.toBeInTheDocument();
});

it('dismisses on an outside pointer interaction, including non-focusable text', () => {
setup();
fireEvent.pointerDown(screen.getByText('Outside text'));
expect(screen.queryByRole('listbox')).not.toBeInTheDocument();
});

it('keeps scrollbar focus inside a modal and supports keyboard selection afterward', () => {
const change = vi.fn();
const close = vi.fn();
render(<Modal isOpen fade={false} toggle={close} labelledBy='scroll-dialog-title'>
<h2 id='scroll-dialog-title'>Edit asset</h2>
<ModalBody>{renderDropdown(change)}</ModalBody>
</Modal>);
userEvent.click(screen.getByRole('combobox'));
const list = screen.getByRole('listbox');
// Native scrollbar clicks can focus the closest focusable ancestor. Without
// a focusable list, that is the modal, which looks like an outside focus.
expect(fireEvent.mouseDown(list)).toBe(true);
act(() => list.closest<HTMLElement>('[tabindex]')?.focus());
expect(screen.getByRole('listbox')).toBe(list);
expect(list).toHaveFocus();
fireEvent.mouseUp(list);
fireEvent.keyDown(list, { key: 'ArrowDown' });
fireEvent.keyDown(list, { key: 'Enter' });
expect(change).toHaveBeenCalledWith(['Tag 1']);
expect(screen.queryByRole('listbox')).not.toBeInTheDocument();
expect(screen.getByRole('dialog', { name: 'Edit asset' })).toBeInTheDocument();
expect(close).not.toHaveBeenCalled();
});

it('does not dismiss on a window blur without an outside interaction', () => {
const { list } = setup();
fireEvent.blur(window);
expect(screen.getByRole('listbox')).toBe(list);
});

it('dismisses when focus moves outside without a pointer interaction', () => {
setup();
act(() => screen.getByRole('button', { name: 'Outside button' }).focus());
expect(screen.queryByRole('listbox')).not.toBeInTheDocument();
});

it.each([false, true])('dismisses on Tab with shift=%s and preserves focus navigation', shift => {
const { input } = setup();
userEvent.tab({ shift });
expect(input).not.toHaveFocus();
expect(screen.queryByRole('listbox')).not.toBeInTheDocument();
});

it('dismisses on Escape after the scrollbar blurs the input', () => {
const { input, list } = setup();
fireEvent.pointerDown(list);
act(() => input.blur());
fireEvent.keyDown(document.body, { key: 'Escape' });
expect(screen.queryByRole('listbox')).not.toBeInTheDocument();
});

it('preserves keyboard selection after scrolling and refocusing the input', () => {
const { input, list, change } = setup();
fireEvent.pointerDown(list);
act(() => input.blur());
fireEvent.scroll(list, { target: { scrollTop: 250 } });
userEvent.click(input);
fireEvent.keyDown(input, { key: 'ArrowDown' });
fireEvent.keyDown(input, { key: 'ArrowDown' });
fireEvent.keyDown(input, { key: 'ArrowUp' });
expect(screen.getByRole('option', { name: 'Tag 1' })).toHaveAttribute('aria-selected', 'true');
fireEvent.keyDown(input, { key: 'Enter' });
expect(change).toHaveBeenCalledWith(['Tag 1']);
expect(screen.queryByRole('listbox')).not.toBeInTheDocument();
});
});

it('closes the previous selector when another selector is opened', () => {
render(<>
<SearchCombobox id='first-tags' placeholder='First tags' options={options} onChange={vi.fn()} />
<SearchCombobox id='second-tags' placeholder='Second tags' options={options} onChange={vi.fn()} />
</>);
const first = screen.getByRole('combobox', { name: 'First tags' });
const second = screen.getByRole('combobox', { name: 'Second tags' });
userEvent.click(first);
userEvent.click(second);
expect(first).toHaveAttribute('aria-expanded', 'false');
expect(second).toHaveAttribute('aria-expanded', 'true');
expect(screen.getAllByRole('listbox')).toHaveLength(1);
});
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
import SearchAsyncOptions from './SearchAsyncOptions';

it('searches asynchronously, selects a server result and hides the menu on blur after rerender', async () => {
it('searches asynchronously, selects a server result and hides the menu on outside focus after rerender', async () => {
const onSearch = vi.fn();
const onChange = vi.fn();
const props = {
Expand Down Expand Up @@ -32,7 +32,7 @@ it('searches asynchronously, selects a server result and hides the menu on blur
await waitFor(() => expect(onSearch).toHaveBeenCalledWith('San'));
rerender(<SearchAsyncOptions {...props} options={[person]} />);
expect(await screen.findByRole('option')).toBeVisible();
fireEvent.blur(input);
fireEvent.focusIn(document.body);
await waitFor(() =>
expect(screen.queryByRole('option')).not.toBeInTheDocument()
);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { useState } from 'react';
import { describe, expect, it, vi, afterEach } from 'vitest';
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
import { SearchCombobox } from './SearchCombobox';

afterEach(cleanup);
Expand Down Expand Up @@ -40,21 +40,42 @@ describe('DaisyUI search combobox', () => {
expect((screen.getByRole('combobox') as HTMLInputElement).value).toBe('ABC');
});

it('closes suggestions on Escape and blur, and disables selection', () => {
it('closes suggestions on Escape and outside focus, and disables selection', () => {
const change = vi.fn();
const view = render(<SearchCombobox id='tags' options={['Dell']} onChange={change} />);
const input = screen.getByRole('combobox');
fireEvent.focus(input);
fireEvent.keyDown(input, { key: 'Escape' });
expect(screen.queryByRole('listbox')).toBeNull();
fireEvent.focus(input);
fireEvent.blur(input);
fireEvent.focusIn(document.body);
expect(screen.queryByRole('listbox')).toBeNull();
view.rerender(<SearchCombobox id='tags' options={['Dell']} onChange={change} disabled />);
expect((input as HTMLInputElement).disabled).toBe(true);
expect(change).not.toHaveBeenCalled();
});

it('returns focus from the listbox to the input on Escape and resets the active option', () => {
const change = vi.fn();
render(<SearchCombobox id='tags' options={['Laptop', 'Desktop']} onChange={change} />);
const input = screen.getByRole('combobox');
act(() => input.focus());
const list = screen.getByRole('listbox');
act(() => list.focus());
expect(list).toHaveFocus();
fireEvent.keyDown(list, { key: 'ArrowDown' });
fireEvent.keyDown(list, { key: 'ArrowDown' });
fireEvent.keyDown(list, { key: 'Escape' });
expect(input).toHaveFocus();
expect(input).toHaveAttribute('aria-expanded', 'false');
expect(input).not.toHaveAttribute('aria-activedescendant');
expect(screen.queryByRole('listbox')).not.toBeInTheDocument();
expect(change).not.toHaveBeenCalled();

fireEvent.keyDown(input, { key: 'ArrowDown' });
expect(screen.getByRole('option', { name: 'Laptop' })).toHaveAttribute('aria-selected', 'true');
});

it('debounces remote searches, honors minimum length, and displays results', async () => {
const search = vi.fn();
const change = vi.fn();
Expand Down
Loading
Loading