Skip to content

Commit

Permalink
feat: v8 (#1509)
Browse files Browse the repository at this point in the history
BREAKING CHANGE: Release Downshift v8.

## PRs included:
#1440
#1445
#1463
#1510
#1482

## Changes

These changes will also be covered in the [V8 migration guide](https://github.com/downshift-js/downshift/blob/master/src/hooks/MIGRATION_V8.md).

### isItemDisabled

Both `useCombobox` and `useSelect` now support the `isItemDisabled` function. This new API is used to mark menu items as disabled, and as such remove the from the navigation and prevent them from being selected. The old API required passing the `disabled` prop to the `getItemProps` function. This old API has been removed and you will receive a console warning if you are trying to use the `disabled` prop in getItemProps.

Example of API migration:

Old:

```jsx
const items = [{value: 'item1'}, {value: 'item2'}]

const {getInputProps, ...rest} = useCombobox({items})

return (
  // ... rest
  <li {...getItemProps({item, disabled: item.value === 'item2'})}>
)
```

New:

```jsx
const items = [{value: 'item1'}, {value: 'item2'}]

const {getInputProps, ...rest} = useCombobox({items, isItemDisabled(item, _index) { return item.value === 'item2' }})

return (
  // ... rest
  <li {...getItemProps({item})}>
)
```

The API for Downshift remains unchange.

### useCombobox input click

[ARIA 1.2](combobox-aria-example) recommends to toggle the menu open state at input click. Previously, in v7, the menu was opened on receiving focus, from both mouse and keyboard. Starting with v8, input focus will not trigger any state change anymore. Only the input click event will be handled and will trigger a menu toggle. Consequently:

- getInputProps **will not** return any _Focus_ event handler.
- getInputProps **will** return a _Click_ event handler.
- `useCombobox.stateChangeTypes.InputFocus` has been removed.
- `useCombobox.stateChangeTypes.InputClick` has been added instead.

We recommend having the default toggle on input click behaviour as it's part of the official ARIA combobox 1.2 spec, but if you wish to override it and not toggle the menu on click, use the stateReducer:

```js
function stateReducer(state, actionAndChanges) {
  const {changes, type} = actionAndChanges
  switch (type) {
    case useCombobox.stateChangeTypes.InputClick:
      return {
        ...changes,
        isOpen: state.isOpen, // do not toggle the menu when input is clicked.
      }
    default:
      return changes
  }
}
```

If you want to return to the v7 behaviour and open the menu on focus, keep the reducer above so you remove the toggle behaviour, and call the _openMenu_ imperative function, returned by useCombobox, in a _onFocus_ handler passed to
_getInputProps_:

```js
<input
  {...getInputProps({
    onFocus() {
      openMenu()
    },
  })}
/>
```

Consider to use the default 1.2 ARIA behaviour provided by default in order to align your widget to the accessibility official spec. This behaviour consistency improves the user experience, since all comboboxes should behave the same and
there won't be need for any additional guess work done by your users.

### Getter props return value types

Previously, the return value from the getter props returned by both Downshift and the hooks was `any`. In v8 we improved the types in order to reflect what is actually returned: the default values return by the getter prop function and
whatever else the user passes as arguments. The type changes are done in [this PR](#1482), make sure you adapt your TS code, if applicable.

Also, in the `Downshift` component, the return values for some getter prop values have changed from `null` to `undefined`, since that is what HTML elements expect (value or undefined). These values are also reflected in the TS types.

- getRootProps: 'aria-owns': isOpen ? this.menuId : ~~null~~undefined,
- getInputProps:
  - 'aria-controls': isOpen ? this.menuId : ~~null~~undefined
  - 'aria-activedescendant': isOpen && typeof highlightedIndex === 'number' &&
    highlightedIndex >= 0 ? this.getItemId(highlightedIndex) : ~~null~~undefined
- getMenuProps: props && props['aria-label'] ? ~~null~~undefined : this.labelId,

### environment propTypes

The `environment` prop is useful when you are using downshift in a context
different than regular DOM. Its TS type has been updated to contain `Node` and
the propTypes have also been updated to reflect the properties which are
required by downshift from `environment`.

[combobox-aria-example]:
  https://www.w3.org/WAI/ARIA/apg/example-index/combobox/combobox-autocomplete-list.html
  • Loading branch information
silviuaavram committed Jul 15, 2023
1 parent 57f8690 commit b62fe05
Show file tree
Hide file tree
Showing 44 changed files with 2,500 additions and 1,374 deletions.
5 changes: 3 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -1043,6 +1043,8 @@ const ui = (
Allows reseting the internal id counter which is used to generate unique ids for
Downshift component.

**This is unnecessary if you are using React 18 or newer**

You should never need to use this in the browser. Only if you are running an
universal React app that is rendered on the server you should call
[resetIdCounter](#resetidcounter) before every render so that the ids that get
Expand Down Expand Up @@ -1506,8 +1508,7 @@ MIT
https://courses.reacttraining.com/courses/advanced-react/lectures/3172720
[react-training]: https://reacttraining.com/
[advanced-react]: https://courses.reacttraining.com/courses/enrolled/200086
[use-a-render-prop]:
https://medium.com/@mjackson/use-a-render-prop-50de598f11ce
[use-a-render-prop]: https://medium.com/@mjackson/use-a-render-prop-50de598f11ce
[semver]: http://semver.org/
[hooks-readme]: https://github.com/downshift-js/downshift/blob/master/src/hooks
[useselect-readme]:
Expand Down
40 changes: 20 additions & 20 deletions other/ssr/__tests__/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@ import * as React from 'react'
import * as ReactDOMServer from 'react-dom/server'
import Downshift, {resetIdCounter} from '../../../src'

// something to commit

test('does not throw an error when server rendering', () => {
expect(() => {
ReactDOMServer.renderToString(
Expand All @@ -19,25 +17,27 @@ test('does not throw an error when server rendering', () => {
}).not.toThrow()
})

test('resets idCounter', () => {
const getRenderedString = () => {
resetIdCounter()
return ReactDOMServer.renderToString(
<Downshift id="my-autocomplete-component">
{({getInputProps, getLabelProps}) => (
<div>
<label {...getLabelProps()} />
<input {...getInputProps()} />
</div>
)}
</Downshift>,
)
}
if (!('useId' in React)) {
test('resets idCounter', () => {
const getRenderedString = () => {
resetIdCounter()
return ReactDOMServer.renderToString(
<Downshift id="my-autocomplete-component">
{({getInputProps, getLabelProps}) => (
<div>
<label {...getLabelProps()} />
<input {...getInputProps()} />
</div>
)}
</Downshift>,
)
}

const firstRun = getRenderedString()
const secondRun = getRenderedString()
const firstRun = getRenderedString()
const secondRun = getRenderedString()

expect(firstRun).toBe(secondRun)
})
expect(firstRun).toBe(secondRun)
})
}

/* eslint jsx-a11y/label-has-for:0 */
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,7 @@
"@testing-library/user-event": "^14.4.3",
"@types/jest": "^26.0.24",
"@types/react": "^17.0.15",
"@types/react-native": "^0.71.3",
"@typescript-eslint/eslint-plugin": "^4.28.5",
"@typescript-eslint/parser": "^4.28.5",
"babel-plugin-macros": "^3.1.0",
Expand Down
21 changes: 21 additions & 0 deletions src/__tests__/__snapshots__/set-a11y-status.js.snap
Original file line number Diff line number Diff line change
@@ -1,5 +1,26 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`creates new status div if there is none 1`] = `
Array [
Array [
id,
a11y-status-message,
],
Array [
role,
status,
],
Array [
aria-live,
polite,
],
Array [
aria-relevant,
additions text,
],
]
`;

exports[`does add anything for an empty string 1`] = `
<div
aria-live=polite
Expand Down
2 changes: 1 addition & 1 deletion src/__tests__/downshift.aria.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import Downshift from '../'
import {resetIdCounter} from '../utils'

beforeEach(() => {
resetIdCounter()
if (!('useId' in React)) resetIdCounter()
})

test('basic snapshot', () => {
Expand Down
4 changes: 4 additions & 0 deletions src/__tests__/downshift.props.js
Original file line number Diff line number Diff line change
Expand Up @@ -84,8 +84,12 @@ test('uses given environment', () => {
const environment = {
addEventListener: jest.fn(),
removeEventListener: jest.fn(),
Node,
document: {
getElementById: jest.fn(() => document.createElement('div')),
createElement: jest.fn(),
body: {},
activeElement: {},
},
}
const {unmount, setHighlightedIndex} = setup({environment})
Expand Down
35 changes: 35 additions & 0 deletions src/__tests__/set-a11y-status.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,41 @@ test('performs cleanup after a timeout', () => {
expect(document.body.firstChild).toMatchSnapshot()
})

test('creates new status div if there is none', () => {
const statusDiv = {setAttribute: jest.fn(), style: {}}
const document = {
getElementById: jest.fn(() => null),
createElement: jest.fn().mockReturnValue(statusDiv),
body: {
appendChild: jest.fn(),
},
}

const setA11yStatus = setup()
setA11yStatus('hello', document)

expect(document.getElementById).toHaveBeenCalledTimes(1)
expect(document.getElementById).toHaveBeenCalledWith('a11y-status-message')
expect(document.createElement).toHaveBeenCalledTimes(1)
expect(document.createElement).toHaveBeenCalledWith('div')
expect(statusDiv.setAttribute).toHaveBeenCalledTimes(4)
expect(statusDiv.setAttribute.mock.calls).toMatchSnapshot()
expect(statusDiv.style).toEqual({
border: '0',
clip: 'rect(0 0 0 0)',
height: '1px',
margin: '-1px',
overflow: 'hidden',
padding: '0',
position: 'absolute',
width: '1px',
})
expect(document.body.appendChild).toHaveBeenCalledTimes(1)
expect(document.body.appendChild).toHaveBeenCalledWith(statusDiv)
// eslint-disable-next-line jest-dom/prefer-to-have-text-content
expect(statusDiv.textContent).toEqual('hello')
})

function setup() {
jest.resetModules()
return require('../set-a11y-status').default
Expand Down
224 changes: 224 additions & 0 deletions src/__tests__/utils.get-highlighted-index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,224 @@
import {getHighlightedIndex} from '../utils'

test('should return next index', () => {
const offset = 1
const start = 0
const items = {length: 3}
function isItemDisabled() {
return false
}

expect(getHighlightedIndex(start, offset, items, isItemDisabled)).toEqual(1)
})

test('should return previous index', () => {
const offset = -1
const start = 2
const items = {length: 3}
function isItemDisabled() {
return false
}

expect(getHighlightedIndex(start, offset, items, isItemDisabled)).toEqual(1)
})

test('should return previous index based on moveAmount', () => {
const offset = -2
const start = 2
const items = {length: 3}
function isItemDisabled() {
return false
}

expect(getHighlightedIndex(start, offset, items, isItemDisabled)).toEqual(0)
})

test('should wrap to first if circular and reached end', () => {
const offset = 3
const start = 2
const items = {length: 3}
function isItemDisabled() {
return false
}
const circular = true

expect(
getHighlightedIndex(start, offset, items, isItemDisabled, circular),
).toEqual(0)
})

test('should not wrap to first if not circular and reached end', () => {
const offset = 3
const start = 2
const items = {length: 3}
function isItemDisabled() {
return false
}
const circular = false

expect(
getHighlightedIndex(start, offset, items, isItemDisabled, circular),
).toEqual(2)
})

test('should wrap to last if circular and reached start', () => {
const offset = -3
const start = 2
const items = {length: 3}
function isItemDisabled() {
return false
}
const circular = true

expect(
getHighlightedIndex(start, offset, items, isItemDisabled, circular),
).toEqual(2)
})

test('should not wrap to last if not circular and reached start', () => {
const offset = -3
const start = 2
const items = {length: 3}
function isItemDisabled() {
return false
}
const circular = false

expect(
getHighlightedIndex(start, offset, items, isItemDisabled, circular),
).toEqual(0)
})

test('should skip disabled when moving downwards', () => {
const offset = 1
const start = 0
const items = {length: 3}
function isItemDisabled(_item, index) {
return index === 1
}

expect(getHighlightedIndex(start, offset, items, isItemDisabled)).toEqual(2)
})

test('should skip disabled when moving upwards', () => {
const offset = -1
const start = 2
const items = {length: 3}
function isItemDisabled(_item, index) {
return index === 1
}

expect(getHighlightedIndex(start, offset, items, isItemDisabled)).toEqual(0)
})

test('should skip disabled and wrap to last if circular when reaching first', () => {
const offset = -1
const start = 1
const items = {length: 3}
function isItemDisabled(_item, index) {
return index === 0
}
const circular = true

expect(
getHighlightedIndex(start, offset, items, isItemDisabled, circular),
).toEqual(2)
})

test('should skip disabled and wrap to second to last if circular when reaching first and last is disabled', () => {
const offset = -1
const start = 1
const items = {length: 3}
function isItemDisabled(_item, index) {
return [0, 2].includes(index)
}
const circular = true

expect(
getHighlightedIndex(start, offset, items, isItemDisabled, circular),
).toEqual(1)
})

test('should skip disabled and not wrap to last if circular when reaching first', () => {
const offset = -1
const start = 1
const items = {length: 3}
function isItemDisabled(_item, index) {
return index === 0
}
const circular = false

expect(
getHighlightedIndex(start, offset, items, isItemDisabled, circular),
).toEqual(1)
})

test('should skip disabled and wrap to first if circular when reaching last', () => {
const offset = 1
const start = 1
const items = {length: 3}
function isItemDisabled(_item, index) {
return index === 2
}
const circular = true

expect(
getHighlightedIndex(start, offset, items, isItemDisabled, circular),
).toEqual(0)
})

test('should skip disabled and wrap to second if circular when reaching last and first is disabled', () => {
const offset = 1
const start = 1
const items = {length: 3}
function isItemDisabled(_item, index) {
return [0, 2].includes(index)
}
const circular = true

expect(
getHighlightedIndex(start, offset, items, isItemDisabled, circular),
).toEqual(1)
})

test('should skip disabled and not wrap to first if circular when reaching last', () => {
const offset = 1
const start = 1
const items = {length: 3}
function isItemDisabled(_item, index) {
return index === 2
}
const circular = false

expect(
getHighlightedIndex(start, offset, items, isItemDisabled, circular),
).toEqual(1)
})

test('should not select any if all disabled when arrow up', () => {
const offset = -1
const start = -1
const items = {length: 3}
function isItemDisabled() {
return true
}
const circular = true

expect(
getHighlightedIndex(start, offset, items, isItemDisabled, circular),
).toEqual(-1)
})

test('should not select any if all disabled when arrow down', () => {
const offset = 1
const start = -1
const items = {length: 3}
function isItemDisabled() {
return true
}
const circular = true

expect(
getHighlightedIndex(start, offset, items, isItemDisabled, circular),
).toEqual(-1)
})
Loading

0 comments on commit b62fe05

Please sign in to comment.