Skip to content

Commit

Permalink
fix(DatePicker): Focus selected date or today when picker opens
Browse files Browse the repository at this point in the history
This makes focusing consistent with the W3 WAI-ARIA date picker example.
  • Loading branch information
jpveooys committed Aug 12, 2022
1 parent 4b302c0 commit 9eb0eb2
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 8 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -612,6 +612,22 @@ describe('DatePicker', () => {
})
})

describe('when a single date picker with a value is rendered and the picker is opened', () => {
beforeEach(() => {
wrapper = render(
<DatePicker startDate={new Date('2022-01-18T00:00:00Z')} />
)

return user.click(wrapper.getByTestId('datepicker-input-button'))
})

it('focuses the current date', () => {
expect(
wrapper.getByRole('button', { name: '18th January (Tuesday)' })
).toHaveFocus()
})
})

describe('when a single date picker is rendered and the picker is opened', () => {
beforeEach(() => {
wrapper = render(<DatePicker />)
Expand All @@ -623,12 +639,10 @@ describe('DatePicker', () => {
expect(wrapper.getByText('December 2019')).toBeInTheDocument()
})

it('focuses the previous month button', () => {
return waitFor(() =>
expect(
wrapper.getByLabelText(PREVIOUS_MONTH_BUTTON_LABEL)
).toHaveFocus()
)
it('focuses the current date', () => {
expect(
wrapper.getByRole('button', { name: '5th December (Thursday)' })
).toHaveFocus()
})

describe('when Shift-Tab is pressed once', () => {
Expand All @@ -638,7 +652,7 @@ describe('DatePicker', () => {

it('traps the focus within the picker', () => {
expect(
wrapper.getByRole('button', { name: '5th December (Thursday)' })
wrapper.getByLabelText(PREVIOUS_MONTH_BUTTON_LABEL)
).toHaveFocus()
})

Expand All @@ -649,7 +663,7 @@ describe('DatePicker', () => {

it('still traps the focus within the picker', () => {
expect(
wrapper.getByLabelText(PREVIOUS_MONTH_BUTTON_LABEL)
wrapper.getByRole('button', { name: '5th December (Thursday)' })
).toHaveFocus()
})
})
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -354,6 +354,7 @@ export const DatePicker: React.FC<DatePickerProps> = ({
onDayMouseLeave={handleDayBlurOrMouseLeave}
onDayFocus={handleDayFocusOrMouseEnter}
onDayBlur={handleDayBlurOrMouseLeave}
initialFocus
/>
</div>
</FocusTrap>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ export function useFocusTrapOptions(
isEventTargetDescendantOf(event, clickAllowedElementRefs),
clickOutsideDeactivates: (event) =>
!isEventTargetDescendantOf(event, clickAllowedElementRefs),
initialFocus: false,
onDeactivate: close,
}),
[clickAllowedElementRefs, close]
Expand Down

0 comments on commit 9eb0eb2

Please sign in to comment.