-
Notifications
You must be signed in to change notification settings - Fork 536
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
v2 Menus: Implement typeahead focus #1834
Merged
Merged
Changes from all commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
e643f44
Add hook for typeahead
siddharthkp 7fb2019
add tests!
siddharthkp 68d4b53
update menu focus tests to pass ref
siddharthkp 56b18a1
add changelog
siddharthkp ce7f696
rename hook to useTypeaheadFocus
siddharthkp 8538d5a
Merge branch 'main' into siddharth/menu-focus-first-letter
colebemis 43cc167
Merge branch 'main' into siddharth/menu-focus-first-letter
siddharthkp bffc226
Merge branch 'main' into siddharth/menu-focus-first-letter
siddharthkp 87a628e
update snapshots
siddharthkp 807412c
Create chilly-cheetahs-end.md
siddharthkp ab16d73
Merge branch 'main' into siddharth/menu-focus-first-letter
siddharthkp d68aab2
Merge branch 'siddharth/upgrade-behaviors-1.1.0' into siddharth/menu-…
siddharthkp 4ff95ac
Merge branch 'main' into siddharth/menu-focus-first-letter
siddharthkp File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
--- | ||
'@primer/react': minor | ||
--- | ||
|
||
ActionMenu2 + DropdownMenu2: Implement typeahead search. [See detailed spec.](https://github.com/github/primer/issues/518#issuecomment-999104848) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,196 @@ | ||
import React from 'react' | ||
import {render, fireEvent, cleanup} from '@testing-library/react' | ||
import {useTypeaheadFocus} from '../../hooks' | ||
import {TYPEAHEAD_TIMEOUT} from '../../hooks/useTypeaheadFocus' | ||
|
||
const Component = ({ | ||
onSelect = () => null, | ||
hasInput = false, | ||
refNotAttached = false | ||
}: { | ||
onSelect?: (event: React.KeyboardEvent<HTMLButtonElement>) => void | ||
hasInput?: boolean | ||
refNotAttached?: boolean | ||
}) => { | ||
const containerRef = React.createRef<HTMLDivElement>() | ||
useTypeaheadFocus(true, containerRef) // hard coding open=true for test | ||
|
||
return ( | ||
<> | ||
<div ref={refNotAttached ? undefined : containerRef} data-testid="container"> | ||
{/* eslint-disable-next-line jsx-a11y/no-autofocus */} | ||
{hasInput && <input autoFocus type="text" placeholder="Filter options" />} | ||
<button onKeyDown={onSelect}>button 1</button> | ||
<button onKeyDown={onSelect}>Button 2</button> | ||
<button disabled>button 3 is disabled</button> | ||
<button onKeyDown={onSelect}>button 4</button> | ||
<button onKeyDown={onSelect}>third button</button> | ||
<span>not focusable</span> | ||
</div> | ||
</> | ||
) | ||
} | ||
|
||
describe('useTypeaheadFocus', () => { | ||
afterEach(cleanup) | ||
|
||
it('First element: when b is pressed, it should move focus the "b"utton 1', () => { | ||
const {getByTestId, getByText} = render(<Component />) | ||
const container = getByTestId('container') | ||
|
||
fireEvent.keyDown(container, {key: 'b', code: 'b'}) | ||
expect(getByText('button 1')).toEqual(document.activeElement) | ||
}) | ||
|
||
it('Not first element: when t is pressed, it should move focus the "t"hird button', () => { | ||
const {getByTestId, getByText} = render(<Component />) | ||
const container = getByTestId('container') | ||
|
||
fireEvent.keyDown(container, {key: 't', code: 't'}) | ||
expect(getByText('third button')).toEqual(document.activeElement) | ||
}) | ||
|
||
it('Case insinsitive: when B is pressed, it should move focus the "b"utton 1', () => { | ||
const {getByTestId, getByText} = render(<Component />) | ||
const container = getByTestId('container') | ||
|
||
fireEvent.keyDown(container, {key: 'B', code: 'B'}) | ||
expect(getByText('button 1')).toEqual(document.activeElement) | ||
}) | ||
|
||
it('Repeating letter: when b is pressed repeatedly, it should wrap through the buttons starting with "b", skipping the disabled button', () => { | ||
const {getByTestId, getByText} = render(<Component />) | ||
const container = getByTestId('container') | ||
|
||
fireEvent.keyDown(container, {key: 'b', code: 'b'}) | ||
expect(getByText('button 1')).toEqual(document.activeElement) | ||
|
||
fireEvent.keyDown(container, {key: 'b', code: 'b'}) | ||
expect(getByText('Button 2')).toEqual(document.activeElement) | ||
|
||
fireEvent.keyDown(container, {key: 'b', code: 'b'}) | ||
expect(getByText('button 4')).toEqual(document.activeElement) | ||
|
||
fireEvent.keyDown(container, {key: 'b', code: 'b'}) | ||
expect(getByText('button 1')).toEqual(document.activeElement) | ||
}) | ||
|
||
it('Timeout: when presses b, waits and presses t, it should move focus the "t"hird button', async () => { | ||
jest.useFakeTimers() | ||
const {getByTestId, getByText} = render(<Component />) | ||
const container = getByTestId('container') | ||
|
||
fireEvent.keyDown(container, {key: 'b', code: 'b'}) | ||
expect(getByText('button 1')).toEqual(document.activeElement) | ||
|
||
// if we press t now, the query would be "bt", | ||
// and focus will stay wherever it is | ||
fireEvent.keyDown(container, {key: 't', code: 't'}) | ||
expect(getByText('button 1')).toEqual(document.activeElement) | ||
|
||
// but, if we simulate typeahead timeout, then type t | ||
// it should jump to the third button | ||
jest.advanceTimersByTime(TYPEAHEAD_TIMEOUT) | ||
fireEvent.keyDown(container, {key: 't', code: 't'}) | ||
expect(getByText('third button')).toEqual(document.activeElement) | ||
}) | ||
|
||
it('Space: when user is typing and presses Space, it should not select the option', () => { | ||
const mockFunction = jest.fn() | ||
const {getByTestId, getByText} = render(<Component onSelect={mockFunction} />) | ||
|
||
const container = getByTestId('container') | ||
fireEvent.keyDown(container, {key: 't', code: 't'}) | ||
|
||
const thirdButton = getByText('third button') | ||
expect(thirdButton).toEqual(document.activeElement) | ||
fireEvent.keyDown(thirdButton, {key: ' ', code: 'Space'}) | ||
expect(mockFunction).not.toHaveBeenCalled() | ||
}) | ||
|
||
it('Space after timeout: when user is presses Space after waiting, it should select the option', () => { | ||
jest.useFakeTimers() | ||
const mockFunction = jest.fn() | ||
const {getByTestId, getByText} = render(<Component onSelect={mockFunction} />) | ||
|
||
const container = getByTestId('container') | ||
fireEvent.keyDown(container, {key: 't', code: 't'}) | ||
|
||
const thirdButton = getByText('third button') | ||
expect(thirdButton).toEqual(document.activeElement) | ||
|
||
jest.advanceTimersByTime(TYPEAHEAD_TIMEOUT) | ||
fireEvent.keyDown(thirdButton, {key: ' ', code: 'Space'}) | ||
expect(mockFunction).toHaveBeenCalled() | ||
}) | ||
|
||
it('Enter: when user is presses Enter, it should instantly select the option', () => { | ||
jest.useFakeTimers() | ||
const mockFunction = jest.fn() | ||
const {getByTestId, getByText} = render(<Component onSelect={mockFunction} />) | ||
|
||
const container = getByTestId('container') | ||
fireEvent.keyDown(container, {key: 't', code: 't'}) | ||
|
||
const thirdButton = getByText('third button') | ||
expect(thirdButton).toEqual(document.activeElement) | ||
|
||
fireEvent.keyDown(thirdButton, {key: 'Enter', code: 'Enter'}) | ||
expect(mockFunction).toHaveBeenCalled() | ||
}) | ||
|
||
it('Long string: when user starts typing a longer string "button 4", focus should jump to closest match', async () => { | ||
jest.useFakeTimers() | ||
const mockFunction = jest.fn() | ||
const {getByTestId, getByText} = render(<Component onSelect={mockFunction} />) | ||
const container = getByTestId('container') | ||
|
||
fireEvent.keyDown(container, {key: 'b', code: 'b'}) | ||
expect(getByText('button 1')).toEqual(document.activeElement) | ||
|
||
fireEvent.keyDown(container, {key: 'u', code: 'u'}) | ||
expect(getByText('button 1')).toEqual(document.activeElement) | ||
|
||
fireEvent.keyDown(container, {key: 't', code: 't'}) | ||
fireEvent.keyDown(container, {key: 't', code: 't'}) | ||
fireEvent.keyDown(container, {key: 'o', code: 'o'}) | ||
fireEvent.keyDown(container, {key: 'n', code: 'n'}) | ||
|
||
// pressing Space should be treated as part of query | ||
// and shouldn't select the option | ||
fireEvent.keyDown(container, {key: ' ', code: 'Space'}) | ||
expect(mockFunction).not.toHaveBeenCalled() | ||
expect(getByText('button 1')).toEqual(document.activeElement) | ||
|
||
fireEvent.keyDown(container, {key: '4', code: '4'}) | ||
// the query is now "button 4" and should move focus | ||
expect(getByText('button 4')).toEqual(document.activeElement) | ||
}) | ||
|
||
it('Shortcuts: when a modifier is used, typeahead should not do anything', () => { | ||
const {getByTestId, getByText} = render(<Component />) | ||
const container = getByTestId('container') | ||
|
||
fireEvent.keyDown(container, {metaKey: true, key: 'b', code: 'b'}) | ||
expect(getByText('button 1')).not.toEqual(document.activeElement) | ||
}) | ||
|
||
it('TextInput: when an textinput has focus, typeahead should not do anything', async () => { | ||
const {getByTestId, getByPlaceholderText} = render(<Component hasInput={true} />) | ||
const container = getByTestId('container') | ||
|
||
const input = getByPlaceholderText('Filter options') | ||
expect(input).toEqual(document.activeElement) | ||
|
||
fireEvent.keyDown(container, {key: 'b', code: 'b'}) | ||
expect(input).toEqual(document.activeElement) | ||
}) | ||
|
||
it('Missing ref: when a ref is not attached, typeahead should break the component', async () => { | ||
const {getByTestId, getByText} = render(<Component refNotAttached={true} />) | ||
const container = getByTestId('container') | ||
|
||
fireEvent.keyDown(container, {key: 'b', code: 'b'}) | ||
expect(getByText('button 1')).not.toEqual(document.activeElement) | ||
}) | ||
}) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,94 @@ | ||
import React from 'react' | ||
import {iterateFocusableElements} from '@primer/behaviors/utils' | ||
import {useProvidedRefOrCreate} from './useProvidedRefOrCreate' | ||
|
||
export const TYPEAHEAD_TIMEOUT = 1000 | ||
|
||
export const useTypeaheadFocus = (open: boolean, providedRef?: React.RefObject<HTMLElement>) => { | ||
const containerRef = useProvidedRefOrCreate(providedRef) | ||
|
||
React.useEffect(() => { | ||
if (!open || !containerRef.current) return | ||
const container = containerRef.current | ||
|
||
let query = '' | ||
let timeout: number | undefined | ||
|
||
const handler = (event: KeyboardEvent) => { | ||
// skip if a TextInput has focus | ||
const activeElement = document.activeElement as HTMLElement | ||
if (activeElement.tagName === 'INPUT') return | ||
|
||
// skip if used with modifier to preserve shortcuts like ⌘ + F | ||
const hasModifier = event.ctrlKey || event.altKey || event.metaKey | ||
if (hasModifier) return | ||
|
||
if (query.length && event.code === 'Space') { | ||
// prevent the menu from selecting an option | ||
event.preventDefault() | ||
} | ||
|
||
// skip if it's not a alphabet key | ||
else if (!isAlphabetKey(event)) { | ||
query = '' // reset the typeahead query | ||
return | ||
} | ||
|
||
query += event.key.toLowerCase() | ||
|
||
// if this is a typeahead event, don't propagate outside of menu | ||
event.stopPropagation() | ||
|
||
// reset the query after timeout | ||
window.clearTimeout(timeout) | ||
timeout = window.setTimeout(() => (query = ''), TYPEAHEAD_TIMEOUT) | ||
|
||
let elementToFocus: HTMLElement | undefined | ||
|
||
const focusableItems = [...iterateFocusableElements(container)] | ||
|
||
const focusNextMatch = () => { | ||
const itemsStartingWithKey = focusableItems.filter(item => { | ||
return item.textContent?.toLowerCase().startsWith(query) | ||
}) | ||
|
||
const currentActiveIndex = itemsStartingWithKey.indexOf(activeElement) | ||
|
||
// If the last element is already selected, cycle through the list | ||
if (currentActiveIndex === itemsStartingWithKey.length - 1) { | ||
elementToFocus = itemsStartingWithKey[0] | ||
} else { | ||
elementToFocus = itemsStartingWithKey.find((item, index) => { | ||
return index > currentActiveIndex | ||
}) | ||
} | ||
elementToFocus?.focus() | ||
} | ||
|
||
// Single charachter in query: Jump to the next match | ||
if (query.length === 1) return focusNextMatch() | ||
|
||
// 2 charachters in query but the user is pressing | ||
// the same key, jump to the next match | ||
if (query.length === 2 && query[0] === query[1]) { | ||
query = query[0] // remove the second key | ||
return focusNextMatch() | ||
} | ||
|
||
// More > 1 charachters in query | ||
// If active element satisfies the query stay there, | ||
if (activeElement.textContent?.toLowerCase().startsWith(query)) return | ||
// otherwise move to the next one that does. | ||
return focusNextMatch() | ||
} | ||
|
||
container.addEventListener('keydown', handler) | ||
return () => container.removeEventListener('keydown', handler) | ||
}, [open, containerRef]) | ||
|
||
const isAlphabetKey = (event: KeyboardEvent) => { | ||
return event.key.length === 1 && /[a-z\d]/i.test(event.key) | ||
} | ||
|
||
return {containerRef} | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Note 1: Changed both of these hooks to accept a ref if it's passed (or create a new one if it's not passed)
Note 2: Did not combine these into one hook called
useMenuFocus
, we might want to re-use typeahead logic in NavigationTree 🤷