From 95e958ecebdaaf3bc6e769f53455bd5be41f0b90 Mon Sep 17 00:00:00 2001 From: Cal Date: Fri, 13 Nov 2026 11:13:05 -0800 Subject: [PATCH 1/2] scrollbar hacking --- .../src/components/Shared/AssetFilterBar.tsx | 68 ++++---- .../Shared/DropdownScrolling.test.tsx | 149 ++++++++++++++++++ .../Shared/SearchAsyncOptions.test.tsx | 4 +- .../components/Shared/SearchCombobox.test.tsx | 4 +- .../src/components/Shared/SearchCombobox.tsx | 41 ++--- .../components/Shared/useDropdownDismiss.ts | 37 +++++ Keas.Mvc/ClientApp/src/styles/main.css | 36 +++++ Keas.Mvc/Views/Shared/_Layout.cshtml | 4 +- 8 files changed, 286 insertions(+), 57 deletions(-) create mode 100644 Keas.Mvc/ClientApp/src/components/Shared/DropdownScrolling.test.tsx create mode 100644 Keas.Mvc/ClientApp/src/components/Shared/useDropdownDismiss.ts 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..5e621247b 100644 --- a/Keas.Mvc/ClientApp/src/components/Shared/SearchCombobox.test.tsx +++ b/Keas.Mvc/ClientApp/src/components/Shared/SearchCombobox.test.tsx @@ -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,7 +48,7 @@ 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); diff --git a/Keas.Mvc/ClientApp/src/components/Shared/SearchCombobox.tsx b/Keas.Mvc/ClientApp/src/components/Shared/SearchCombobox.tsx index 3a32dbb0b..384404f2f 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(); 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 &&