diff --git a/Keas.Mvc/ClientApp/src/components/Shared/AssetFilterBar.tsx b/Keas.Mvc/ClientApp/src/components/Shared/AssetFilterBar.tsx index e57792d3d..6579cca7d 100644 --- a/Keas.Mvc/ClientApp/src/components/Shared/AssetFilterBar.tsx +++ b/Keas.Mvc/ClientApp/src/components/Shared/AssetFilterBar.tsx @@ -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; @@ -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)) @@ -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) => { + 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(() => { @@ -68,13 +95,8 @@ export const AssetFilterBar = ({
{ - if (!event.currentTarget.contains(event.relatedTarget)) { - setOpen(false); - setActive(-1); - } - }} > {open && (
{suggestions.length === 0 && (

@@ -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)} diff --git a/Keas.Mvc/ClientApp/src/components/Shared/DropdownScrolling.test.tsx b/Keas.Mvc/ClientApp/src/components/Shared/DropdownScrolling.test.tsx new file mode 100644 index 000000000..f2666a84b --- /dev/null +++ b/Keas.Mvc/ClientApp/src/components/Shared/DropdownScrolling.test.tsx @@ -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) => ( + + ) + }, + { + name: 'asset filters', + renderDropdown: (onChange: (values: string[]) => void) => ( + ({ + 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)} + +

Outside text

+ ); + 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( +

Edit asset

+ {renderDropdown(change)} +
); + 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('[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(<> + + + ); + 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); +}); diff --git a/Keas.Mvc/ClientApp/src/components/Shared/SearchAsyncOptions.test.tsx b/Keas.Mvc/ClientApp/src/components/Shared/SearchAsyncOptions.test.tsx index e1a9b943b..d7899c3e5 100644 --- a/Keas.Mvc/ClientApp/src/components/Shared/SearchAsyncOptions.test.tsx +++ b/Keas.Mvc/ClientApp/src/components/Shared/SearchAsyncOptions.test.tsx @@ -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 = { @@ -32,7 +32,7 @@ it('searches asynchronously, selects a server result and hides the menu on blur await waitFor(() => expect(onSearch).toHaveBeenCalledWith('San')); rerender(); expect(await screen.findByRole('option')).toBeVisible(); - fireEvent.blur(input); + fireEvent.focusIn(document.body); await waitFor(() => expect(screen.queryByRole('option')).not.toBeInTheDocument() ); diff --git a/Keas.Mvc/ClientApp/src/components/Shared/SearchCombobox.test.tsx b/Keas.Mvc/ClientApp/src/components/Shared/SearchCombobox.test.tsx index 4ea2a3eb9..257f734ab 100644 --- a/Keas.Mvc/ClientApp/src/components/Shared/SearchCombobox.test.tsx +++ b/Keas.Mvc/ClientApp/src/components/Shared/SearchCombobox.test.tsx @@ -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); @@ -40,7 +40,7 @@ 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(); const input = screen.getByRole('combobox'); @@ -48,13 +48,34 @@ describe('DaisyUI search combobox', () => { 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(); 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(); + 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(); diff --git a/Keas.Mvc/ClientApp/src/components/Shared/SearchCombobox.tsx b/Keas.Mvc/ClientApp/src/components/Shared/SearchCombobox.tsx index 3a32dbb0b..ad8423aa4 100644 --- a/Keas.Mvc/ClientApp/src/components/Shared/SearchCombobox.tsx +++ b/Keas.Mvc/ClientApp/src/components/Shared/SearchCombobox.tsx @@ -1,6 +1,7 @@ import * as React from 'react'; -import { useEffect, useRef, useState } from 'react'; +import { useCallback, useEffect, useRef, useState } from 'react'; import { XMarkIcon } from '@heroicons/react/24/outline'; +import { useDropdownDismiss } from './useDropdownDismiss'; interface Props { id: string; @@ -37,6 +38,8 @@ export const SearchCombobox = (props: Props) => { const [active, setActive] = useState(-1); const [pending, setPending] = useState(false); const input = useRef(null); + const dismiss = useCallback(() => { setOpen(false); setActive(-1); }, []); + const container = useDropdownDismiss(open && !props.disabled, dismiss); const search = useRef(props.onSearch); search.current = props.onSearch; // Serialize searches so an older response never overwrites a newer response. @@ -78,10 +81,21 @@ export const SearchCombobox = (props: Props) => { commit(props.multiple ? [...selected, option] : [option]); setQuery(''); setActive(-1); input.current?.focus(); setOpen(false); }; + const handleKeyDown = (event: React.KeyboardEvent) => { + if (event.key === 'ArrowDown' || event.key === 'ArrowUp') { + event.preventDefault(); setOpen(true); + setActive(event.key === 'ArrowDown' ? Math.min(activeIndex + 1, choices.length - 1) + : activeIndex <= 0 ? choices.length - 1 : activeIndex - 1); + } else if (event.key === 'Enter' && expanded && choices.length) { + event.preventDefault(); choose(choices[activeIndex >= 0 ? activeIndex : 0]); + } else if (event.key === 'Escape' && open) { + event.preventDefault(); event.stopPropagation(); input.current?.focus(); setOpen(false); setActive(-1); + } else if (event.key === 'Backspace' && !query && props.multiple && selected.length) { + commit(selected.slice(0, -1)); + } + }; return ( -
{ - if (!event.currentTarget.contains(event.relatedTarget as Node)) { setOpen(false); setActive(-1); } - }}> +
{props.multiple && selected.map((option, index) => ( @@ -105,19 +119,7 @@ export const SearchCombobox = (props: Props) => { if (!props.multiple && selected.length) commit([]); setQuery(event.target.value); setOpen(true); setActive(-1); }} - onKeyDown={event => { - if (event.key === 'ArrowDown' || event.key === 'ArrowUp') { - event.preventDefault(); setOpen(true); - setActive(event.key === 'ArrowDown' ? Math.min(activeIndex + 1, choices.length - 1) - : activeIndex <= 0 ? choices.length - 1 : activeIndex - 1); - } else if (event.key === 'Enter' && expanded && choices.length) { - event.preventDefault(); choose(choices[activeIndex >= 0 ? activeIndex : 0]); - } else if (event.key === 'Escape' && open) { - event.preventDefault(); event.stopPropagation(); setOpen(false); setActive(-1); - } else if (event.key === 'Backspace' && !query && props.multiple && selected.length) { - commit(selected.slice(0, -1)); - } - }} /> + onKeyDown={handleKeyDown} /> {loading && } {props.clearButton && selected.length > 0 && !props.disabled && (
{expanded &&
    + tabIndex={-1} onKeyDown={handleKeyDown} + className='dropdown-scroll menu absolute start-0 top-full z-50 mt-1 max-h-64 w-full max-w-[calc(100vw-2rem)] flex-nowrap overflow-y-auto rounded-box border border-base-content/15 bg-base-100 p-1 shadow-lg'> {choices.map((option, index) => (
  • event.preventDefault()} onMouseMove={() => setActive(index)} onClick={() => choose(option)}> -
    +
    {option.customOption ? `${props.newSelectionPrefix || 'Add: '}${label(option)}` : props.renderMenuItemChildren ? props.renderMenuItemChildren(option, { text: query }, index) : label(option)}
    diff --git a/Keas.Mvc/ClientApp/src/components/Shared/useDropdownDismiss.ts b/Keas.Mvc/ClientApp/src/components/Shared/useDropdownDismiss.ts new file mode 100644 index 000000000..0fef80e51 --- /dev/null +++ b/Keas.Mvc/ClientApp/src/components/Shared/useDropdownDismiss.ts @@ -0,0 +1,37 @@ +import { useEffect, useRef } from 'react'; + +export const useDropdownDismiss = (open: boolean, onDismiss: () => void) => { + const container = useRef(null); + + useEffect(() => { + if (!open) return; + + const dismissOutside = (event: Event) => { + if (event.target instanceof Node && !container.current?.contains(event.target)) { + onDismiss(); + } + }; + const dismissWithKeyboard = (event: KeyboardEvent) => { + if (event.key === 'Escape') { + event.preventDefault(); + event.stopPropagation(); + onDismiss(); + } else if (event.key === 'Tab') { + onDismiss(); + } + }; + + // Native scrollbar interaction can blur the input without focusing another + // element. Dismiss on an actual outside interaction instead of that blur. + document.addEventListener('pointerdown', dismissOutside, true); + document.addEventListener('focusin', dismissOutside, true); + document.addEventListener('keydown', dismissWithKeyboard); + return () => { + document.removeEventListener('pointerdown', dismissOutside, true); + document.removeEventListener('focusin', dismissOutside, true); + document.removeEventListener('keydown', dismissWithKeyboard); + }; + }, [open, onDismiss]); + + return container; +}; diff --git a/Keas.Mvc/ClientApp/src/styles/main.css b/Keas.Mvc/ClientApp/src/styles/main.css index a36053f0e..35b3663f6 100644 --- a/Keas.Mvc/ClientApp/src/styles/main.css +++ b/Keas.Mvc/ClientApp/src/styles/main.css @@ -32,6 +32,42 @@ body { } @layer components { + .dropdown-scroll { + scrollbar-gutter: stable; + scrollbar-width: auto; + /* Non-auto standard colors override the explicit WebKit track width. */ + scrollbar-color: auto; + overscroll-behavior-y: contain; + } + + @supports not selector(::-webkit-scrollbar) { + .dropdown-scroll { + scrollbar-color: color-mix(in oklab, var(--color-base-content) 45%, transparent) var(--color-base-200); + } + } + + .dropdown-scroll::-webkit-scrollbar { + width: 20px; + } + + .dropdown-scroll::-webkit-scrollbar-track { + background: var(--color-base-200); + } + + .dropdown-scroll::-webkit-scrollbar-thumb { + border: 4px solid var(--color-base-200); + border-radius: 999px; + background: color-mix(in oklab, var(--color-base-content) 45%, transparent); + } + + .dropdown-scroll::-webkit-scrollbar-thumb:hover { + background: color-mix(in oklab, var(--color-base-content) 65%, transparent); + } + + .dropdown-scroll::-webkit-scrollbar-thumb:active { + background: color-mix(in oklab, var(--color-base-content) 75%, transparent); + } + .hero-icon { display: inline-block; width: 1.25em; diff --git a/Keas.Mvc/Views/Shared/_Layout.cshtml b/Keas.Mvc/Views/Shared/_Layout.cshtml index 77d89d61b..194ff3849 100644 --- a/Keas.Mvc/Views/Shared/_Layout.cshtml +++ b/Keas.Mvc/Views/Shared/_Layout.cshtml @@ -198,7 +198,7 @@ aria-hidden="true">
    + class="dropdown-scroll relative z-50 mt-1 max-h-[60vh] w-full overflow-y-auto rounded-lg border border-main-border bg-base-100 p-2 shadow-lg lg:absolute lg:left-0 lg:top-full lg:mt-2 lg:w-80"> @if ((await AuthorizationService.AuthorizeAsync(User, AccessCodes.Codes.DepartmentAdminAccess)).Succeeded) { @@ -263,7 +263,7 @@ aria-hidden="true">
    + class="dropdown-scroll relative z-50 mt-1 max-h-[60vh] w-full overflow-y-auto rounded-lg border border-main-border bg-base-100 p-2 shadow-lg lg:absolute lg:right-0 lg:top-full lg:mt-2 lg:w-80"> @foreach (var teamItem in await TeamsManager.GetMyTeams()) {