Add Alert & RadioGroup components (#274)

* add Alert component

* expose Alert

* rename forgotten FLYOUT to POPOVER

* use PopoverRenderPropArg

* organize imports in a consistent way

* ensure Portals behave as expected

Portals can be nested from a React perspective, however in the DOM they
are rendered as siblings, this is mostly fine.

However, when they are rendered inside a Dialog, the Dialog itself is
marked with `role="modal"` which makes all the other content inert. This
means that rendering Menu.Items in a Portal or an Alert in a portal
makes it non-interactable. Alerts are not even announced.

To fix  this, we ensure that we make the `root` of the Portal the actual
dialog. This allows you to still interact with it, because an open modal
is the "root" for the assistive technology.

But there is a catch, a Dialog in a Dialog *can* render as a sibling,
because you force the focus into the new Dialog. So we also ensured that
Dialogs are always rendered in the portal root, and not inside another
Dialog.

* add dialog with alert example

* add internal Description component

* add internal Label component

* add RadioGroup component

* expose RadioGroup

* add RadioGroup example

* ensure to include tha RadioGroup.Option own id

* update changelog

* split documentation
This commit is contained in:
Robin Malfait
2021-03-15 12:07:36 +01:00
parent e3cbcc43f9
commit 00cc8c50e3
43 changed files with 5239 additions and 3089 deletions
+2
View File
@@ -27,6 +27,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Add `FocusTrap` component ([#220](https://github.com/tailwindlabs/headlessui/pull/220))
- Add `Popover` component ([#220](https://github.com/tailwindlabs/headlessui/pull/220))
- All components that accept a `className`, can now also receive a function with the renderProp argument ([#257](https://github.com/tailwindlabs/headlessui/pull/257))
- Add `RadioGroup` component ([#274](https://github.com/tailwindlabs/headlessui/pull/274))
- Add `Alert` component ([#274](https://github.com/tailwindlabs/headlessui/pull/274))
## [Unreleased - Vue]
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,126 @@
import React, { useState, Fragment } from 'react'
import { Dialog, Portal, Transition, Alert } from '@headlessui/react'
export default function Home() {
let [isOpen, setIsOpen] = useState(false)
let [deleted, setDeleted] = useState(false)
function notifyUser() {
setDeleted(true)
setTimeout(() => {
setDeleted(false)
}, 10 * 1000)
}
return (
<>
<button
type="button"
onClick={() => setIsOpen(v => !v)}
className="m-12 px-4 py-2 text-base font-medium leading-6 text-gray-700 transition duration-150 ease-in-out bg-white border border-gray-300 rounded-md shadow-sm hover:text-gray-500 focus:outline-none focus:border-blue-300 focus:shadow-outline-blue sm:text-sm sm:leading-5"
>
Toggle!
</button>
<Transition show={isOpen} as={Fragment}>
<Dialog open={isOpen} onClose={setIsOpen} static>
<div className="fixed z-10 inset-0 overflow-y-auto">
<div className="flex items-end justify-center min-h-screen pt-4 px-4 pb-20 text-center sm:block sm:p-0">
<Transition.Child
enter="ease-out duration-300"
enterFrom="opacity-0"
enterTo="opacity-100"
leave="ease-in duration-200"
leaveFrom="opacity-100"
leaveTo="opacity-0"
>
<Dialog.Overlay className="fixed inset-0 transition-opacity">
<div className="absolute inset-0 bg-gray-500 opacity-75"></div>
</Dialog.Overlay>
</Transition.Child>
<Transition.Child
enter="ease-out transform duration-300"
enterFrom="opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95"
enterTo="opacity-100 translate-y-0 sm:scale-100"
leave="ease-in transform duration-200"
leaveFrom="opacity-100 translate-y-0 sm:scale-100"
leaveTo="opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95"
>
{/* This element is to trick the browser into centering the modal contents. */}
<span
className="hidden sm:inline-block sm:align-middle sm:h-screen"
aria-hidden="true"
>
&#8203;
</span>
<div className="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full">
<div className="bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4">
<div className="sm:flex sm:items-start">
<div className="mx-auto flex-shrink-0 flex items-center justify-center h-12 w-12 rounded-full bg-red-100 sm:mx-0 sm:h-10 sm:w-10">
{/* Heroicon name: exclamation */}
<svg
className="h-6 w-6 text-red-600"
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
aria-hidden="true"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"
/>
</svg>
</div>
<div className="mt-3 text-center sm:mt-0 sm:ml-4 sm:text-left">
<Dialog.Title
as="h3"
className="text-lg leading-6 font-medium text-gray-900"
>
Deactivate account
</Dialog.Title>
<div className="mt-2">
<p className="text-sm text-gray-500">
Are you sure you want to deactivate your account? All of your data will
be permanently removed. This action cannot be undone.
</p>
{deleted && (
<Portal>
<div className="fixed z-50 bg-blue-400 text-white font-bold text-lg p-4 py-6 top-0 left-0 right-0">
<Alert>I am now deleted!</Alert>
</div>
</Portal>
)}
<div className="relative inline-block text-left mt-10"></div>
</div>
</div>
</div>
</div>
<div className="bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse">
<button
type="button"
onClick={() => notifyUser()}
className="w-full inline-flex justify-center rounded-md border border-transparent shadow-sm px-4 py-2 bg-red-600 text-base font-medium text-white hover:bg-red-700 focus:outline-none focus:shadow-outline-red sm:ml-3 sm:w-auto sm:text-sm"
>
Deactivate
</button>
<button
type="button"
onClick={() => setIsOpen(false)}
className="mt-3 w-full inline-flex justify-center rounded-md border border-gray-300 shadow-sm px-4 py-2 bg-white text-base font-medium text-gray-700 hover:text-gray-500 focus:outline-none focus:shadow-outline-indigo sm:mt-0 sm:w-auto sm:text-sm"
>
Cancel
</button>
</div>
</div>
</Transition.Child>
</div>
</div>
</Dialog>
</Transition>
</>
)
}
@@ -0,0 +1,101 @@
import React, { useState } from 'react'
import { RadioGroup } from '@headlessui/react'
import { classNames } from '../../src/utils/class-names'
export default function Home() {
let access = [
{
id: 'access-1',
name: 'Public access',
description: 'This project would be available to anyone who has the link',
},
{
id: 'access-2',
name: 'Private to Project Members',
description: 'Only members of this project would be able to access',
},
{
id: 'access-3',
name: 'Private to you',
description: 'You are the only one able to access this project',
},
]
let [active, setActive] = useState()
return (
<div className="p-12 max-w-xl">
<a href="/">Link before</a>
<RadioGroup value={active} onChange={setActive}>
<fieldset className="space-y-4">
<legend>
<h2 className="text-xl">Privacy setting</h2>
</legend>
<div className="bg-white rounded-md -space-y-px">
{access.map(({ id, name, description }, i) => {
return (
<RadioGroup.Option
key={id}
value={id}
className={({ active }) =>
classNames(
// Rounded corners
i === 0 && 'rounded-tl-md rounded-tr-md',
access.length - 1 === i && 'rounded-bl-md rounded-br-md',
// Shared
'relative border p-4 flex focus:outline-none',
active ? 'bg-indigo-50 border-indigo-200 z-10' : 'border-gray-200'
)
}
>
{({ active, checked }) => (
<div className="flex justify-between items-center w-full">
<div className="ml-3 flex flex-col cursor-pointer">
<span
className={classNames(
'block text-sm leading-5 font-medium',
active ? 'text-indigo-900' : 'text-gray-900'
)}
>
{name}
</span>
<span
className={classNames(
'block text-sm leading-5',
active ? 'text-indigo-700' : 'text-gray-500'
)}
>
{description}
</span>
</div>
<div>
{checked && (
<svg
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
className="h-5 w-5 text-indigo-500"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"
/>
</svg>
)}
</div>
</div>
)}
</RadioGroup.Option>
)
})}
</div>
</fieldset>
</RadioGroup>
<a href="/">Link after</a>
</div>
)
}
@@ -0,0 +1,49 @@
## Alert
A component for announcing information to screenreader/assistive technology users.
- [Installation](#installation)
- [Basic example](#basic-example)
- [Component API](#component-api)
### Installation
```sh
# npm
npm install @headlessui/react
# Yarn
yarn add @headlessui/react
```
### Basic example
```jsx
<Alert>Notifications have been enabled</Alert>
```
### Component API
#### Alert
```jsx
<Alert>Notifications have been enabled</Alert>
```
##### Props
| Prop | Type | Default | Description |
| :----------- | :---------------------- | :------- | :------------------------------------------------------------------------------ |
| `as` | String \| Component | `div` | The element or component the `Alert` should render as. |
| `importance` | `polite` \| `assertive` | `polite` | The importance of the alert message when it is announced to screenreader users. |
| Importance | Description |
| :---------- | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `polite` | Indicates that updates to the region should be presented at the next graceful opportunity, such as at the end of speaking the current sentence or when the user pauses typing. |
| `assertive` | Indicates that updates to the region have the highest priority and should be presented the user immediately. |
Source: https://www.w3.org/TR/wai-aria-1.2/#aria-live
##### Render prop object
- None
@@ -0,0 +1,31 @@
import React from 'react'
import { render } from '@testing-library/react'
import { getByText } from '../../test-utils/accessibility-assertions'
import { Alert } from './alert'
describe('Rendering', () => {
it('should be possible to render an Alert', () => {
render(<Alert>This is an alert</Alert>)
expect(getByText('This is an alert')).toHaveAttribute('role', 'status')
})
it('should be possible to render an Alert using a render prop', () => {
render(<Alert>{() => 'This is an alert'}</Alert>)
expect(getByText('This is an alert')).toHaveAttribute('role', 'status')
})
it('should be possible to render an Alert with an explicit level of importance (polite)', () => {
render(<Alert importance="polite">This is a polite message</Alert>)
expect(getByText('This is a polite message')).toHaveAttribute('role', 'status')
})
it('should be possible to render an Alert with an explicit level of importance (assertive)', () => {
render(<Alert importance="assertive">This is a assertive message</Alert>)
expect(getByText('This is a assertive message')).toHaveAttribute('role', 'alert')
})
})
@@ -0,0 +1,48 @@
import {
useMemo,
// Types
ElementType,
} from 'react'
import { Props } from '../../types'
import { render } from '../../utils/render'
import { match } from '../../utils/match'
type Importance =
/**
* Indicates that updates to the region should be presented at the next
* graceful opportunity, such as at the end of speaking the current sentence
* or when the user pauses typing.
*/
| 'polite'
/**
* Indicates that updates to the region have the highest priority and should
* be presented the user immediately.
*/
| 'assertive'
// ---
let DEFAULT_ALERT_TAG = 'div' as const
interface AlertRenderPropArg {
importance: Importance
}
type AlertPropsWeControl = 'role'
export function Alert<TTag extends ElementType = typeof DEFAULT_ALERT_TAG>(
props: Props<TTag, AlertRenderPropArg, AlertPropsWeControl> & {
importance?: Importance
}
) {
let { importance = 'polite', ...passThroughProps } = props
let propsWeControl = match(importance, {
polite: () => ({ role: 'status' }),
assertive: () => ({ role: 'alert' }),
})
let bag = useMemo<AlertRenderPropArg>(() => ({ importance }), [importance])
return render({ ...passThroughProps, ...propsWeControl }, bag, DEFAULT_ALERT_TAG)
}
@@ -0,0 +1,108 @@
import { render } from '@testing-library/react'
import { Description, useDescriptions } from './description'
import React, { ReactNode } from 'react'
jest.mock('../../hooks/use-id')
it('should be possible to use a DescriptionProvider without using a Description', async () => {
function Component(props: { children: ReactNode }) {
let [describedby, DescriptionProvider] = useDescriptions()
return (
<DescriptionProvider>
<div aria-describedby={describedby}>{props.children}</div>
</DescriptionProvider>
)
}
function Example() {
return <Component>No description</Component>
}
let { container } = render(<Example />)
expect(container.firstChild).toMatchInlineSnapshot(`
<div>
No description
</div>
`)
})
it('should be possible to use a DescriptionProvider and a single Description, and have them linked', async () => {
function Component(props: { children: ReactNode }) {
let [describedby, DescriptionProvider] = useDescriptions()
return (
<DescriptionProvider>
<div aria-describedby={describedby}>{props.children}</div>
</DescriptionProvider>
)
}
function Example() {
return (
<Component>
<Description>I am a description</Description>
<span>Contents</span>
</Component>
)
}
let { container } = render(<Example />)
expect(container.firstChild).toMatchInlineSnapshot(`
<div
aria-describedby="headlessui-description-1"
>
<p
id="headlessui-description-1"
>
I am a description
</p>
<span>
Contents
</span>
</div>
`)
})
it('should be possible to use a DescriptionProvider and multiple Description ocmponents, and have them linked', async () => {
function Component(props: { children: ReactNode }) {
let [describedby, DescriptionProvider] = useDescriptions()
return (
<DescriptionProvider>
<div aria-describedby={describedby}>{props.children}</div>
</DescriptionProvider>
)
}
function Example() {
return (
<Component>
<Description>I am a description</Description>
<span>Contents</span>
<Description>I am also a description</Description>
</Component>
)
}
let { container } = render(<Example />)
expect(container.firstChild).toMatchInlineSnapshot(`
<div
aria-describedby="headlessui-description-1 headlessui-description-2"
>
<p
id="headlessui-description-1"
>
I am a description
</p>
<span>
Contents
</span>
<p
id="headlessui-description-2"
>
I am also a description
</p>
</div>
`)
})
@@ -0,0 +1,86 @@
import React, {
createContext,
useCallback,
useContext,
useMemo,
useState,
// Types
ElementType,
ReactNode,
} from 'react'
import { Props } from '../../types'
import { useId } from '../../hooks/use-id'
import { render } from '../../utils/render'
import { useIsoMorphicEffect } from '../../hooks/use-iso-morphic-effect'
// ---
let DescriptionContext = createContext<{ register(value: string): () => void }>({
register() {
return () => {}
},
})
function useDescriptionContext() {
return useContext(DescriptionContext)
}
export function useDescriptions(): [
string | undefined,
(props: { children: ReactNode }) => JSX.Element
] {
let [descriptionIds, setDescriptionIds] = useState<string[]>([])
return [
// The actual id's as string or undefined
descriptionIds.length > 0 ? descriptionIds.join(' ') : undefined,
// The provider component
useMemo(() => {
return function DescriptionProvider(props: { children: ReactNode }) {
let register = useCallback((value: string) => {
setDescriptionIds(existing => [...existing, value])
return () =>
setDescriptionIds(existing => {
let clone = existing.slice()
let idx = clone.indexOf(value)
if (idx !== -1) clone.splice(idx, 1)
return clone
})
}, [])
let contextBag = useMemo(() => ({ register }), [register])
return (
<DescriptionContext.Provider value={contextBag}>
{props.children}
</DescriptionContext.Provider>
)
}
}, [setDescriptionIds]),
]
}
// ---
let DEFAULT_DESCRIPTION_TAG = 'p' as const
interface DescriptionRenderPropArg {}
type DescriptionPropsWeControl = 'id'
export function Description<TTag extends ElementType = typeof DEFAULT_DESCRIPTION_TAG>(
props: Props<TTag, DescriptionRenderPropArg, DescriptionPropsWeControl>
) {
let { register } = useDescriptionContext()
let id = `headlessui-description-${useId()}`
useIsoMorphicEffect(() => register(id), [id, register])
let passThroughProps = props
let propsWeControl = { id }
let bag = useMemo<DescriptionRenderPropArg>(() => ({}), [])
return render({ ...passThroughProps, ...propsWeControl }, bag, DEFAULT_DESCRIPTION_TAG)
}
@@ -0,0 +1,155 @@
## Dialog
- [Installation](#installation)
- [Basic example](#basic-example)
- [Component API](#component-api)
This component can be used to render content inside a Dialog/Modal. This contains a ton of features:
1. Renders inside a `Portal`
2. Controlled component
3. Uses `FocusTrap` with its features (Focus first focusable element, `autoFocus` or `initialFocus` ref)
> **NOTE:** This component will throw when there are no focusable elements.
> This is an accessibility feature. At least try to provide a close button or
> similar so that users don't get stuck.
4. Adds a scroll lock
5. Prevents content jumps by faking your scrollbar width
6. Marks other elements as `inert` (hides other elements from screen readers)
7. Closes on `escape`
8. Closes on click outside
9. Once the Dialog becomes hidden (e.g.: `md:hidden`) it will also trigger the `onClose`
### Installation
```sh
# npm
npm install @headlessui/react
# Yarn
yarn add @headlessui/react
```
### Basic example
```jsx
import { useState } from 'react'
import { Dialog } from '@headlessui/react'
function Example() {
let [isOpen, setIsOpen] = useState(true)
return (
<Dialog open={isOpen} onClose={setIsOpen}>
<Dialog.Overlay />
<Dialog.Title>Deactivate account</Dialog.Title>
<Dialog.Description>This will permanently deactivate your account</Dialog.Description>
<p>
Are you sure you want to deactivate your account? All of your data will be permanently
removed. This action cannot be undone.
</p>
<button onClick={() => setIsOpen(false)}>Deactivate</button>
<button onClick={() => setIsOpen(false)}>Cancel</button>
</Dialog>
)
}
```
### Component API
#### Dialog
```jsx
import { useState } from 'react'
import { Dialog } from '@headlessui/react'
function Example() {
let [isOpen, setIsOpen] = useState(true)
return (
<Dialog open={isOpen} onClose={setIsOpen}>
<Dialog.Overlay />
<Dialog.Title>Deactivate account</Dialog.Title>
<Dialog.Description>This will permanently deactivate your account</Dialog.Description>
<p>
Are you sure you want to deactivate your account? All of your data will be permanently
removed. This action cannot be undone.
</p>
<button onClick={() => setIsOpen(false)}>Deactivate</button>
<button onClick={() => setIsOpen(false)}>Cancel</button>
</Dialog>
)
}
```
##### Props
| Prop | Type | Default | Description |
| :------------- | :--------------------- | :------ | :------------------------------------------------------------------------------------------------------------------------------- |
| `open` | Boolean | / | Wether the `Dialog` is open or not. |
| `onClose` | Function | / | Called when the `Dialog` should close. For convenience we pass in a `onClose(false)` so that you can use: `onClose={setIsOpen}`. |
| `initialFocus` | React.MutableRefObject | / | A ref to an element that should receive focus first. |
| `as` | String \| Component | `div` | The element or component the `Dialog` should render as. |
| `static` | Boolean | `false` | Whether the element should ignore the internally managed open/closed state. |
| `unmount` | Boolean | `true` | Whether the element should be unmounted or hidden based on the open/closed state. |
> **note**: `static` and `unmount` can not be used at the same time. You will get a TypeScript error if you try to do it.
##### Render prop object
| Prop | Type | Description |
| :----- | :------ | :--------------------------------- |
| `open` | Boolean | Whether or not the dialog is open. |
#### Dialog.Overlay
This can be used to create an overlay for your Dialog component. Clicking on the overlay will close the Dialog.
##### Props
| Prop | Type | Default | Description |
| :--- | :------------------ | :------ | :-------------------------------------------------------------- |
| `as` | String \| Component | `div` | The element or component the `Dialog.Overlay` should render as. |
##### Render prop object
| Prop | Type | Description |
| :----- | :------ | :------------------------------------- |
| `open` | Boolean | Whether or not the disclosure is open. |
#### Dialog.Title
This is the title for your Dialog. When this is used, it will set the `aria-labelledby` on the Dialog.
##### Props
| Prop | Type | Default | Description |
| :--- | :------------------ | :------ | :------------------------------------------------------------ |
| `as` | String \| Component | `h2` | The element or component the `Dialog.Title` should render as. |
##### Render prop object
| Prop | Type | Description |
| :----- | :------ | :------------------------------------- |
| `open` | Boolean | Whether or not the disclosure is open. |
#### Dialog.Description
This is the description for your Dialog. When this is used, it will set the `aria-describedby` on the Dialog.
##### Props
| Prop | Type | Default | Description |
| :--- | :------------------ | :------ | :------------------------------------------------------------------ |
| `as` | String \| Component | `p` | The element or component the `Dialog.Description` should render as. |
##### Render prop object
| Prop | Type | Description |
| :----- | :------ | :------------------------------------- |
| `open` | Boolean | Whether or not the disclosure is open. |
@@ -1,19 +1,19 @@
// WAI-ARIA: https://www.w3.org/TR/wai-aria-practices-1.2/#dialog_modal
import React, {
createContext,
useContext,
useReducer,
useMemo,
useCallback,
useContext,
useEffect,
useMemo,
useReducer,
useRef,
// Types
ElementType,
Ref,
MouseEvent as ReactMouseEvent,
useEffect,
useRef,
ContextType,
ElementType,
MouseEvent as ReactMouseEvent,
MutableRefObject,
Ref,
} from 'react'
import { Props } from '../../types'
@@ -27,6 +27,7 @@ import { useFocusTrap } from '../../hooks/use-focus-trap'
import { useInertOthers } from '../../hooks/use-inert-others'
import { Portal } from '../../components/portal/portal'
import { StackProvider, StackMessage } from '../../internal/stack-context'
import { ForcePortalRoot } from '../../internal/portal-force-root'
import { contains } from '../../internal/dom-containers'
enum DialogStates {
@@ -277,17 +278,23 @@ let DialogRoot = forwardRefWithAs(function Dialog<
})
}}
>
<Portal>
<DialogContext.Provider value={contextBag}>
{render(
{ ...passthroughProps, ...propsWeControl },
propsBag,
DEFAULT_DIALOG_TAG,
DialogRenderFeatures,
dialogState === DialogStates.Open
)}
</DialogContext.Provider>
</Portal>
<ForcePortalRoot force={true}>
<Portal>
<DialogContext.Provider value={contextBag}>
<Portal.Group target={internalDialogRef}>
<ForcePortalRoot force={false}>
{render(
{ ...passthroughProps, ...propsWeControl },
propsBag,
DEFAULT_DIALOG_TAG,
DialogRenderFeatures,
dialogState === DialogStates.Open
)}
</ForcePortalRoot>
</Portal.Group>
</DialogContext.Provider>
</Portal>
</ForcePortalRoot>
</StackProvider>
)
})
@@ -0,0 +1,81 @@
## Disclosure
A component for showing/hiding content.
- [Installation](#installation)
- [Basic example](#basic-example)
- [Component API](#component-api)
### Installation
```sh
# npm
npm install @headlessui/react
# Yarn
yarn add @headlessui/react
```
### Basic example
```jsx
<Disclosure>
<Disclosure.Button>Toggle</Disclosure.Button>
<Disclosure.Panel>Contents</Disclosure.Panel>
</Disclosure>
```
### Component API
#### Disclosure
```jsx
<Disclosure>
<Disclosure.Button>Toggle</Disclosure.Button>
<Disclosure.Panel>Contents</Disclosure.Panel>
</Disclosure>
```
##### Props
| Prop | Type | Default | Description |
| :--- | :------------------ | :-------------------------------------- | :---------------------------------------------------------- |
| `as` | String \| Component | `React.Fragment` _(no wrapper element_) | The element or component the `Disclosure` should render as. |
##### Render prop object
| Prop | Type | Description |
| :----- | :------ | :------------------------------------- |
| `open` | Boolean | Whether or not the disclosure is open. |
#### Disclosure.Button
##### Props
| Prop | Type | Default | Description |
| :--- | :------------------ | :------- | :----------------------------------------------------------------- |
| `as` | String \| Component | `button` | The element or component the `Disclosure.Button` should render as. |
##### Render prop object
| Prop | Type | Description |
| :----- | :------ | :------------------------------------- |
| `open` | Boolean | Whether or not the disclosure is open. |
#### Disclosure.Panel
##### Props
| Prop | Type | Default | Description |
| :-------- | :------------------ | :------ | :-------------------------------------------------------------------------------- |
| `as` | String \| Component | `div` | The element or component the `Disclosure.Panel` should render as. |
| `static` | Boolean | `false` | Whether the element should ignore the internally managed open/closed state. |
| `unmount` | Boolean | `true` | Whether the element should be unmounted or hidden based on the open/closed state. |
> **note**: `static` and `unmount` can not be used at the same time. You will get a TypeScript error if you try to do it.
##### Render prop object
| Prop | Type | Description |
| :----- | :------ | :------------------------------------- |
| `open` | Boolean | Whether or not the disclosure is open. |
@@ -1,19 +1,19 @@
// WAI-ARIA: https://www.w3.org/TR/wai-aria-practices-1.2/#disclosure
import React, {
createContext,
useContext,
Fragment,
useReducer,
createContext,
useCallback,
useContext,
useEffect,
useMemo,
useCallback,
useReducer,
// Types
Dispatch,
ElementType,
Ref,
KeyboardEvent as ReactKeyboardEvent,
MouseEvent as ReactMouseEvent,
Ref,
} from 'react'
import { Props } from '../../types'
@@ -0,0 +1,64 @@
## FocusTrap
- [Installation](#installation)
- [Basic example](#basic-example)
- [Component API](#component-api)
A component for making sure that you can't Tab out of the contents of this
component.
Focus strategy:
- An `initialFocus` prop can be passed in, this is a `ref` object, which is a ref to the element that should receive initial focus.
- If an input element exists with an `autoFocus` prop, it will receive initial focus.
- If none of those exists, it will try and focus the first focusable element.
- If that doesn't exist, it will throw an error.
Once the `FocusTrap` will unmount, the focus will be restored to the element that was focused _before_ the `FocusTrap` was rendered.
> **NOTE:** This component will throw when there are no focusable elements.
> This is an accessibility feature. At least try to provide a close button or
> similar so that users don't get stuck.
### Installation
```sh
# npm
npm install @headlessui/react
# Yarn
yarn add @headlessui/react
```
### Basic example
```jsx
<FocusTrap>
<form>
<input type="email" name="Email" />
<input type="password" name="password" />
<button>Submit</button>
</form>
</FocusTrap>
```
### Component API
#### FocusTrap
```jsx
<FocusTrap>
<form>
<input type="email" name="Email" />
<input type="password" name="password" />
<button>Submit</button>
</form>
</FocusTrap>
```
##### Props
| Prop | Type | Default | Description |
| :------------- | :--------------------- | :---------- | :--------------------------------------------------------- |
| `as` | String \| Component | `div` | The element or component the `FocusTrap` should render as. |
| `initialFocus` | React.MutableRefObject | `undefined` | A ref to an element that should receive focus first. |
@@ -6,7 +6,9 @@ export enum Keys {
Escape = 'Escape',
Backspace = 'Backspace',
ArrowLeft = 'ArrowLeft',
ArrowUp = 'ArrowUp',
ArrowRight = 'ArrowRight',
ArrowDown = 'ArrowDown',
Home = 'Home',
@@ -0,0 +1,108 @@
import { render } from '@testing-library/react'
import { Label, useLabels } from './label'
import React, { ReactNode } from 'react'
jest.mock('../../hooks/use-id')
it('should be possible to use a LabelProvider without using a Label', async () => {
function Component(props: { children: ReactNode }) {
let [labelledby, LabelProvider] = useLabels()
return (
<LabelProvider>
<div aria-labelledby={labelledby}>{props.children}</div>
</LabelProvider>
)
}
function Example() {
return <Component>No label</Component>
}
let { container } = render(<Example />)
expect(container.firstChild).toMatchInlineSnapshot(`
<div>
No label
</div>
`)
})
it('should be possible to use a LabelProvider and a single Label, and have them linked', async () => {
function Component(props: { children: ReactNode }) {
let [labelledby, LabelProvider] = useLabels()
return (
<LabelProvider>
<div aria-labelledby={labelledby}>{props.children}</div>
</LabelProvider>
)
}
function Example() {
return (
<Component>
<Label>I am a label</Label>
<span>Contents</span>
</Component>
)
}
let { container } = render(<Example />)
expect(container.firstChild).toMatchInlineSnapshot(`
<div
aria-labelledby="headlessui-label-1"
>
<label
id="headlessui-label-1"
>
I am a label
</label>
<span>
Contents
</span>
</div>
`)
})
it('should be possible to use a LabelProvider and multiple Label ocmponents, and have them linked', async () => {
function Component(props: { children: ReactNode }) {
let [labelledby, LabelProvider] = useLabels()
return (
<LabelProvider>
<div aria-labelledby={labelledby}>{props.children}</div>
</LabelProvider>
)
}
function Example() {
return (
<Component>
<Label>I am a label</Label>
<span>Contents</span>
<Label>I am also a label</Label>
</Component>
)
}
let { container } = render(<Example />)
expect(container.firstChild).toMatchInlineSnapshot(`
<div
aria-labelledby="headlessui-label-1 headlessui-label-2"
>
<label
id="headlessui-label-1"
>
I am a label
</label>
<span>
Contents
</span>
<label
id="headlessui-label-2"
>
I am also a label
</label>
</div>
`)
})
@@ -0,0 +1,82 @@
import React, {
createContext,
useCallback,
useContext,
useMemo,
useState,
// Types
ElementType,
ReactNode,
} from 'react'
import { Props } from '../../types'
import { useId } from '../../hooks/use-id'
import { render } from '../../utils/render'
import { useIsoMorphicEffect } from '../../hooks/use-iso-morphic-effect'
// ---
let LabelContext = createContext<{ register(value: string): () => void }>({
register() {
return () => {}
},
})
function useLabelContext() {
return useContext(LabelContext)
}
export function useLabels(
id?: string
): [string | undefined, (props: { children: ReactNode }) => JSX.Element] {
let [labelIds, setLabelIds] = useState<string[]>([])
return [
// The actual id's as string or undefined. If there are labels defined and
// we got an id passed in, let's add it as well!
labelIds.length > 0 ? (id ? [id, ...labelIds].join(' ') : labelIds.join(' ')) : undefined,
// The provider component
useMemo(() => {
return function LabelProvider(props: { children: ReactNode }) {
let register = useCallback((value: string) => {
setLabelIds(existing => [...existing, value])
return () =>
setLabelIds(existing => {
let clone = existing.slice()
let idx = clone.indexOf(value)
if (idx !== -1) clone.splice(idx, 1)
return clone
})
}, [])
let contextBag = useMemo(() => ({ register }), [register])
return <LabelContext.Provider value={contextBag}>{props.children}</LabelContext.Provider>
}
}, [setLabelIds]),
]
}
// ---
let DEFAULT_LABEL_TAG = 'label' as const
interface LabelRenderPropArg {}
type LabelPropsWeControl = 'id'
export function Label<TTag extends ElementType = typeof DEFAULT_LABEL_TAG>(
props: Props<TTag, LabelRenderPropArg, LabelPropsWeControl>
) {
let { register } = useLabelContext()
let id = `headlessui-label-${useId()}`
useIsoMorphicEffect(() => register(id), [id, register])
let passThroughProps = props
let propsWeControl = { id }
let bag = useMemo<LabelRenderPropArg>(() => ({}), [])
return render({ ...passThroughProps, ...propsWeControl }, bag, DEFAULT_LABEL_TAG)
}
@@ -0,0 +1,520 @@
## Listbox (Select)
[View live demo on CodeSandbox](https://codesandbox.io/s/headlessuireact-listbox-example-57eoj?file=/src/App.js)
The `Listbox` component and related child components are used to quickly build custom listbox components that are fully accessible out of the box, including correct ARIA attribute management and robust keyboard navigation support.
- [Installation](#installation)
- [Basic example](#basic-example)
- [Styling the active and selected option](#styling-the-active-and-selected-option)
- [Showing/hiding the listbox](#showinghiding-the-listbox)
- [Using a custom label](#using-a-custom-label)
- [Disabling an option](#disabling-an-option)
- [Transitions](#transitions)
- [Rendering additional content](#rendering-additional-content)
- [Rendering a different element for a component](#rendering-a-different-element-for-a-component)
- [Component API](#component-api)
### Installation
```sh
# npm
npm install @headlessui/react
# Yarn
yarn add @headlessui/react
```
### Basic example
Listboxes are built using the `Listbox`, `Listbox.Button`, `Listbox.Options`, `Listbox.Option` and `Listbox.Label` components.
The `Listbox.Button` will automatically open/close the `Listbox.Options` when clicked, and when the menu is open, the list of items receives focus and is automatically navigable via the keyboard.
```jsx
import { useState } from 'react'
import { Listbox } from '@headlessui/react'
const people = [
{ id: 1, name: 'Durward Reynolds', unavailable: false },
{ id: 2, name: 'Kenton Towne', unavailable: false },
{ id: 3, name: 'Therese Wunsch', unavailable: false },
{ id: 4, name: 'Benedict Kessler', unavailable: true },
{ id: 5, name: 'Katelyn Rohan', unavailable: false },
]
function MyListbox() {
const [selectedPerson, setSelectedPerson] = useState(people[0])
return (
<Listbox value={selectedPerson} onChange={setSelectedPerson}>
<Listbox.Button>{selectedPerson.name}</Listbox.Button>
<Listbox.Options>
{people.map(person => (
<Listbox.Option key={person.id} value={person} disabled={person.unavailable}>
{person.name}
</Listbox.Option>
))}
</Listbox.Options>
</Listbox>
)
}
```
### Styling the active and selected option
This is a headless component so there are no styles included by default. Instead, the components expose useful information via [render props](https://reactjs.org/docs/render-props.html) that you can use to apply the styles you'd like to apply yourself.
To style the active `Listbox.Option` you can read the `active` render prop argument, which tells you whether or not that listbox option is the option that is currently focused via the mouse or keyboard.
To style the selected `Listbox.Option` you can read the `selected` render prop argument, which tells you whether or not that listbox option is the option that is currently the `value` passed to the `Listbox`.
> Note: An option can be both **active** and **selected** at the same time!
You can use this state to conditionally apply whatever active/focus styles you like, for instance a blue background like is typical in most operating systems. For the selected state, a checkmark is also common.
```jsx
import { useState, Fragment } from 'react'
import { Listbox } from '@headlessui/react'
import CheckmarkIcon from './CheckmarkIcon'
const people = [
{ id: 1, name: 'Durward Reynolds' },
{ id: 2, name: 'Kenton Towne' },
{ id: 3, name: 'Therese Wunsch' },
{ id: 4, name: 'Benedict Kessler' },
{ id: 5, name: 'Katelyn Rohan' },
]
function MyListbox() {
const [selectedPerson, setSelectedPerson] = useState(people[0])
return (
<Listbox value={selectedPerson} onChange={setSelectedPerson}>
<Listbox.Button>{selectedPerson.name}</Listbox.Button>
<Listbox.Options>
{people.map(person => (
/* Use the `active` state to conditionally style the active option. */
/* Use the `selected` state to conditionally style the selected option. */
<Listbox.Option as={Fragment} key={person.id} value={person}>
{({ active, selected }) => (
<li className={`${active ? 'bg-blue-500 text-white' : 'bg-white text-black'}`}>
{selected && <CheckmarkIcon />}
{person.name}
</li>
)}
</Listbox.Option>
))}
</Listbox.Options>
</Listbox>
)
}
```
### Using a custom label
By default the `Listbox` will use the button contents as the label for screenreaders. However you can also render a custom `Listbox.Label`.
```jsx
import { useState, Fragment } from 'react'
import { Listbox } from '@headlessui/react'
const people = [
{ id: 1, name: 'Durward Reynolds' },
{ id: 2, name: 'Kenton Towne' },
{ id: 3, name: 'Therese Wunsch' },
{ id: 4, name: 'Benedict Kessler' },
{ id: 5, name: 'Katelyn Rohan' },
]
function MyListbox() {
const [selectedPerson, setSelectedPerson] = useState(people[0])
return (
<Listbox value={selectedPerson} onChange={setSelectedPerson}>
<Listbox.Label>Assignee:</Listbox.Label>
<Listbox.Button>{selectedPerson.name}</Listbox.Button>
<Listbox.Options>
{people.map(person => (
<Listbox.Option as={Fragment} key={person.id} value={person}>
{person.name}
</Listbox.Option>
))}
</Listbox.Options>
</Listbox>
)
}
```
### Showing/hiding the listbox
By default, your `Listbox.Options` instance will be shown/hidden automatically based on the internal `open` state tracked within the `Listbox` component itself.
```jsx
import { useState } from 'react'
import { Listbox } from '@headlessui/react'
const people = [
{ id: 1, name: 'Durward Reynolds', unavailable: false },
{ id: 2, name: 'Kenton Towne', unavailable: false },
{ id: 3, name: 'Therese Wunsch', unavailable: false },
{ id: 4, name: 'Benedict Kessler', unavailable: true },
{ id: 5, name: 'Katelyn Rohan', unavailable: false },
]
function MyListbox() {
const [selectedPerson, setSelectedPerson] = useState(people[0])
return (
<Listbox value={selectedPerson} onChange={setSelectedPerson}>
<Listbox.Button>{selectedPerson.name}</Listbox.Button>
{/* By default, this will automatically show/hide when the Listbox.Button is pressed. */}
<Listbox.Options>
{people.map(person => (
<Listbox.Option key={person.id} value={person} disabled={person.unavailable}>
{person.name}
</Listbox.Option>
))}
</Listbox.Options>
</Listbox>
)
}
```
If you'd rather handle this yourself (perhaps because you need to add an extra wrapper element for one reason or another), you can add a `static` prop to the `Listbox.Options` instance to tell it to always render, and inspect the `open` slot prop provided by the `Listbox` to control which element is shown/hidden yourself.
```jsx
import { useState } from 'react'
import { Listbox } from '@headlessui/react'
const people = [
{ id: 1, name: 'Durward Reynolds', unavailable: false },
{ id: 2, name: 'Kenton Towne', unavailable: false },
{ id: 3, name: 'Therese Wunsch', unavailable: false },
{ id: 4, name: 'Benedict Kessler', unavailable: true },
{ id: 5, name: 'Katelyn Rohan', unavailable: false },
]
function MyListbox() {
const [selectedPerson, setSelectedPerson] = useState(people[0])
return (
<Listbox value={selectedPerson} onChange={setSelectedPerson}>
{({ open }) => (
<>
<Listbox.Button>{selectedPerson.name}</Listbox.Button>
{open && (
<div>
{/* Using `static`, `Listbox.Options` is always rendered and ignores the `open` state. */}
<Listbox.Options static>
{people.map(person => (
<Listbox.Option key={person.id} value={person} disabled={person.unavailable}>
{person.name}
</Listbox.Option>
))}
</Listbox.Options>
</div>
)}
</>
)}
</Listbox>
)
}
```
### Disabling an option
Use the `disabled` prop to disable a `Listbox.Option`. This will make it unselectable via keyboard navigation, and it will be skipped when pressing the up/down arrows.
```jsx
import { useState } from 'react'
import { Listbox } from '@headlessui/react'
const people = [
{ id: 1, name: 'Durward Reynolds', unavailable: false },
{ id: 2, name: 'Kenton Towne', unavailable: false },
{ id: 3, name: 'Therese Wunsch', unavailable: false },
{ id: 4, name: 'Benedict Kessler', unavailable: true },
{ id: 5, name: 'Katelyn Rohan', unavailable: false },
]
function MyListbox() {
const [selectedPerson, setSelectedPerson] = useState(people[0])
return (
<Listbox value={selectedPerson} onChange={setSelectedPerson}>
<Listbox.Button>{selectedPerson.name}</Listbox.Button>
<Listbox.Options>
{people.map(person => (
/* Disabled options will be skipped by keyboard navigation. */
<Listbox.Option key={person.id} value={person} disabled={person.unavailable}>
<span className={person.unavailable ? 'opacity-75' : ''}>{person.name}</span>
</Listbox.Option>
))}
</Listbox.Options>
</Listbox>
)
}
```
### Transitions
To animate the opening/closing of the listbox panel, use the provided `Transition` component. All you need to do is mark your `Listbox.Options` as `static`, wrap it in a `<Transition>`, and the transition will be applied automatically.
```jsx
import { useState } from 'react'
import { Listbox, Transition } from '@headlessui/react'
const people = [
{ id: 1, name: 'Durward Reynolds', unavailable: false },
{ id: 2, name: 'Kenton Towne', unavailable: false },
{ id: 3, name: 'Therese Wunsch', unavailable: false },
{ id: 4, name: 'Benedict Kessler', unavailable: true },
{ id: 5, name: 'Katelyn Rohan', unavailable: false },
]
function MyListbox() {
const [selectedPerson, setSelectedPerson] = useState(people[0])
return (
<Listbox value={selectedPerson} onChange={setSelectedPerson}>
{({ open }) => (
<>
<Listbox.Button>{selectedPerson.name}</Listbox.Button>
{/* Use the Transition + open render prop argument to add transitions. */}
<Transition
show={open}
enter="transition duration-100 ease-out"
enterFrom="transform scale-95 opacity-0"
enterTo="transform scale-100 opacity-100"
leave="transition duration-75 ease-out"
leaveFrom="transform scale-100 opacity-100"
leaveTo="transform scale-95 opacity-0"
>
<Listbox.Options static>
{people.map(person => (
<Listbox.Option key={person.id} value={person} disabled={person.unavailable}>
{person.name}
</Listbox.Option>
))}
</Listbox.Options>
</Transition>
</>
)}
</Listbox>
)
}
```
### Rendering a different element for a component
By default, the `Listbox` and its subcomponents each render a default element that is sensible for that component.
For example, `Listbox.Label` renders a `label` by default, `Listbox.Button` renders a `button` by default, `Listbox.Options` renders a `ul` and `Listbox.Option` renders a `li` by default. `Listbox` interestingly _does not render an extra element_, and instead renders its children directly by default.
This is easy to change using the `as` prop, which exists on every component.
```jsx
import { useState } from 'react'
import { Listbox } from '@headlessui/react'
const people = [
{ id: 1, name: 'Durward Reynolds' },
{ id: 2, name: 'Kenton Towne' },
{ id: 3, name: 'Therese Wunsch' },
{ id: 4, name: 'Benedict Kessler' },
{ id: 5, name: 'Katelyn Rohan' },
]
function MyListbox() {
const [selectedPerson, setSelectedPerson] = useState(people[0])
return (
<Listbox as="div" value={selectedPerson} onChange={setSelectedPerson}>
<Listbox.Button>{selectedPerson.name}</Listbox.Button>
<Listbox.Options as="div">
{people.map(person => (
<Listbox.Option as="span" key={person.id} value={person}>
{person.name}
</Listbox.Option>
))}
</Listbox.Options>
</Listbox>
)
}
```
To tell an element to render its children directly with no wrapper element, use `as={React.Fragment}`.
```jsx
import { useState, Fragment } from 'react'
import { Listbox } from '@headlessui/react'
const people = [
{ id: 1, name: 'Durward Reynolds' },
{ id: 2, name: 'Kenton Towne' },
{ id: 3, name: 'Therese Wunsch' },
{ id: 4, name: 'Benedict Kessler' },
{ id: 5, name: 'Katelyn Rohan' },
]
function MyListbox() {
const [selectedPerson, setSelectedPerson] = useState(people[0])
return (
<Listbox value={selectedPerson} onChange={setSelectedPerson}>
<Listbox.Button as={Fragment}>{selectedPerson.name}</Listbox.Button>
<Listbox.Options>
{people.map(person => (
<Listbox.Option key={person.id} value={person}>
{person.name}
</Listbox.Option>
))}
</Listbox.Options>
</Listbox>
)
}
```
### Component API
#### Listbox
```jsx
import { useState } from 'react'
import { Listbox } from '@headlessui/react'
const people = [
{ id: 1, name: 'Durward Reynolds' },
{ id: 2, name: 'Kenton Towne' },
{ id: 3, name: 'Therese Wunsch' },
{ id: 4, name: 'Benedict Kessler' },
{ id: 5, name: 'Katelyn Rohan' },
]
function MyListbox() {
const [selectedPerson, setSelectedPerson] = useState(people[0])
return (
<Listbox value={selectedPerson} onChange={setSelectedPerson}>
<Listbox.Button>{selectedPerson.name}</Listbox.Button>
<Listbox.Options>
{people.map(person => (
<Listbox.Option key={person.id} value={person}>
{person.name}
</Listbox.Option>
))}
</Listbox.Options>
</Listbox>
)
}
```
##### Props
| Prop | Type | Default | Description |
| :--------- | :------------------ | :-------------------------------------- | :------------------------------------------------------- |
| `as` | String \| Component | `React.Fragment` _(no wrapper element_) | The element or component the `Listbox` should render as. |
| `disabled` | Boolean | `false` | Enable/Disable the `Listbox` component. |
| `value` | `T` | - | The selected value. |
| `onChange` | `(value: T): void` | - | The function to call when a new option is selected. |
##### Render prop object
| Prop | Type | Description |
| :--------- | :------ | :-------------------------------------- |
| `open` | Boolean | Whether or not the listbox is open. |
| `disabled` | Boolean | Whether or not the listbox is disabled. |
#### Listbox.Button
```jsx
<Listbox.Button>
{({ open }) => (
<>
<span>More options</span>
<ChevronRightIcon className={`${open ? 'transform rotate-90' : ''}`} />
</>
)}
</Listbox.Button>
```
##### Props
| Prop | Type | Default | Description |
| :--- | :------------------ | :------- | :-------------------------------------------------------------- |
| `as` | String \| Component | `button` | The element or component the `Listbox.Button` should render as. |
##### Render prop object
| Prop | Type | Description |
| :--------- | :------ | :-------------------------------------- |
| `open` | Boolean | Whether or not the listbox is open. |
| `disabled` | Boolean | Whether or not the listbox is disabled. |
#### Listbox.Label
```jsx
<Listbox.Label>Enable notifications</Listbox.Label>
```
##### Props
| Prop | Type | Default | Description |
| :--- | :------------------ | :------ | :------------------------------------------------------------- |
| `as` | String \| Component | `label` | The element or component the `Listbox.Label` should render as. |
##### Render prop object
| Prop | Type | Description |
| :--------- | :------ | :-------------------------------------- |
| `open` | Boolean | Whether or not the listbox is open. |
| `disabled` | Boolean | Whether or not the listbox is disabled. |
#### Listbox.Options
```jsx
<Listbox.Options>
<Listbox.Option value="option-a">{/* ... */}></Listbox.Option>
{/* ... */}>
</Listbox.Options>
```
##### Props
| Prop | Type | Default | Description |
| :-------- | :------------------ | :------ | :-------------------------------------------------------------------------------- |
| `as` | String \| Component | `ul` | The element or component the `Listbox.Options` should render as. |
| `static` | Boolean | `false` | Whether the element should ignore the internally managed open/closed state. |
| `unmount` | Boolean | `true` | Whether the element should be unmounted or hidden based on the open/closed state. |
> **note**: `static` and `unmount` can not be used at the same time. You will get a TypeScript error if you try to do it.
##### Render prop object
| Prop | Type | Description |
| :----- | :------ | :---------------------------------- |
| `open` | Boolean | Whether or not the listbox is open. |
#### Listbox.Option
```jsx
<Listbox.Option value="option-a">Option A</Listbox.Option>
```
##### Props
| Prop | Type | Default | Description |
| :--------- | :------------------ | :------ | :-------------------------------------------------------------------------------------- |
| `as` | String \| Component | `li` | The element or component the `Listbox.Option` should render as. |
| `value` | `T` | - | The option value. |
| `disabled` | Boolean | `false` | Whether or not the option should be disabled for keyboard navigation and ARIA purposes. |
##### Render prop object
| Prop | Type | Description |
| :--------- | :------ | :----------------------------------------------------------------------------------- |
| `active` | Boolean | Whether or not the option is the active/focused option in the list. |
| `selected` | Boolean | Whether or not the option is the selected option in the list. |
| `disabled` | Boolean | Whether or not the option is the disabled for keyboard navigation and ARIA purposes. |
@@ -1,4 +1,5 @@
import React, {
Fragment,
createContext,
createRef,
useCallback,
@@ -7,7 +8,6 @@ import React, {
useMemo,
useReducer,
useRef,
Fragment,
// Types
Dispatch,
@@ -0,0 +1,406 @@
## Menu Button (Dropdown)
[View live demo on CodeSandbox](https://codesandbox.io/s/headlessuireact-menu-example-b6xje?file=/src/App.js)
The `Menu` component and related child components are used to quickly build custom dropdown components that are fully accessible out of the box, including correct ARIA attribute management and robust keyboard navigation support.
- [Installation](#installation)
- [Basic example](#basic-example)
- [Styling the active item](#styling-the-active-item)
- [Showing/hiding the menu](#showinghiding-the-menu)
- [Disabling an item](#disabling-an-item)
- [Transitions](#transitions)
- [Rendering additional content](#rendering-additional-content)
- [Rendering a different element for a component](#rendering-a-different-element-for-a-component)
- [Component API](#component-api)
### Installation
```sh
# npm
npm install @headlessui/react
# Yarn
yarn add @headlessui/react
```
### Basic example
Menu Buttons are built using the `Menu`, `Menu.Button`, `Menu.Items`, and `Menu.Item` components.
The `Menu.Button` will automatically open/close the `Menu.Items` when clicked, and when the menu is open, the list of items receives focus and is automatically navigable via the keyboard.
```jsx
import { Menu } from '@headlessui/react'
function MyDropdown() {
return (
<Menu>
<Menu.Button>More</Menu.Button>
<Menu.Items>
<Menu.Item>
{({ active }) => (
<a className={`${active && 'bg-blue-500'}`} href="/account-settings">
Account settings
</a>
)}
</Menu.Item>
<Menu.Item>
{({ active }) => (
<a className={`${active && 'bg-blue-500'}`} href="/account-settings">
Documentation
</a>
)}
</Menu.Item>
<Menu.Item disabled>
<span className="opacity-75">Invite a friend (coming soon!)</span>
</Menu.Item>
</Menu.Items>
</Menu>
)
}
```
### Styling the active item
This is a headless component so there are no styles included by default. Instead, the components expose useful information via [render props](https://reactjs.org/docs/render-props.html) that you can use to apply the styles you'd like to apply yourself.
To style the active `Menu.Item` you can read the `active` render prop argument, which tells you whether or not that menu item is the item that is currently focused via the mouse or keyboard.
You can use this state to conditionally apply whatever active/focus styles you like, for instance a blue background like is typical in most operating systems.
```jsx
import { Menu } from '@headlessui/react'
function MyDropdown() {
return (
<Menu>
<Menu.Button>More</Menu.Button>
<Menu.Items>
{/* Use the `active` state to conditionally style the active item. */}
<Menu.Item>
{({ active }) => (
<a
className={`${active ? 'bg-blue-500 text-white' : 'bg-white text-black'}`}
href="/account-settings"
>
Account settings
</a>
)}
</Menu.Item>
{/* ... */}
</Menu.Items>
</Menu>
)
}
```
### Showing/hiding the menu
By default, your `Menu.Items` instance will be shown/hidden automatically based on the internal `open` state tracked within the `Menu` component itself.
```jsx
import { Menu } from '@headlessui/react'
function MyDropdown() {
return (
<Menu>
<Menu.Button>More</Menu.Button>
{/* By default, this will automatically show/hide when the Menu.Button is pressed. */}
<Menu.Items>
<Menu.Item>{/* ... */}</Menu.Item>
{/* ... */}
</Menu.Items>
</Menu>
)
}
```
If you'd rather handle this yourself (perhaps because you need to add an extra wrapper element for one reason or another), you can add a `static` prop to the `Menu.Items` instance to tell it to always render, and inspect the `open` slot prop provided by the `Menu` to control which element is shown/hidden yourself.
```jsx
import { Menu } from '@headlessui/react'
function MyDropdown() {
return (
<Menu>
{({ open }) => (
<Menu.Button>More</Menu.Button>
{open && (
<div>
{/* Using `static`, `Menu.Items` is always rendered and ignores the `open` state. */}
<Menu.Items static>
<Menu.Item>{/* ... */}</Menu.Item>
{/* ... */}
</Menu.Items>
</div>
)}
)}
</Menu>
)
}
```
### Disabling an item
Use the `disabled` prop to disable a `Menu.Item`. This will make it unselectable via keyboard navigation, and it will be skipped when pressing the up/down arrows.
```jsx
import { Menu } from '@headlessui/react'
function MyDropdown() {
return (
<Menu>
<Menu.Button>More</Menu.Button>
<Menu.Items>
{/* ... */}
{/* This item will be skipped by keyboard navigation. */}
<Menu.Item disabled>
<span className="opacity-75">Invite a friend (coming soon!)</span>
</Menu.Item>
{/* ... */}
</Menu.Items>
</Menu>
)
}
```
### Transitions
To animate the opening/closing of the menu panel, use the provided `Transition` component. All you need to do is mark your `Menu.Items` as `static`, wrap it in a `<Transition>`, and the transition will be applied automatically.
```jsx
import { Menu, Transition } from '@headlessui/react'
function MyDropdown() {
return (
<Menu>
{({ open }) => (
<>
<Menu.Button>More</Menu.Button>
{/* Use the Transition + open render prop argument to add transitions. */}
<Transition
show={open}
enter="transition duration-100 ease-out"
enterFrom="transform scale-95 opacity-0"
enterTo="transform scale-100 opacity-100"
leave="transition duration-75 ease-out"
leaveFrom="transform scale-100 opacity-100"
leaveTo="transform scale-95 opacity-0"
>
<Menu.Items static>
<Menu.Item>{/* ... */}</Menu.Item>
{/* ... */}
</Menu.Items>
</Transition>
</>
)}
</Menu>
)
}
```
### Rendering additional content
The `Menu` component is not limited to rendering only its related subcomponents. You can render anything you like within a menu, which gives you complete control over exactly what you are building.
For example, if you'd like to add a little header section to the menu with some extra information in it, just render an extra `div` with your content in it.
```jsx
import { Menu } from '@headlessui/react'
function MyDropdown() {
return (
<Menu>
<Menu.Button>More</Menu.Button>
<Menu.Items>
<div className="px-4 py-3">
<p className="text-sm leading-5">Signed in as</p>
<p className="text-sm font-medium leading-5 text-gray-900 truncate">tom@example.com</p>
</div>
<Menu.Item>
{({ active }) => (
<a className={`${active && 'bg-blue-500'}`} href="/account-settings">
Account settings
</a>
)}
</Menu.Item>
{/* ... */}
</Menu.Items>
</Menu>
)
}
```
Note that only `Menu.Item` instances will be navigable via the keyboard.
### Rendering a different element for a component
By default, the `Menu` and its subcomponents each render a default element that is sensible for that component.
For example, `Menu.Button` renders a `button` by default, and `Menu.Items` renders a `div`. `Menu` and `Menu.Item` interestingly _do not render an extra element_, and instead render their children directly by default.
This is easy to change using the `as` prop, which exists on every component.
```jsx
import { Menu } from '@headlessui/react'
function MyDropdown() {
return (
{/* Render a `div` instead of no wrapper element */}
<Menu as="div">
<Menu.Button>More</Menu.Button>
{/* Render a `ul` instead of a `div` */}
<Menu.Items as="ul">
{/* Render an `li` instead of no wrapper element */}
<Menu.Item as="li">
{({ active }) => (
<a className={`${active && 'bg-blue-500'}`} href="/account-settings">
Account settings
</a>
)}
</Menu.Item>
{/* ... */}
</Menu.Items>
</Menu>
)
}
```
To tell an element to render its children directly with no wrapper element, use `as={React.Fragment}`.
```jsx
import { Menu } from '@headlessui/react'
function MyDropdown() {
return (
<Menu>
{/* Render no wrapper, instead pass in a button manually. */}
<Menu.Button as={React.Fragment}>
<button>More</button>
</Menu.Button>
<Menu.Items>
<Menu.Item>
{({ active }) => (
<a className={`${active && 'bg-blue-500'}`} href="/account-settings">
Account settings
</a>
)}
</Menu.Item>
{/* ... */}
</Menu.Items>
</Menu>
)
}
```
### Component API
#### Menu
```jsx
<Menu>
<Menu.Button>More</Menu.Button>
<Menu.Items>
<Menu.Item>{/* ... */}</Menu.Item>
{/* ... */}
</Menu.Items>
</Menu>
```
##### Props
| Prop | Type | Default | Description |
| :--- | :------------------ | :-------------------------------------- | :---------------------------------------------------- |
| `as` | String \| Component | `React.Fragment` _(no wrapper element_) | The element or component the `Menu` should render as. |
##### Render prop object
| Prop | Type | Description |
| :----- | :------ | :------------------------------- |
| `open` | Boolean | Whether or not the menu is open. |
#### Menu.Button
```jsx
<Menu.Button>
{({ open }) => (
<>
<span>More options</span>
<ChevronRightIcon className={`${open ? 'transform rotate-90' : ''}`} />
</>
)}
</Menu.Button>
```
##### Props
| Prop | Type | Default | Description |
| :--- | :------------------ | :------- | :----------------------------------------------------------- |
| `as` | String \| Component | `button` | The element or component the `Menu.Button` should render as. |
##### Render prop object
| Prop | Type | Description |
| :----- | :------ | :------------------------------- |
| `open` | Boolean | Whether or not the menu is open. |
#### Menu.Items
```jsx
<Menu.Items>
<Menu.Item>{/* ... */}></Menu.Item>
{/* ... */}>
</Menu.Items>
```
##### Props
| Prop | Type | Default | Description |
| :-------- | :------------------ | :------ | :-------------------------------------------------------------------------------- |
| `as` | String \| Component | `div` | The element or component the `Menu.Items` should render as. |
| `static` | Boolean | `false` | Whether the element should ignore the internally managed open/closed state. |
| `unmount` | Boolean | `true` | Whether the element should be unmounted or hidden based on the open/closed state. |
> **note**: `static` and `unmount` can not be used at the same time. You will get a TypeScript error if you try to do it.
##### Render prop object
| Prop | Type | Description |
| :----- | :------ | :------------------------------- |
| `open` | Boolean | Whether or not the menu is open. |
#### Menu.Item
```jsx
<Menu.Item>
{({ active }) => (
<a
className={`${active ? 'bg-blue-500 text-white' : 'bg-white text-black'}`}
href="/account-settings"
>
Account settings
</a>
)}
</Menu.Item>
```
##### Props
| Prop | Type | Default | Description |
| :--------- | :------------------ | :-------------------------------------- | :------------------------------------------------------------------------------------ |
| `as` | String \| Component | `React.Fragment` _(no wrapper element)_ | The element or component the `Menu.Item` should render as. |
| `disabled` | Boolean | `false` | Whether or not the item should be disabled for keyboard navigation and ARIA purposes. |
##### Render prop object
| Prop | Type | Description |
| :--------- | :------ | :--------------------------------------------------------------------------------- |
| `active` | Boolean | Whether or not the item is the active/focused item in the list. |
| `disabled` | Boolean | Whether or not the item is the disabled for keyboard navigation and ARIA purposes. |
@@ -1,5 +1,6 @@
// WAI-ARIA: https://www.w3.org/TR/wai-aria-practices-1.2/#menubutton
import React, {
Fragment,
createContext,
createRef,
useCallback,
@@ -8,7 +9,6 @@ import React, {
useMemo,
useReducer,
useRef,
Fragment,
// Types
Dispatch,
@@ -0,0 +1,164 @@
## Popover
- [Installation](#installation)
- [Basic example](#basic-example)
- [Component API](#component-api)
This component can be used for navigation menu's, mobile menu's and flyout menu's.
### Installation
```sh
# npm
npm install @headlessui/react
# Yarn
yarn add @headlessui/react
```
### Basic example
```jsx
<Popover.Group>
<Popover>
<Popover.Button>Solutions</Popover.Button>
<Popover.Panel>
<a href="#">Analytics</a>
<a href="#">Engagement</a>
<a href="#">Security</a>
<a href="#">Integrations</a>
<a href="#">Automations</a>
</Popover.Panel>
</Popover>
<a href="#">Pricing</a>
<a href="#">Docs</a>
<Popover>
<Popover.Button>More</Popover.Button>
<Popover.Panel focus>
<a href="#">Help Center</a>
<a href="#">Guides</a>
<a href="#">Events</a>
<a href="#">Security</a>
</Popover.Panel>
</Popover>
</Popover.Group>
```
### Component API
#### Popover
```jsx
<Popover.Group>
<Popover>
<Popover.Button>Solutions</Popover.Button>
<Popover.Panel>
<a href="#">Analytics</a>
<a href="#">Engagement</a>
<a href="#">Security</a>
<a href="#">Integrations</a>
<a href="#">Automations</a>
</Popover.Panel>
</Popover>
<a href="#">Pricing</a>
<a href="#">Docs</a>
<Popover>
<Popover.Button>More</Popover.Button>
<Popover.Panel focus>
<a href="#">Help Center</a>
<a href="#">Guides</a>
<a href="#">Events</a>
<a href="#">Security</a>
</Popover.Panel>
</Popover>
</Popover.Group>
```
##### Props
| Prop | Type | Default | Description |
| :--- | :------------------ | :------ | :------------------------------------------------------- |
| `as` | String \| Component | `div` | The element or component the `Popover` should render as. |
##### Render prop object
| Prop | Type | Description |
| :----- | :------ | :--------------------------------- |
| `open` | Boolean | Whether or not the dialog is open. |
#### Popover.Overlay
This can be used to create an overlay for your Popover component. Clicking on the overlay will close the Popover.
##### Props
| Prop | Type | Default | Description |
| :--- | :------------------ | :------ | :--------------------------------------------------------------- |
| `as` | String \| Component | `div` | The element or component the `Popover.Overlay` should render as. |
##### Render prop object
| Prop | Type | Description |
| :----- | :------ | :------------------------------------- |
| `open` | Boolean | Whether or not the disclosure is open. |
#### Popover.Button
This is the trigger component to open a Popover. You can also use this
`Popover.Button` component inside a `Popover.Panel`, if you do so, then it will
behave as a `close` button. We will also make sure to provide the correct
`aria-*` attributes onto the button.
##### Props
| Prop | Type | Default | Description |
| :--- | :------------------ | :------- | :-------------------------------------------------------------- |
| `as` | String \| Component | `button` | The element or component the `Popover.Button` should render as. |
##### Render prop object
| Prop | Type | Description |
| :----- | :------ | :------------------------------------- |
| `open` | Boolean | Whether or not the disclosure is open. |
#### Popover.Panel
This component contains the contents of your Popover.
##### Props
| Prop | Type | Default | Description |
| :-------- | :------------------ | :------ | :------------------------------------------------------------------------------------------------------------------------------------------ |
| `as` | String \| Component | `div` | The element or component the `Popover.Panel` should render as. |
| `focus` | Boolean | `false` | This will force focus inside the `Popover.Panel` when the `Popover` is open. It will also close the `Popover` if focus left this component. |
| `static` | Boolean | `false` | Whether the element should ignore the internally managed open/closed state. |
| `unmount` | Boolean | `true` | Whether the element should be unmounted or hidden based on the open/closed state. |
> **note**: `static` and `unmount` can not be used at the same time. You will get a TypeScript error if you try to do it.
##### Render prop object
| Prop | Type | Description |
| :----- | :------ | :------------------------------------- |
| `open` | Boolean | Whether or not the disclosure is open. |
#### Popover.Group
This allows you to wrap multiple elements and Popover's inside a group.
- When you tab out of a `Popover.Panel`, it will focus the next `Popover.Button` in line.
- If focus left the `Popover.Group` it will close all the `Popover`'s.
##### Props
| Prop | Type | Default | Description |
| :--- | :------------------ | :------ | :------------------------------------------------------------- |
| `as` | String \| Component | `div` | The element or component the `Popover.Group` should render as. |
##### Render prop object
- None
@@ -1,20 +1,20 @@
import React, {
createContext,
useCallback,
useContext,
useReducer,
useEffect,
useMemo,
useCallback,
// Types
Dispatch,
ElementType,
Ref,
KeyboardEvent as ReactKeyboardEvent,
MouseEvent as ReactMouseEvent,
useReducer,
useRef,
useState,
// Types
ContextType,
Dispatch,
ElementType,
KeyboardEvent as ReactKeyboardEvent,
MouseEvent as ReactMouseEvent,
Ref,
} from 'react'
import { Props } from '../../types'
@@ -143,13 +143,13 @@ function stateReducer(state: StateDefinition, action: Actions) {
// ---
let DEFAULT_FLYOUT_TAG = 'div' as const
let DEFAULT_POPOVER_TAG = 'div' as const
interface PopoverRenderPropArg {
open: boolean
}
export function Popover<TTag extends ElementType = typeof DEFAULT_FLYOUT_TAG>(
props: Props<TTag, { open: boolean }>
export function Popover<TTag extends ElementType = typeof DEFAULT_POPOVER_TAG>(
props: Props<TTag, PopoverRenderPropArg>
) {
let buttonId = `headlessui-popover-button-${useId()}`
let panelId = `headlessui-popover-panel-${useId()}`
@@ -228,7 +228,7 @@ export function Popover<TTag extends ElementType = typeof DEFAULT_FLYOUT_TAG>(
return (
<PopoverContext.Provider value={reducerBag}>
{render(props, propsBag, DEFAULT_FLYOUT_TAG)}
{render(props, propsBag, DEFAULT_POPOVER_TAG)}
</PopoverContext.Provider>
)
}
@@ -0,0 +1,45 @@
## Portal
- [Installation](#installation)
- [Basic example](#basic-example)
- [Component API](#component-api)
A component for rendering your contents within a Portal (at the end of `document.body`).
### Installation
```sh
# npm
npm install @headlessui/react
# Yarn
yarn add @headlessui/react
```
### Basic example
```jsx
<Portal>
<p>This will be rendered inside a Portal, at the end of `document.body`</p>
</Portal>
```
### Component API
#### Portal
```jsx
<Portal>
<p>This will be rendered inside a Portal, at the end of `document.body`</p>
</Portal>
```
##### Props
| Prop | Type | Default | Description |
| :--- | :------------------ | :-------------------------------------- | :------------------------------------------------------ |
| `as` | String \| Component | `React.Fragment` _(no wrapper element_) | The element or component the `Portal` should render as. |
##### Render prop object
- None
@@ -1,4 +1,4 @@
import React, { useState } from 'react'
import React, { useState, useRef } from 'react'
import { render } from '@testing-library/react'
import { Portal } from './portal'
@@ -273,3 +273,32 @@ it('should be possible to tamper with the modal root and restore correctly', asy
expect(getPortalRoot()).not.toBe(null)
expect(getPortalRoot().childNodes).toHaveLength(2)
})
it('should be possable to force the Portal into a specific element using Portal.Group', async () => {
function Example() {
let container = useRef(null)
return (
<main>
<aside ref={container} id="group-1">
A
</aside>
<Portal.Group target={container}>
<section id="group-2">
<span>B</span>
</section>
<Portal>Next to A</Portal>
</Portal.Group>
<Portal>I am in the portal root</Portal>
</main>
)
}
render(<Example />)
expect(document.body.innerHTML).toMatchInlineSnapshot(
`"<div><main><aside id=\\"group-1\\">A<div>Next to A</div></aside><section id=\\"group-2\\"><span>B</span></section></main></div><div id=\\"headlessui-portal-root\\"><div>I am in the portal root</div></div>"`
)
})
@@ -1,26 +1,47 @@
// WAI-ARIA: https://www.w3.org/TR/wai-aria-practices-1.2/#dialog_modal
import React, {
Fragment,
createContext,
useContext,
useEffect,
useState,
// Types
ElementType,
MutableRefObject,
} from 'react'
import { createPortal } from 'react-dom'
import { Props } from '../../types'
import { render } from '../../utils/render'
import { useIsoMorphicEffect } from '../../hooks/use-iso-morphic-effect'
import { StackProvider, useElemenStack } from '../../internal/stack-context'
import { useElemenStack, StackProvider } from '../../internal/stack-context'
import { usePortalRoot } from '../../internal/portal-force-root'
function resolvePortalRoot() {
if (typeof window === 'undefined') return null
let existingRoot = document.getElementById('headlessui-portal-root')
if (existingRoot) return existingRoot
function usePortalTarget(): HTMLElement | null {
let forceInRoot = usePortalRoot()
let groupTarget = useContext(PortalGroupContext)
let [target, setTarget] = useState(() => {
// Group context is used, but still null
if (!forceInRoot && groupTarget !== null) return null
let root = document.createElement('div')
root.setAttribute('id', 'headlessui-portal-root')
return document.body.appendChild(root)
// No group context is used, let's create a default portal root
if (typeof window === 'undefined') return null
let existingRoot = document.getElementById('headlessui-portal-root')
if (existingRoot) return existingRoot
let root = document.createElement('div')
root.setAttribute('id', 'headlessui-portal-root')
return document.body.appendChild(root)
})
useEffect(() => {
if (forceInRoot) return
if (groupTarget === null) return
setTarget(groupTarget.current)
}, [groupTarget, setTarget, forceInRoot])
return target
}
// ---
@@ -31,7 +52,8 @@ interface PortalRenderPropArg {}
export function Portal<TTag extends ElementType = typeof DEFAULT_PORTAL_TAG>(
props: Props<TTag, PortalRenderPropArg>
) {
let [target, setTarget] = useState(resolvePortalRoot)
let passthroughProps = props
let target = usePortalTarget()
let [element] = useState<HTMLDivElement | null>(() =>
typeof window === 'undefined' ? null : document.createElement('div')
)
@@ -39,7 +61,7 @@ export function Portal<TTag extends ElementType = typeof DEFAULT_PORTAL_TAG>(
useElemenStack(element)
useIsoMorphicEffect(() => {
if (!target) return setTarget(resolvePortalRoot())
if (!target) return
if (!element) return
target.appendChild(element)
@@ -49,13 +71,43 @@ export function Portal<TTag extends ElementType = typeof DEFAULT_PORTAL_TAG>(
if (!element) return
target.removeChild(element)
if (target.childNodes.length <= 0) target.parentElement?.removeChild(target)
if (target.childNodes.length <= 0) {
target.parentElement?.removeChild(target)
}
}
}, [target, element])
return (
<StackProvider>
{!target || !element ? null : createPortal(render(props, {}, DEFAULT_PORTAL_TAG), element)}
{!target || !element
? null
: createPortal(render(passthroughProps, {}, DEFAULT_PORTAL_TAG), element)}
</StackProvider>
)
}
// ---
let DEFAULT_GROUP_TAG = Fragment
interface GroupRenderPropArg {}
let PortalGroupContext = createContext<MutableRefObject<HTMLElement | null> | null>(null)
function Group<TTag extends ElementType = typeof DEFAULT_GROUP_TAG>(
props: Props<TTag, GroupRenderPropArg> & {
target: MutableRefObject<HTMLElement | null>
}
) {
let { target, ...passthroughProps } = props
return (
<PortalGroupContext.Provider value={target}>
{render(passthroughProps, {}, DEFAULT_GROUP_TAG)}
</PortalGroupContext.Provider>
)
}
// ---
Portal.Group = Group
@@ -0,0 +1,89 @@
## RadioGroup
A component for grouping radio options.
- [Installation](#installation)
- [Basic example](#basic-example)
- [Component API](#component-api)
### Installation
```sh
# npm
npm install @headlessui/react
# Yarn
yarn add @headlessui/react
```
### Basic example
```jsx
import React, { useState } from 'react'
import { RadioGroup } from '@headlessui/react'
function Example() {
let [deliveryMethod, setDeliveryMethod] = useState(undefined)
return (
<RadioGroup value={deliveryMethod} onChange={setDeliveryMethod}>
<RadioGroup.Label>Pizza Delivery</RadioGroup.Label>
<RadioGroup.Option value="pickup">Pickup</RadioGroup.Option>
<RadioGroup.Option value="home-delivery">Home delivery</RadioGroup.Option>
<RadioGroup.Option value="dine-in">Dine in</RadioGroup.Option>
</RadioGroup>
)
}
```
### Component API
#### RadioGroup
```jsx
let [deliveryMethod, setDeliveryMethod] = useState(undefined)
<RadioGroup value={deliveryMethod} onChange={setDeliveryMethod}>
<RadioGroup.Option value="pickup">Pickup</RadioGroup.Option>
<RadioGroup.Option value="home-delivery">Home delivery</RadioGroup.Option>
<RadioGroup.Option value="dine-in">Dine in</RadioGroup.Option>
</RadioGroup>
```
##### Props
| Prop | Type | Default | Description |
| :--------- | :------------------ | :---------- | :---------------------------------------------------------- |
| `as` | String \| Component | `div` | The element or component the `RadioGroup` should render as. |
| `value` | `T` \| undefined | `undefined` | The current selected value in the `RadioGroup`. |
| `onChange` | Function | `undefined` | The function called to update the `RadioGroup` value. |
##### Render prop object
- None
#### RadioGroup.Option
```jsx
let [deliveryMethod, setDeliveryMethod] = useState(undefined)
<RadioGroup value={deliveryMethod} onChange={setDeliveryMethod}>
<RadioGroup.Option value="pickup">Pickup</RadioGroup.Option>
<RadioGroup.Option value="home-delivery">Home delivery</RadioGroup.Option>
<RadioGroup.Option value="dine-in">Dine in</RadioGroup.Option>
</RadioGroup>
```
##### Props
| Prop | Type | Default | Description |
| :------ | :------------------ | :---------- | :------------------------------------------------------------------------------------------------------------------------- |
| `as` | String \| Component | `div` | The element or component the `RadioGroup` should render as. |
| `value` | `T` \| undefined | `undefined` | The value of the current `RadioGroup.Option`. The type should match the type of the `value` in the `RadioGroup` component. |
##### Render prop object
| Prop | Type | Description |
| :-------- | :------ | :----------------------------------------------------------------- |
| `active` | Boolean | Whether or not the option is active (using the mouse or keyboard). |
| `checked` | Boolean | Whether or not the current option is the checked value. |
@@ -0,0 +1,664 @@
import React, { createElement, useState } from 'react'
import { render } from '@testing-library/react'
import { RadioGroup } from './radio-group'
import { suppressConsoleLogs } from '../../test-utils/suppress-console-logs'
import { press, Keys, shift, click } from '../../test-utils/interactions'
import {
getByText,
assertRadioGroupLabel,
getRadioGroupOptions,
assertFocusable,
assertNotFocusable,
assertActiveElement,
} from '../../test-utils/accessibility-assertions'
jest.mock('../../hooks/use-id')
beforeAll(() => {
jest.spyOn(window, 'requestAnimationFrame').mockImplementation(setImmediate as any)
jest.spyOn(window, 'cancelAnimationFrame').mockImplementation(clearImmediate as any)
})
afterAll(() => jest.restoreAllMocks())
describe('Safe guards', () => {
it.each([['RadioGroup.Option', RadioGroup.Option]])(
'should error when we are using a <%s /> without a parent <RadioGroup />',
suppressConsoleLogs((name, Component) => {
expect(() => render(createElement(Component))).toThrowError(
`<${name} /> is missing a parent <RadioGroup /> component.`
)
})
)
it(
'should be possible to render a RadioGroup without crashing',
suppressConsoleLogs(async () => {
render(
<RadioGroup value={undefined} onChange={console.log}>
<RadioGroup.Label>Pizza Delivery</RadioGroup.Label>
<RadioGroup.Option value="pickup">Pickup</RadioGroup.Option>
<RadioGroup.Option value="home-delivery">Home delivery</RadioGroup.Option>
<RadioGroup.Option value="dine-in">Dine in</RadioGroup.Option>
</RadioGroup>
)
assertRadioGroupLabel({ textContent: 'Pizza Delivery' })
})
)
it('should be possible to render a RadioGroup without options and without crashing', () => {
render(<RadioGroup value={undefined} onChange={console.log} />)
})
})
describe('Rendering', () => {
it('should be possible to render a RadioGroup, where the first element is tabbable', async () => {
render(
<RadioGroup value={undefined} onChange={console.log}>
<RadioGroup.Label>Pizza Delivery</RadioGroup.Label>
<RadioGroup.Option value="pickup">Pickup</RadioGroup.Option>
<RadioGroup.Option value="home-delivery">Home delivery</RadioGroup.Option>
<RadioGroup.Option value="dine-in">Dine in</RadioGroup.Option>
</RadioGroup>
)
expect(getRadioGroupOptions()).toHaveLength(3)
assertFocusable(getByText('Pickup'))
assertNotFocusable(getByText('Home delivery'))
assertNotFocusable(getByText('Dine in'))
})
it('should be possible to render a RadioGroup with an active value', async () => {
render(
<RadioGroup value="home-delivery" onChange={console.log}>
<RadioGroup.Label>Pizza Delivery</RadioGroup.Label>
<RadioGroup.Option value="pickup">Pickup</RadioGroup.Option>
<RadioGroup.Option value="home-delivery">Home delivery</RadioGroup.Option>
<RadioGroup.Option value="dine-in">Dine in</RadioGroup.Option>
</RadioGroup>
)
expect(getRadioGroupOptions()).toHaveLength(3)
assertNotFocusable(getByText('Pickup'))
assertFocusable(getByText('Home delivery'))
assertNotFocusable(getByText('Dine in'))
})
it('should guarantee the radio option order after a few unmounts', async () => {
function Example() {
let [showFirst, setShowFirst] = useState(false)
let [active, setActive] = useState()
return (
<>
<button onClick={() => setShowFirst(v => !v)}>Toggle</button>
<RadioGroup value={active} onChange={setActive}>
<RadioGroup.Label>Pizza Delivery</RadioGroup.Label>
{showFirst && <RadioGroup.Option value="pickup">Pickup</RadioGroup.Option>}
<RadioGroup.Option value="home-delivery">Home delivery</RadioGroup.Option>
<RadioGroup.Option value="dine-in">Dine in</RadioGroup.Option>
</RadioGroup>
</>
)
}
render(<Example />)
await click(getByText('Toggle')) // Render the pickup again
await press(Keys.Tab) // Focus first element
assertActiveElement(getByText('Pickup'))
await press(Keys.ArrowUp) // Loop around
assertActiveElement(getByText('Dine in'))
await press(Keys.ArrowUp) // Up again
assertActiveElement(getByText('Home delivery'))
})
})
describe('Keyboard interactions', () => {
describe('`Tab` key', () => {
it('should be possible to tab to the first item', async () => {
render(
<RadioGroup value={undefined} onChange={console.log}>
<RadioGroup.Label>Pizza Delivery</RadioGroup.Label>
<RadioGroup.Option value="pickup">Pickup</RadioGroup.Option>
<RadioGroup.Option value="home-delivery">Home delivery</RadioGroup.Option>
<RadioGroup.Option value="dine-in">Dine in</RadioGroup.Option>
</RadioGroup>
)
await press(Keys.Tab)
assertActiveElement(getByText('Pickup'))
})
it('should not change the selected element on focus', async () => {
let changeFn = jest.fn()
render(
<RadioGroup value={undefined} onChange={changeFn}>
<RadioGroup.Label>Pizza Delivery</RadioGroup.Label>
<RadioGroup.Option value="pickup">Pickup</RadioGroup.Option>
<RadioGroup.Option value="home-delivery">Home delivery</RadioGroup.Option>
<RadioGroup.Option value="dine-in">Dine in</RadioGroup.Option>
</RadioGroup>
)
await press(Keys.Tab)
assertActiveElement(getByText('Pickup'))
expect(changeFn).toHaveBeenCalledTimes(0)
})
it('should be possible to tab to the active item', async () => {
render(
<RadioGroup value="home-delivery" onChange={console.log}>
<RadioGroup.Label>Pizza Delivery</RadioGroup.Label>
<RadioGroup.Option value="pickup">Pickup</RadioGroup.Option>
<RadioGroup.Option value="home-delivery">Home delivery</RadioGroup.Option>
<RadioGroup.Option value="dine-in">Dine in</RadioGroup.Option>
</RadioGroup>
)
await press(Keys.Tab)
assertActiveElement(getByText('Home delivery'))
})
it('should not change the selected element on focus (when selecting the active item)', async () => {
let changeFn = jest.fn()
render(
<RadioGroup value="home-delivery" onChange={changeFn}>
<RadioGroup.Label>Pizza Delivery</RadioGroup.Label>
<RadioGroup.Option value="pickup">Pickup</RadioGroup.Option>
<RadioGroup.Option value="home-delivery">Home delivery</RadioGroup.Option>
<RadioGroup.Option value="dine-in">Dine in</RadioGroup.Option>
</RadioGroup>
)
await press(Keys.Tab)
assertActiveElement(getByText('Home delivery'))
expect(changeFn).toHaveBeenCalledTimes(0)
})
it('should be possible to tab out of the radio group (no selected value)', async () => {
render(
<>
<button>Before</button>
<RadioGroup value={undefined} onChange={console.log}>
<RadioGroup.Label>Pizza Delivery</RadioGroup.Label>
<RadioGroup.Option value="pickup">Pickup</RadioGroup.Option>
<RadioGroup.Option value="home-delivery">Home delivery</RadioGroup.Option>
<RadioGroup.Option value="dine-in">Dine in</RadioGroup.Option>
</RadioGroup>
<button>After</button>
</>
)
await press(Keys.Tab)
assertActiveElement(getByText('Before'))
await press(Keys.Tab)
assertActiveElement(getByText('Pickup'))
await press(Keys.Tab)
assertActiveElement(getByText('After'))
})
it('should be possible to tab out of the radio group (selected value)', async () => {
render(
<>
<button>Before</button>
<RadioGroup value="home-delivery" onChange={console.log}>
<RadioGroup.Label>Pizza Delivery</RadioGroup.Label>
<RadioGroup.Option value="pickup">Pickup</RadioGroup.Option>
<RadioGroup.Option value="home-delivery">Home delivery</RadioGroup.Option>
<RadioGroup.Option value="dine-in">Dine in</RadioGroup.Option>
</RadioGroup>
<button>After</button>
</>
)
await press(Keys.Tab)
assertActiveElement(getByText('Before'))
await press(Keys.Tab)
assertActiveElement(getByText('Home delivery'))
await press(Keys.Tab)
assertActiveElement(getByText('After'))
})
})
describe('`Shift+Tab` key', () => {
it('should be possible to tab to the first item', async () => {
render(
<>
<RadioGroup value={undefined} onChange={console.log}>
<RadioGroup.Label>Pizza Delivery</RadioGroup.Label>
<RadioGroup.Option value="pickup">Pickup</RadioGroup.Option>
<RadioGroup.Option value="home-delivery">Home delivery</RadioGroup.Option>
<RadioGroup.Option value="dine-in">Dine in</RadioGroup.Option>
</RadioGroup>
<button>After</button>
</>
)
getByText('After')?.focus()
await press(shift(Keys.Tab))
assertActiveElement(getByText('Pickup'))
})
it('should not change the selected element on focus', async () => {
let changeFn = jest.fn()
render(
<>
<RadioGroup value={undefined} onChange={changeFn}>
<RadioGroup.Label>Pizza Delivery</RadioGroup.Label>
<RadioGroup.Option value="pickup">Pickup</RadioGroup.Option>
<RadioGroup.Option value="home-delivery">Home delivery</RadioGroup.Option>
<RadioGroup.Option value="dine-in">Dine in</RadioGroup.Option>
</RadioGroup>
<button>After</button>
</>
)
getByText('After')?.focus()
await press(shift(Keys.Tab))
assertActiveElement(getByText('Pickup'))
expect(changeFn).toHaveBeenCalledTimes(0)
})
it('should be possible to tab to the active item', async () => {
render(
<>
<RadioGroup value="home-delivery" onChange={console.log}>
<RadioGroup.Label>Pizza Delivery</RadioGroup.Label>
<RadioGroup.Option value="pickup">Pickup</RadioGroup.Option>
<RadioGroup.Option value="home-delivery">Home delivery</RadioGroup.Option>
<RadioGroup.Option value="dine-in">Dine in</RadioGroup.Option>
</RadioGroup>
<button>After</button>
</>
)
getByText('After')?.focus()
await press(shift(Keys.Tab))
assertActiveElement(getByText('Home delivery'))
})
it('should not change the selected element on focus (when selecting the active item)', async () => {
let changeFn = jest.fn()
render(
<>
<RadioGroup value="home-delivery" onChange={changeFn}>
<RadioGroup.Label>Pizza Delivery</RadioGroup.Label>
<RadioGroup.Option value="pickup">Pickup</RadioGroup.Option>
<RadioGroup.Option value="home-delivery">Home delivery</RadioGroup.Option>
<RadioGroup.Option value="dine-in">Dine in</RadioGroup.Option>
</RadioGroup>
<button>After</button>
</>
)
getByText('After')?.focus()
await press(shift(Keys.Tab))
assertActiveElement(getByText('Home delivery'))
expect(changeFn).toHaveBeenCalledTimes(0)
})
it('should be possible to tab out of the radio group (no selected value)', async () => {
render(
<>
<button>Before</button>
<RadioGroup value={undefined} onChange={console.log}>
<RadioGroup.Label>Pizza Delivery</RadioGroup.Label>
<RadioGroup.Option value="pickup">Pickup</RadioGroup.Option>
<RadioGroup.Option value="home-delivery">Home delivery</RadioGroup.Option>
<RadioGroup.Option value="dine-in">Dine in</RadioGroup.Option>
</RadioGroup>
<button>After</button>
</>
)
getByText('After')?.focus()
await press(shift(Keys.Tab))
assertActiveElement(getByText('Pickup'))
await press(shift(Keys.Tab))
assertActiveElement(getByText('Before'))
})
it('should be possible to tab out of the radio group (selected value)', async () => {
render(
<>
<button>Before</button>
<RadioGroup value="home-delivery" onChange={console.log}>
<RadioGroup.Label>Pizza Delivery</RadioGroup.Label>
<RadioGroup.Option value="pickup">Pickup</RadioGroup.Option>
<RadioGroup.Option value="home-delivery">Home delivery</RadioGroup.Option>
<RadioGroup.Option value="dine-in">Dine in</RadioGroup.Option>
</RadioGroup>
<button>After</button>
</>
)
getByText('After')?.focus()
await press(shift(Keys.Tab))
assertActiveElement(getByText('Home delivery'))
await press(shift(Keys.Tab))
assertActiveElement(getByText('Before'))
})
})
describe('`ArrowLeft` key', () => {
it('should go to the previous item when pressing the ArrowLeft key', async () => {
let changeFn = jest.fn()
render(
<>
<button>Before</button>
<RadioGroup value={undefined} onChange={changeFn}>
<RadioGroup.Label>Pizza Delivery</RadioGroup.Label>
<RadioGroup.Option value="pickup">Pickup</RadioGroup.Option>
<RadioGroup.Option value="home-delivery">Home delivery</RadioGroup.Option>
<RadioGroup.Option value="dine-in">Dine in</RadioGroup.Option>
</RadioGroup>
<button>After</button>
</>
)
// Focus the "Before" button
await press(Keys.Tab)
// Focus the RadioGroup
await press(Keys.Tab)
assertActiveElement(getByText('Pickup'))
await press(Keys.ArrowLeft) // Loop around
assertActiveElement(getByText('Dine in'))
await press(Keys.ArrowLeft)
assertActiveElement(getByText('Home delivery'))
expect(changeFn).toHaveBeenCalledTimes(2)
expect(changeFn).toHaveBeenNthCalledWith(1, 'dine-in')
expect(changeFn).toHaveBeenNthCalledWith(2, 'home-delivery')
})
})
describe('`ArrowUp` key', () => {
it('should go to the previous item when pressing the ArrowUp key', async () => {
let changeFn = jest.fn()
render(
<>
<button>Before</button>
<RadioGroup value={undefined} onChange={changeFn}>
<RadioGroup.Label>Pizza Delivery</RadioGroup.Label>
<RadioGroup.Option value="pickup">Pickup</RadioGroup.Option>
<RadioGroup.Option value="home-delivery">Home delivery</RadioGroup.Option>
<RadioGroup.Option value="dine-in">Dine in</RadioGroup.Option>
</RadioGroup>
<button>After</button>
</>
)
// Focus the "Before" button
await press(Keys.Tab)
// Focus the RadioGroup
await press(Keys.Tab)
assertActiveElement(getByText('Pickup'))
await press(Keys.ArrowUp) // Loop around
assertActiveElement(getByText('Dine in'))
await press(Keys.ArrowUp)
assertActiveElement(getByText('Home delivery'))
expect(changeFn).toHaveBeenCalledTimes(2)
expect(changeFn).toHaveBeenNthCalledWith(1, 'dine-in')
expect(changeFn).toHaveBeenNthCalledWith(2, 'home-delivery')
})
})
describe('`ArrowRight` key', () => {
it('should go to the next item when pressing the ArrowRight key', async () => {
let changeFn = jest.fn()
render(
<>
<button>Before</button>
<RadioGroup value={undefined} onChange={changeFn}>
<RadioGroup.Label>Pizza Delivery</RadioGroup.Label>
<RadioGroup.Option value="pickup">Pickup</RadioGroup.Option>
<RadioGroup.Option value="home-delivery">Home delivery</RadioGroup.Option>
<RadioGroup.Option value="dine-in">Dine in</RadioGroup.Option>
</RadioGroup>
<button>After</button>
</>
)
// Focus the "Before" button
await press(Keys.Tab)
// Focus the RadioGroup
await press(Keys.Tab)
assertActiveElement(getByText('Pickup'))
await press(Keys.ArrowRight)
assertActiveElement(getByText('Home delivery'))
await press(Keys.ArrowRight)
assertActiveElement(getByText('Dine in'))
await press(Keys.ArrowRight) // Loop around
assertActiveElement(getByText('Pickup'))
expect(changeFn).toHaveBeenCalledTimes(3)
expect(changeFn).toHaveBeenNthCalledWith(1, 'home-delivery')
expect(changeFn).toHaveBeenNthCalledWith(2, 'dine-in')
expect(changeFn).toHaveBeenNthCalledWith(3, 'pickup')
})
})
describe('`ArrowDown` key', () => {
it('should go to the next item when pressing the ArrowDown key', async () => {
let changeFn = jest.fn()
render(
<>
<button>Before</button>
<RadioGroup value={undefined} onChange={changeFn}>
<RadioGroup.Label>Pizza Delivery</RadioGroup.Label>
<RadioGroup.Option value="pickup">Pickup</RadioGroup.Option>
<RadioGroup.Option value="home-delivery">Home delivery</RadioGroup.Option>
<RadioGroup.Option value="dine-in">Dine in</RadioGroup.Option>
</RadioGroup>
<button>After</button>
</>
)
// Focus the "Before" button
await press(Keys.Tab)
// Focus the RadioGroup
await press(Keys.Tab)
assertActiveElement(getByText('Pickup'))
await press(Keys.ArrowDown)
assertActiveElement(getByText('Home delivery'))
await press(Keys.ArrowDown)
assertActiveElement(getByText('Dine in'))
await press(Keys.ArrowDown) // Loop around
assertActiveElement(getByText('Pickup'))
expect(changeFn).toHaveBeenCalledTimes(3)
expect(changeFn).toHaveBeenNthCalledWith(1, 'home-delivery')
expect(changeFn).toHaveBeenNthCalledWith(2, 'dine-in')
expect(changeFn).toHaveBeenNthCalledWith(3, 'pickup')
})
})
describe('`Space` key', () => {
it('should select the current option when pressing space', async () => {
let changeFn = jest.fn()
render(
<>
<button>Before</button>
<RadioGroup value={undefined} onChange={changeFn}>
<RadioGroup.Label>Pizza Delivery</RadioGroup.Label>
<RadioGroup.Option value="pickup">Pickup</RadioGroup.Option>
<RadioGroup.Option value="home-delivery">Home delivery</RadioGroup.Option>
<RadioGroup.Option value="dine-in">Dine in</RadioGroup.Option>
</RadioGroup>
<button>After</button>
</>
)
// Focus the "Before" button
await press(Keys.Tab)
// Focus the RadioGroup
await press(Keys.Tab)
assertActiveElement(getByText('Pickup'))
await press(Keys.Space)
assertActiveElement(getByText('Pickup'))
expect(changeFn).toHaveBeenCalledTimes(1)
expect(changeFn).toHaveBeenNthCalledWith(1, 'pickup')
})
it('should select the current option only once when pressing space', async () => {
let changeFn = jest.fn()
function Example() {
let [value, setValue] = useState(undefined)
return (
<>
<button>Before</button>
<RadioGroup
value={value}
onChange={v => {
setValue(v)
changeFn(v)
}}
>
<RadioGroup.Label>Pizza Delivery</RadioGroup.Label>
<RadioGroup.Option value="pickup">Pickup</RadioGroup.Option>
<RadioGroup.Option value="home-delivery">Home delivery</RadioGroup.Option>
<RadioGroup.Option value="dine-in">Dine in</RadioGroup.Option>
</RadioGroup>
<button>After</button>
</>
)
}
render(<Example />)
// Focus the "Before" button
await press(Keys.Tab)
// Focus the RadioGroup
await press(Keys.Tab)
assertActiveElement(getByText('Pickup'))
await press(Keys.Space)
await press(Keys.Space)
await press(Keys.Space)
await press(Keys.Space)
await press(Keys.Space)
assertActiveElement(getByText('Pickup'))
expect(changeFn).toHaveBeenCalledTimes(1)
expect(changeFn).toHaveBeenNthCalledWith(1, 'pickup')
})
})
})
describe('Mouse interactions', () => {
it('should be possible to change the current radio group value when clicking on a radio option', async () => {
let changeFn = jest.fn()
render(
<>
<button>Before</button>
<RadioGroup value={undefined} onChange={changeFn}>
<RadioGroup.Label>Pizza Delivery</RadioGroup.Label>
<RadioGroup.Option value="pickup">Pickup</RadioGroup.Option>
<RadioGroup.Option value="home-delivery">Home delivery</RadioGroup.Option>
<RadioGroup.Option value="dine-in">Dine in</RadioGroup.Option>
</RadioGroup>
<button>After</button>
</>
)
await click(getByText('Home delivery'))
assertActiveElement(getByText('Home delivery'))
expect(changeFn).toHaveBeenNthCalledWith(1, 'home-delivery')
})
it('should be a no-op when clicking on the same item', async () => {
let changeFn = jest.fn()
function Example() {
let [value, setValue] = useState(undefined)
return (
<>
<button>Before</button>
<RadioGroup
value={value}
onChange={v => {
setValue(v)
changeFn(v)
}}
>
<RadioGroup.Label>Pizza Delivery</RadioGroup.Label>
<RadioGroup.Option value="pickup">Pickup</RadioGroup.Option>
<RadioGroup.Option value="home-delivery">Home delivery</RadioGroup.Option>
<RadioGroup.Option value="dine-in">Dine in</RadioGroup.Option>
</RadioGroup>
<button>After</button>
</>
)
}
render(<Example />)
await click(getByText('Home delivery'))
await click(getByText('Home delivery'))
await click(getByText('Home delivery'))
await click(getByText('Home delivery'))
assertActiveElement(getByText('Home delivery'))
expect(changeFn).toHaveBeenCalledTimes(1)
})
})
@@ -0,0 +1,333 @@
import React, {
createContext,
useCallback,
useContext,
useEffect,
useMemo,
useReducer,
useRef,
// Types
Dispatch,
ElementType,
MutableRefObject,
} from 'react'
import { Props, Expand } from '../../types'
import { render } from '../../utils/render'
import { useId } from '../../hooks/use-id'
import { match } from '../../utils/match'
import { useIsoMorphicEffect } from '../../hooks/use-iso-morphic-effect'
import { Keys } from '../../components/keyboard'
import { focusIn, Focus, FocusResult } from '../../utils/focus-management'
import { useFlags } from '../../hooks/use-flags'
import { Label, useLabels } from '../../components/label/label'
import { Description, useDescriptions } from '../../components/description/description'
interface Option {
id: string
element: MutableRefObject<HTMLElement | null>
propsRef: MutableRefObject<{ value: unknown }>
}
interface StateDefinition {
propsRef: MutableRefObject<{ value: unknown; onChange(value: unknown): void }>
options: Option[]
}
enum ActionTypes {
RegisterOption,
UnregisterOption,
}
type Actions =
| Expand<{ type: ActionTypes.RegisterOption } & Option>
| { type: ActionTypes.UnregisterOption; id: Option['id'] }
let reducers: {
[P in ActionTypes]: (
state: StateDefinition,
action: Extract<Actions, { type: P }>
) => StateDefinition
} = {
[ActionTypes.RegisterOption](state, action) {
return {
...state,
options: [
...state.options,
{ id: action.id, element: action.element, propsRef: action.propsRef },
],
}
},
[ActionTypes.UnregisterOption](state, action) {
let options = state.options.slice()
let idx = state.options.findIndex(radio => radio.id === action.id)
if (idx === -1) return state
options.splice(idx, 1)
return { ...state, options }
},
}
let RadioGroupContext = createContext<[StateDefinition, Dispatch<Actions>] | null>(null)
RadioGroupContext.displayName = 'RadioGroupContext'
function useRadioGroupContext(component: string) {
let context = useContext(RadioGroupContext)
if (context === null) {
let err = new Error(`<${component} /> is missing a parent <${RadioGroup.name} /> component.`)
if (Error.captureStackTrace) Error.captureStackTrace(err, useRadioGroupContext)
throw err
}
return context
}
function stateReducer(state: StateDefinition, action: Actions) {
return match(action.type, reducers, state, action)
}
// ---
let DEFAULT_RADIO_GROUP_TAG = 'div' as const
interface RadioGroupRenderPropArg {}
type RadioGroupPropsWeControl = 'role' | 'aria-labelledby' | 'aria-describedby' | 'id'
export function RadioGroup<
TTag extends ElementType = typeof DEFAULT_RADIO_GROUP_TAG,
TType = string
>(
props: Props<
TTag,
RadioGroupRenderPropArg,
RadioGroupPropsWeControl | 'value' | 'onChange' | 'disabled'
> & {
value: TType
onChange(value: TType): void
disabled?: boolean
}
) {
let { value, onChange, ...passThroughProps } = props
let reducerBag = useReducer(stateReducer, {
propsRef: { current: { value, onChange } },
options: [],
} as StateDefinition)
let [{ propsRef, options }] = reducerBag
let [labelledby, LabelProvider] = useLabels()
let [describedby, DescriptionProvider] = useDescriptions()
let id = `headlessui-radiogroup-${useId()}`
let radioGroupRef = useRef<HTMLElement | null>(null)
useIsoMorphicEffect(() => {
propsRef.current.value = value
}, [value, propsRef])
useIsoMorphicEffect(() => {
propsRef.current.onChange = onChange
}, [onChange, propsRef])
let triggerChange = useCallback(
nextValue => {
if (nextValue === value) return
return onChange(nextValue)
},
[onChange, value]
)
useIsoMorphicEffect(() => {
let container = radioGroupRef.current
if (!container) return
let walker = document.createTreeWalker(container, NodeFilter.SHOW_ELEMENT, {
acceptNode(node: HTMLElement) {
if (node.getAttribute('role') === 'radio') return NodeFilter.FILTER_REJECT
if (node.hasAttribute('role')) return NodeFilter.FILTER_SKIP
return NodeFilter.FILTER_ACCEPT
},
})
while (walker.nextNode()) {
;(walker.currentNode as HTMLElement).setAttribute('role', 'none')
}
}, [radioGroupRef])
useEffect(() => {
let container = radioGroupRef.current
if (!container) return
function handler(event: KeyboardEvent) {
switch (event.key) {
case Keys.ArrowLeft:
case Keys.ArrowUp:
{
event.preventDefault()
event.stopPropagation()
let result = focusIn(
options.map(radio => radio.element.current) as HTMLElement[],
Focus.Previous | Focus.WrapAround
)
if (result === FocusResult.Success) {
let activeOption = options.find(
option => option.element.current === document.activeElement
)
if (activeOption) triggerChange(activeOption.propsRef.current.value)
}
}
break
case Keys.ArrowRight:
case Keys.ArrowDown:
{
event.preventDefault()
event.stopPropagation()
let result = focusIn(
options.map(option => option.element.current) as HTMLElement[],
Focus.Next | Focus.WrapAround
)
if (result === FocusResult.Success) {
let activeOption = options.find(
option => option.element.current === document.activeElement
)
if (activeOption) triggerChange(activeOption.propsRef.current.value)
}
}
break
case Keys.Space:
{
event.preventDefault()
event.stopPropagation()
let activeOption = options.find(
option => option.element.current === document.activeElement
)
if (activeOption) triggerChange(activeOption.propsRef.current.value)
}
break
}
}
container.addEventListener('keydown', handler)
return () => container!.removeEventListener('keydown', handler)
}, [radioGroupRef, options, triggerChange])
let propsWeControl = {
ref: radioGroupRef,
id,
role: 'radiogroup',
'aria-labelledby': labelledby,
'aria-describedby': describedby,
}
let bag = useMemo<RadioGroupRenderPropArg>(() => ({}), [])
return (
<DescriptionProvider>
<LabelProvider>
<RadioGroupContext.Provider value={reducerBag}>
{render({ ...passThroughProps, ...propsWeControl }, bag, DEFAULT_RADIO_GROUP_TAG)}
</RadioGroupContext.Provider>
</LabelProvider>
</DescriptionProvider>
)
}
// ---
enum OptionState {
Empty = 1 << 0,
Active = 1 << 1,
}
let DEFAULT_OPTION_TAG = 'div' as const
interface OptionRenderPropArg {
checked: boolean
active: boolean
}
type RadioPropsWeControl =
| 'aria-checked'
| 'id'
| 'onBlur'
| 'onClick'
| 'onFocus'
| 'ref'
| 'role'
| 'tabIndex'
function Option<
TTag extends ElementType = typeof DEFAULT_OPTION_TAG,
// TODO: One day we will be able to infer this type from the generic in RadioGroup itself.
// But today is not that day..
TType = Parameters<typeof RadioGroup>[0]['value']
>(
props: Props<TTag, OptionRenderPropArg, RadioPropsWeControl | 'value'> & {
value: TType
}
) {
let optionRef = useRef<HTMLElement | null>(null)
let id = `headlessui-radiogroup-option-${useId()}`
let [labelledby, LabelProvider] = useLabels(id)
let [describedby, DescriptionProvider] = useDescriptions()
let { addFlag, removeFlag, hasFlag } = useFlags(OptionState.Empty)
let { value, ...passThroughProps } = props
let propsRef = useRef({ value })
useIsoMorphicEffect(() => {
propsRef.current.value = value
}, [value, propsRef])
let [{ propsRef: radioGroupPropsRef, options }, dispatch] = useRadioGroupContext(
[RadioGroup.name, Option.name].join('.')
)
useIsoMorphicEffect(() => {
dispatch({ type: ActionTypes.RegisterOption, id, element: optionRef, propsRef })
return () => dispatch({ type: ActionTypes.UnregisterOption, id })
}, [id, dispatch, optionRef, props])
let handleClick = useCallback(() => {
if (radioGroupPropsRef.current.value === value) return
addFlag(OptionState.Active)
radioGroupPropsRef.current.onChange(value)
optionRef.current?.focus()
}, [addFlag, radioGroupPropsRef, value])
let handleFocus = useCallback(() => addFlag(OptionState.Active), [addFlag])
let handleBlur = useCallback(() => removeFlag(OptionState.Active), [removeFlag])
let firstRadio = options?.[0]?.id === id
let checked = radioGroupPropsRef.current.value === value
let propsWeControl = {
ref: optionRef,
id,
role: 'radio',
'aria-checked': checked ? 'true' : 'false',
'aria-labelledby': labelledby,
'aria-describedby': describedby,
tabIndex: checked ? 0 : radioGroupPropsRef.current.value === undefined && firstRadio ? 0 : -1,
onClick: handleClick,
onFocus: handleFocus,
onBlur: handleBlur,
}
let bag = useMemo<OptionRenderPropArg>(() => ({ checked, active: hasFlag(OptionState.Active) }), [
checked,
hasFlag,
])
return (
<DescriptionProvider>
<LabelProvider>
{render({ ...passThroughProps, ...propsWeControl }, bag, DEFAULT_OPTION_TAG)}
</LabelProvider>
</DescriptionProvider>
)
}
// ---
RadioGroup.Option = Option
RadioGroup.Label = Label
RadioGroup.Description = Description
@@ -0,0 +1,160 @@
## Switch (Toggle)
[View live demo on CodeSandbox](https://codesandbox.io/s/headlessuireact-switch-example-y40i1?file=/src/App.js)
The `Switch` component and related child components are used to quickly build custom switch/toggle components that are fully accessible out of the box, including correct ARIA attribute management and robust keyboard support.
- [Installation](#installation)
- [Basic example](#basic-example)
- [Using a custom label](#using-a-custom-label)
- [Component API](#component-api)
### Installation
```sh
# npm
npm install @headlessui/react
# Yarn
yarn add @headlessui/react
```
### Basic example
Switches are built using the `Switch` component. Optionally you can also use the `Switch.Group` and `Switch.Label` components.
```jsx
import { useState } from 'react'
import { Switch } from '@headlessui/react'
function NotificationsToggle() {
const [enabled, setEnabled] = useState(false)
return (
<Switch
checked={enabled}
onChange={setEnabled}
className={`${
enabled ? 'bg-blue-600' : 'bg-gray-200'
} relative inline-flex items-center h-6 rounded-full w-11`}
>
<span className="sr-only">Enable notifications</span>
<span
className={`${
enabled ? 'translate-x-6' : 'translate-x-1'
} inline-block w-4 h-4 transform bg-white rounded-full`}
/>
</Switch>
)
}
```
### Using a custom label
By default the `Switch` will use the contents as the label for screenreaders. If you need more control, you can render a `Switch.Label` outside of the `Switch`, as long as both the switch and label are within a parent `Switch.Group`.
Clicking the label will toggle the switch state, like you'd expect from a native checkbox.
```jsx
import { useState } from 'react'
import { Switch } from '@headlessui/react'
function NotificationsToggle() {
const [enabled, setEnabled] = useState(false)
return (
<Switch.Group>
<Switch.Label>Enable notifications</Switch.Label>
<Switch
checked={enabled}
onChange={setEnabled}
className={`${
enabled ? 'bg-blue-600' : 'bg-gray-200'
} relative inline-flex items-center h-6 rounded-full w-11`}
>
<span
className={`${
enabled ? 'translate-x-6' : 'translate-x-1'
} inline-block w-4 h-4 transform bg-white rounded-full`}
/>
</Switch>
</Switch.Group>
)
}
```
### Component API
#### Switch
```jsx
<Switch checked={checkedState} onChange={setCheckedState}>
<span className="sr-only">Enable notifications</span>
{/* ... */}
</Switch>
```
##### Props
| Prop | Type | Default | Description |
| :--------- | :----------------------- | :------- | :------------------------------------------------------ |
| `as` | String \| Component | `button` | The element or component the `Switch` should render as. |
| `checked` | Boolean | - | Whether or not the switch is checked. |
| `onChange` | `(value: boolean): void` | - | The function to call when the switch is toggled. |
##### Render prop object
| Prop | Type | Description |
| :-------- | :------ | :------------------------------------ |
| `checked` | Boolean | Whether or not the switch is checked. |
#### Switch.Label
```jsx
<Switch.Group>
<Switch.Label>Enable notifications</Switch.Label>
<Switch checked={enabled} onChange={setEnabled} className="...">
{/* ... */}
</Switch>
</Switch.Group>
```
##### Props
| Prop | Type | Default | Description |
| :--- | :------------------ | :------ | :------------------------------------------------------------ |
| `as` | String \| Component | `label` | The element or component the `Switch.Label` should render as. |
#### Switch.Description
```jsx
<Switch.Group>
<Switch.Description>Enable notifications</Switch.Description>
<Switch checked={enabled} onChange={setEnabled} className="...">
{/* ... */}
</Switch>
</Switch.Group>
```
##### Props
| Prop | Type | Default | Description |
| :--- | :------------------ | :------ | :------------------------------------------------------------------ |
| `as` | String \| Component | `label` | The element or component the `Switch.Description` should render as. |
#### Switch.Group
```jsx
<Switch.Group>
<Switch.Label>Enable notifications</Switch.Label>
<Switch checked={enabled} onChange={setEnabled} className="...">
{/* ... */}
</Switch>
</Switch.Group>
```
##### Props
| Prop | Type | Default | Description |
| :--- | :------------------ | :-------------------------------------- | :------------------------------------------------------------ |
| `as` | String \| Component | `React.Fragment` _(no wrapper element)_ | The element or component the `Switch.Group` should render as. |
@@ -1,10 +1,10 @@
import React, {
Fragment,
createContext,
useCallback,
useContext,
useMemo,
useState,
Fragment,
// Types
ElementType,
@@ -0,0 +1,308 @@
## Transition
[View live demo on CodeSandbox](https://codesandbox.io/s/headlessuireact-menu-example-b6xje?file=/src/App.js)
The `Transition` component lets you add enter/leave transitions to conditionally rendered elements, using CSS classes to control the actual transition styles in the different stages of the transition.
- [Installation](#installation)
- [Basic example](#basic-example)
- [Showing and hiding content](#showing-and-hiding-content)
- [Animating transitions](#animating-transitions)
- [Co-ordinating multiple transitions](#co-ordinating-multiple-transitions)
- [Transitioning on initial mount](#transitioning-on-initial-mount)
- [Component API](#component-api)
### Installation
```sh
# npm
npm install @headlessui/react
# Yarn
yarn add @headlessui/react
```
### Basic example
The `Transition` accepts a `show` prop that controls whether the children should be shown or hidden, and a set of lifecycle props (like `enterFrom`, and `leaveTo`) that let you add CSS classes at specific phases of a transition.
```tsx
import { Transition } from '@headlessui/react'
import { useState } from 'react'
function MyComponent() {
const [isOpen, setIsOpen] = useState(false)
return (
<>
<button onClick={() => setIsOpen(!isOpen)}>Toggle</button>
<Transition
show={isOpen}
enter="transition-opacity duration-75"
enterFrom="opacity-0"
enterTo="opacity-100"
leave="transition-opacity duration-150"
leaveFrom="opacity-100"
leaveTo="opacity-0"
>
I will fade in and out
</Transition>
</>
)
}
```
### Showing and hiding content
Wrap the content that should be conditionally rendered in a `<Transition>` component, and use the `show` prop to control whether the content should be visible or hidden.
```tsx
import { Transition } from '@headlessui/react'
import { useState } from 'react'
function MyComponent() {
const [isOpen, setIsOpen] = useState(false)
return (
<>
<button onClick={() => setIsOpen(!isOpen)}>Toggle</button>
<Transition
show={isOpen}
// ...
>
I will fade in and out
</Transition>
</>
)
}
```
The `Transition` component will render a `div` by default, but you can use the `as` prop to render a different element instead if needed. Any other HTML attributes (like `className`) can be added directly to the `Transition` the same way they would be to regular elements.
```tsx
import { Transition } from '@headlessui/react'
import { useState } from 'react'
function MyComponent() {
const [isOpen, setIsOpen] = useState(false)
return (
<>
<button onClick={() => setIsOpen(!isOpen)}>Toggle</button>
<Transition
show={isOpen}
as="a"
href="/my-url"
className="font-bold"
// ...
>
I will fade in and out
</Transition>
</>
)
}
```
### Animating transitions
By default, a `Transition` will enter and leave instantly, which is probably not what you're looking for if you're using this library.
To animate your enter/leave transitions, add classes that provide the styling for each phase of the transitions using these props:
- **enter**: Applied the entire time an element is entering. Usually you define your duration and what properties you want to transition here, for example `transition-opacity duration-75`.
- **enterFrom**: The starting point to enter from, for example `opacity-0` if something should fade in.
- **enterTo**: The ending point to enter to, for example `opacity-100` after fading in.
- **leave**: Applied the entire time an element is leaving. Usually you define your duration and what properties you want to transition here, for example `transition-opacity duration-75`.
- **leaveFrom**: The starting point to leave from, for example `opacity-100` if something should fade out.
- **leaveTo**: The ending point to leave to, for example `opacity-0` after fading out.
Here's an example:
```tsx
import { Transition } from '@headlessui/react'
import { useState } from 'react'
function MyComponent() {
const [isOpen, setIsOpen] = useState(false)
return (
<>
<button onClick={() => setIsOpen(!isOpen)}>Toggle</button>
<Transition
show={isOpen}
enter="transition-opacity duration-75"
enterFrom="opacity-0"
enterTo="opacity-100"
leave="transition-opacity duration-150"
leaveFrom="opacity-100"
leaveTo="opacity-0"
>
I will fade in and out
</Transition>
</>
)
}
```
In this example, the transitioning element will take 75ms to enter (that's the `duration-75` class), and will transition the opacity property during that time (that's `transition-opacity`).
It will start completely transparent before entering (that's `opacity-0` in the `enterFrom` phase), and fade in to completely opaque (`opacity-100`) when finished (that's the `enterTo` phase).
When the element is being removed (the `leave` phase), it will transition the opacity property, and spend 150ms doing it (`transition-opacity duration-150`).
It will start as completely opaque (the `opacity-100` in the `leaveFrom` phase), and finish as completely transparent (the `opacity-0` in the `leaveTo` phase).
All of these props are optional, and will default to just an empty string.
### Co-ordinating multiple transitions
Sometimes you need to transition multiple elements with different animations but all based on the same state. For example, say the user clicks a button to open a sidebar that slides over the screen, and you also need to fade-in a background overlay at the same time.
You can do this by wrapping the related elements with a parent `Transition` component, and wrapping each child that needs its own transition styles with a `Transition.Child` component, which will automatically communicate with the parent `Transition` and inherit the parent's `show` state.
```tsx
import { Transition } from '@headlessui/react'
function Sidebar({ isOpen }) {
return (
<Transition show={isOpen}>
{/* Background overlay */}
<Transition.Child
enter="transition-opacity ease-linear duration-300"
enterFrom="opacity-0"
enterTo="opacity-100"
leave="transition-opacity ease-linear duration-300"
leaveFrom="opacity-100"
leaveTo="opacity-0"
>
{/* ... */}
</Transition.Child>
{/* Sliding sidebar */}
<Transition.Child
enter="transition ease-in-out duration-300 transform"
enterFrom="-translate-x-full"
enterTo="translate-x-0"
leave="transition ease-in-out duration-300 transform"
leaveFrom="translate-x-0"
leaveTo="-translate-x-full"
>
{/* ... */}
</Transition.Child>
</Transition>
)
}
```
The `Transition.Child` component has the exact same API as the `Transition` component, but with no `show` prop, since the `show` value is controlled by the parent.
Parent `Transition` components will always automatically wait for all children to finish transitioning before unmounting, so you don't need to manage any of that timing yourself.
### Transitioning on initial mount
If you want an element to transition the very first time it's rendered, set the `appear` prop to `true`.
This is useful if you want something to transition in on initial page load, or when its parent is conditionally rendered.
```tsx
import { Transition } from '@headlessui/react'
function MyComponent({ isShowing }) {
return (
<Transition
appear={true}
show={isShowing}
enter="transition-opacity duration-75"
enterFrom="opacity-0"
enterTo="opacity-100"
leave="transition-opacity duration-150"
leaveFrom="opacity-100"
leaveTo="opacity-0"
>
{/* Your content goes here*/}
</Transition>
)
}
```
### Component API
#### Transition
```jsx
<Transition
appear={true}
show={isOpen}
enter="transition-opacity duration-75"
enterFrom="opacity-0"
enterTo="opacity-100"
leave="transition-opacity duration-150"
leaveFrom="opacity-100"
leaveTo="opacity-0"
>
{/* Your content goes here*/}
</Transition>
```
##### Props
| Prop | Type | Default | Description |
| :------------ | :------------------ | :------ | :------------------------------------------------------------------------------------ |
| `show` | Boolean | - | Whether the children should be shown or hidden. |
| `as` | String \| Component | `div` | The element or component to render in place of the `Transition` itself. |
| `appear` | Boolean | `false` | Whether the transition should run on initial mount. |
| `unmount` | Boolean | `true` | Whether the element should be `unmounted` or `hidden` based on the show state. |
| `enter` | String | `''` | Classes to add to the transitioning element during the entire enter phase. |
| `enterFrom` | String | `''` | Classes to add to the transitioning element before the enter phase starts. |
| `enterTo` | String | `''` | Classes to add to the transitioning element immediately after the enter phase starts. |
| `leave` | String | `''` | Classes to add to the transitioning element during the entire leave phase. |
| `leaveFrom` | String | `''` | Classes to add to the transitioning element before the leave phase starts. |
| `leaveTo` | String | `''` | Classes to add to the transitioning element immediately after the leave phase starts. |
| `beforeEnter` | Function | - | Callback which is called before we start the enter transition. |
| `afterEnter` | Function | - | Callback which is called after we finished the enter transition. |
| `beforeLeave` | Function | - | Callback which is called before we start the leave transition. |
| `afterLeave` | Function | - | Callback which is called after we finished the leave transition. |
##### Render prop object
- None
#### Transition.Child
```jsx
<Transition show={isOpen}>
<Transition.Child
enter="transition-opacity ease-linear duration-300"
enterFrom="opacity-0"
enterTo="opacity-100"
leave="transition-opacity ease-linear duration-300"
leaveFrom="opacity-100"
leaveTo="opacity-0"
>
{/* ... */}
</Transition.Child>
{/* ... */}
</Transition>
```
##### Props
| Prop | Type | Default | Description |
| :------------ | :------------------ | :------ | :------------------------------------------------------------------------------------ |
| `as` | String \| Component | `div` | The element or component to render in place of the `Transition.Child` itself. |
| `appear` | Boolean | `false` | Whether the transition should run on initial mount. |
| `unmount` | Boolean | `true` | Whether the element should be `unmounted` or `hidden` based on the show state. |
| `enter` | String | `''` | Classes to add to the transitioning element during the entire enter phase. |
| `enterFrom` | String | `''` | Classes to add to the transitioning element before the enter phase starts. |
| `enterTo` | String | `''` | Classes to add to the transitioning element immediately after the enter phase starts. |
| `leave` | String | `''` | Classes to add to the transitioning element during the entire leave phase. |
| `leaveFrom` | String | `''` | Classes to add to the transitioning element before the leave phase starts. |
| `leaveTo` | String | `''` | Classes to add to the transitioning element immediately after the leave phase starts. |
| `beforeEnter` | Function | - | Callback which is called before we start the enter transition. |
| `afterEnter` | Function | - | Callback which is called after we finished the enter transition. |
| `beforeLeave` | Function | - | Callback which is called before we start the leave transition. |
| `afterLeave` | Function | - | Callback which is called after we finished the leave transition. |
##### Render prop object
- None
@@ -1,12 +1,12 @@
import React, {
useMemo,
createContext,
useContext,
useRef,
useEffect,
useCallback,
useState,
Fragment,
createContext,
useCallback,
useContext,
useEffect,
useMemo,
useRef,
useState,
// Types
ElementType,
@@ -0,0 +1,12 @@
import { useState, useCallback } from 'react'
export function useFlags(initialFlags = 0) {
let [flags, setFlags] = useState(initialFlags)
let addFlag = useCallback((flag: number) => setFlags(flags => flags | flag), [setFlags])
let hasFlag = useCallback((flag: number) => Boolean(flags & flag), [flags])
let removeFlag = useCallback((flag: number) => setFlags(flags => flags & ~flag), [setFlags])
let toggleFlag = useCallback((flag: number) => setFlags(flags => flags ^ flag), [setFlags])
return { addFlag, hasFlag, removeFlag, toggleFlag }
}
@@ -6,6 +6,7 @@ import * as HeadlessUI from './index'
*/
it('should expose the correct components', () => {
expect(Object.keys(HeadlessUI)).toEqual([
'Alert',
'Dialog',
'Disclosure',
'FocusTrap',
@@ -13,6 +14,7 @@ it('should expose the correct components', () => {
'Menu',
'Popover',
'Portal',
'RadioGroup',
'Switch',
'Transition',
])
+2
View File
@@ -1,3 +1,4 @@
export * from './components/alert/alert'
export * from './components/dialog/dialog'
export * from './components/disclosure/disclosure'
export * from './components/focus-trap/focus-trap'
@@ -5,5 +6,6 @@ export * from './components/listbox/listbox'
export * from './components/menu/menu'
export * from './components/popover/popover'
export * from './components/portal/portal'
export * from './components/radio-group/radio-group'
export * from './components/switch/switch'
export * from './components/transitions/transition'
@@ -0,0 +1,26 @@
import React, {
createContext,
useContext,
// Types
ReactNode,
} from 'react'
let ForcePortalRootContext = createContext(false)
export function usePortalRoot() {
return useContext(ForcePortalRootContext)
}
interface ForcePortalRootProps {
force: boolean
children: ReactNode
}
export function ForcePortalRoot(props: ForcePortalRootProps) {
return (
<ForcePortalRootContext.Provider value={props.force}>
{props.children}
</ForcePortalRootContext.Provider>
)
}
@@ -1,3 +1,5 @@
import { isFocusableElement, FocusableMode } from '../utils/focus-management'
function assertNever(x: never): never {
throw new Error('Unexpected object: ' + x)
}
@@ -1103,6 +1105,48 @@ export function assertDialogOverlay(
// ---
export function getRadioGroup(): HTMLElement | null {
return document.querySelector('[role="radiogroup"]')
}
export function getRadioGroupLabel(): HTMLElement | null {
return document.querySelector('[id^="headlessui-label-"]')
}
export function getRadioGroupOptions(): HTMLElement[] {
return Array.from(document.querySelectorAll('[id^="headlessui-radiogroup-option-"]'))
}
// ---
export function assertRadioGroupLabel(
options: {
attributes?: Record<string, string | null>
textContent?: string
},
label = getRadioGroupLabel(),
radioGroup = getRadioGroup()
) {
try {
if (label === null) return expect(label).not.toBe(null)
if (radioGroup === null) return expect(radioGroup).not.toBe(null)
expect(label).toHaveAttribute('id')
expect(radioGroup).toHaveAttribute('aria-labelledby', label.id)
if (options.textContent) expect(label).toHaveTextContent(options.textContent)
for (let attributeName in options.attributes) {
expect(label).toHaveAttribute(attributeName, options.attributes[attributeName])
}
} catch (err) {
Error.captureStackTrace(err, assertRadioGroupLabel)
throw err
}
}
// ---
export function assertActiveElement(element: HTMLElement | null) {
try {
if (element === null) return expect(element).not.toBe(null)
@@ -1159,6 +1203,30 @@ export function assertVisible(element: HTMLElement | null) {
// ---
export function assertFocusable(element: HTMLElement | null) {
try {
if (element === null) return expect(element).not.toBe(null)
expect(isFocusableElement(element, FocusableMode.Strict)).toBe(true)
} catch (err) {
Error.captureStackTrace(err, assertFocusable)
throw err
}
}
export function assertNotFocusable(element: HTMLElement | null) {
try {
if (element === null) return expect(element).not.toBe(null)
expect(isFocusableElement(element, FocusableMode.Strict)).toBe(false)
} catch (err) {
Error.captureStackTrace(err, assertNotFocusable)
throw err
}
}
// ---
export function getByText(text: string): HTMLElement | null {
let walker = document.createTreeWalker(document.body, NodeFilter.SHOW_ELEMENT, {
acceptNode(node: HTMLElement) {
@@ -14,7 +14,9 @@ export let Keys: Record<string, Partial<KeyboardEvent>> = {
Escape: { key: 'Escape', keyCode: 27, charCode: 27 },
Backspace: { key: 'Backspace', keyCode: 8 },
ArrowLeft: { key: 'ArrowLeft', keyCode: 37 },
ArrowUp: { key: 'ArrowUp', keyCode: 38 },
ArrowRight: { key: 'ArrowRight', keyCode: 39 },
ArrowDown: { key: 'ArrowDown', keyCode: 40 },
Home: { key: 'Home', keyCode: 36 },
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,712 @@
## Listbox (Select)
[View live demo on CodeSandbox](https://codesandbox.io/s/headlessuivue-listbox-example-mi67g?file=/src/App.vue)
The `Listbox` component and related child components are used to quickly build custom listbox components that are fully accessible out of the box, including correct ARIA attribute management and robust keyboard navigation support.
- [Installation](#installation)
- [Basic example](#basic-example)
- [Styling the active and selected option](#styling-the-active-and-selected-option)
- [Showing/hiding the listbox](#showinghiding-the-listbox)
- [Using a custom label](#using-a-custom-label)
- [Disabling an option](#disabling-an-option)
- [Transitions](#transitions)
- [Rendering additional content](#rendering-additional-content)
- [Rendering a different element for a component](#rendering-a-different-element-for-a-component)
- [Component API](#component-api)
## Installation
Please note that **this library only supports Vue 3**.
```sh
# npm
npm install @headlessui/vue
# Yarn
yarn add @headlessui/vue
```
### Basic example
Listboxes are built using the `Listbox`, `ListboxButton`, `ListboxOptions`, `ListboxOption` and `ListboxLabel` components.
The `ListboxButton` will automatically open/close the `ListboxOptions` when clicked, and when the menu is open, the list of items receives focus and is automatically navigable via the keyboard.
```vue
<template>
<Listbox v-model="selectedPerson">
<ListboxButton>{{ selectedPerson.name }}</ListboxButton>
<ListboxOptions>
<ListboxOption
v-for="person in people"
:key="person.id"
:value="person"
:disabled="person.unavailable"
>
{{ person.name }}
</ListboxOption>
</ListboxOptions>
</Listbox>
</template>
<script>
import { ref } from 'vue'
import {
Listbox,
ListboxLabel,
ListboxButton,
ListboxOptions,
ListboxOption,
} from '@headlessui/vue'
export default {
components: {
Listbox,
ListboxLabel,
ListboxButton,
ListboxOptions,
ListboxOption,
},
setup() {
const people = [
{ id: 1, name: 'Durward Reynolds', unavailable: false },
{ id: 2, name: 'Kenton Towne', unavailable: false },
{ id: 3, name: 'Therese Wunsch', unavailable: false },
{ id: 4, name: 'Benedict Kessler', unavailable: true },
{ id: 5, name: 'Katelyn Rohan', unavailable: false },
]
const selectedPerson = ref(people[0])
return {
people,
selectedPerson,
}
},
}
</script>
```
### Styling the active and selected option
This is a headless component so there are no styles included by default. Instead, the components expose useful information via [scoped slots](https://v3.vuejs.org/guide/component-slots.html#scoped-slots) that you can use to apply the styles you'd like to apply yourself.
To style the active `ListboxOption` you can read the `active` slot prop, which tells you whether or not that listbox option is the option that is currently focused via the mouse or keyboard.
To style the selected `ListboxOption` you can read the `selected` slot prop, which tells you whether or not that listbox option is the option that is currently the `value` passed to the `Listbox`.
You can use this state to conditionally apply whatever active/focus styles you like, for instance a blue background like is typical in most operating systems. For the selected state, you might conditionally render a checkmark next to the seleted option.
```vue
<template>
<Listbox v-model="selectedPerson">
<ListboxButton>{{ selectedPerson.name }}</ListboxButton>
<ListboxOptions>
<!-- Use the `active` state to conditionally style the active option. -->
<!-- Use the `selected` state to conditionally style the selected option. -->
<ListboxOption
as="template"
v-slot="{ active, selected }"
v-for="person in people"
:key="person.id"
:value="person"
>
<li :class="{ 'bg-blue-500 text-white': active, 'bg-white text-black': !active }">
<CheckmarkIcon v-show="selected" />
{{ person.name }}
</li>
</ListboxOption>
</ListboxOptions>
</Listbox>
</template>
<script>
import { ref } from 'vue'
import {
Listbox,
ListboxLabel,
ListboxButton,
ListboxOptions,
ListboxOption,
} from '@headlessui/vue'
import CheckmarkIcon from './CheckmarkIcon'
export default {
components: {
Listbox,
ListboxLabel,
ListboxButton,
ListboxOptions,
ListboxOption,
CheckmarkIcon,
},
setup() {
const people = [
{ id: 1, name: 'Durward Reynolds' },
{ id: 2, name: 'Kenton Towne' },
{ id: 3, name: 'Therese Wunsch' },
{ id: 4, name: 'Benedict Kessler' },
{ id: 5, name: 'Katelyn Rohan' },
]
const selectedPerson = ref(people[0])
return {
people,
selectedPerson,
}
},
}
</script>
```
### Using a custom label
By default the `Listbox` will use the button contents as the label for screenreaders. However you can also render a custom `ListboxLabel` which will be automatically linked to the listbox with a generated ID.
```vue
<template>
<Listbox v-model="country">
<ListboxLabel>Country:</ListboxLabel>
<ListboxButton>{country}</ListboxButton>
<ListboxOptions>
<ListboxOption value="australia">Australia</ListboxOption>
<ListboxOption value="belgium">Belgium</ListboxOption>
<ListboxOption value="canada">Canada</ListboxOption>
<ListboxOption value="england">England</ListboxOption>
<!-- ... -->
</ListboxOptions>
</Listbox>
</template>
<script>
import { ref } from 'vue'
import {
Listbox,
ListboxLabel,
ListboxButton,
ListboxOptions,
ListboxOption,
} from '@headlessui/vue'
export default {
components: {
Listbox,
ListboxLabel,
ListboxButton,
ListboxOptions,
ListboxOption,
},
setup() {
const country = ref('belgium')
return {
country,
}
},
}
</script>
```
### Showing/hiding the listbox
By default, your `ListboxOptions` instance will be shown/hidden automatically based on the internal `open` state tracked within the `Listbox` component itself.
```vue
<template>
<Listbox v-model="option">
<ListboxButton>{{ person.name }}</ListboxButton>
<!-- By default, this will automatically show/hide when the ListboxButton is pressed. -->
<ListboxOptions>
<ListboxOption v-for="person in people" :key="person.id" :value="person">
{{ person.name }}
</ListboxOption>
</ListboxOptions>
</Listbox>
</template>
<script>
import { ref } from 'vue'
import {
Listbox,
ListboxLabel,
ListboxButton,
ListboxOptions,
ListboxOption,
} from '@headlessui/vue'
export default {
components: {
Listbox,
ListboxLabel,
ListboxButton,
ListboxOptions,
ListboxOption,
},
setup() {
const people = [
{ id: 1, name: 'Durward Reynolds' },
{ id: 2, name: 'Kenton Towne' },
{ id: 3, name: 'Therese Wunsch' },
{ id: 4, name: 'Benedict Kessler' },
{ id: 5, name: 'Katelyn Rohan' },
]
const selectedPerson = ref(people[0])
return {
people,
selectedPerson,
}
},
}
</script>
```
If you'd rather handle this yourself (perhaps because you need to add an extra wrapper element for one reason or another), you can add a `static` prop to the `ListboxOptions` instance to tell it to always render, and inspect the `open` slot prop provided by the `Listbox` to control which element is shown/hidden yourself.
```vue
<template>
<Listbox v-model="option" v-slot="{ open }">
<ListboxButton>{{ person.name }}</ListboxButton>
<div v-show="open">
<!-- Using `static`, `ListboxOptions` is always rendered and ignores the `open` state. -->
<ListboxOptions static>
<ListboxOption v-for="person in people" :key="person.id" :value="person">
{{ person.name }}
</ListboxOption>
</ListboxOptions>
</div>
</Listbox>
</template>
<script>
import { ref } from 'vue'
import {
Listbox,
ListboxLabel,
ListboxButton,
ListboxOptions,
ListboxOption,
} from '@headlessui/vue'
export default {
components: {
Listbox,
ListboxLabel,
ListboxButton,
ListboxOptions,
ListboxOption,
},
setup() {
const people = [
{ id: 1, name: 'Durward Reynolds' },
{ id: 2, name: 'Kenton Towne' },
{ id: 3, name: 'Therese Wunsch' },
{ id: 4, name: 'Benedict Kessler' },
{ id: 5, name: 'Katelyn Rohan' },
]
const selectedPerson = ref(people[0])
return {
people,
selectedPerson,
}
},
}
</script>
```
### Disabling an option
Use the `disabled` prop to disable a `ListboxOption`. This will make it unselectable via keyboard navigation, and it will be skipped when pressing the up/down arrows.
```vue
<template>
<Listbox v-model="selectedPerson">
<ListboxButton>{{ selectedPerson.name }}</ListboxButton>
<ListboxOptions>
<!-- Disabled options will be skipped by keyboard navigation. -->
<ListboxOption
v-for="person in people"
:key="person.id"
:value="person"
:disabled="person.unavailable"
>
<span :class="{ 'opacity-75': person.unavailable }">{{ person.name }}</span>
</ListboxOption>
</ListboxOptions>
</Listbox>
</template>
<script>
import { ref } from 'vue'
import {
Listbox,
ListboxLabel,
ListboxButton,
ListboxOptions,
ListboxOption,
} from '@headlessui/vue'
export default {
components: {
Listbox,
ListboxLabel,
ListboxButton,
ListboxOptions,
ListboxOption,
},
setup() {
const people = [
{ id: 1, name: 'Durward Reynolds', unavailable: false },
{ id: 2, name: 'Kenton Towne', unavailable: false },
{ id: 3, name: 'Therese Wunsch', unavailable: false },
{ id: 4, name: 'Benedict Kessler', unavailable: true },
{ id: 5, name: 'Katelyn Rohan', unavailable: false },
]
const selectedPerson = ref(people[0])
return {
people,
selectedPerson,
}
},
}
</script>
```
### Transitions
To animate the opening/closing of the menu panel, use Vue's built-in `transition` component. All you need to do is wrap your `ListboxOptions` instance in a `<transition>` element and the transition will be applied automatically.
```vue
<template>
<Listbox v-model="selectedPerson">
<ListboxButton>{{ selectedPerson.name }}</ListboxButton>
<transition
enter-active-class="transition duration-100 ease-out"
enter-from-class="transform scale-95 opacity-0"
enter-to-class="transform scale-100 opacity-100"
leave-active-class="transition duration-75 ease-out"
leave-from-class="transform scale-100 opacity-100"
leave-to-class="transform scale-95 opacity-0"
>
<ListboxOptions>
<ListboxOption
v-for="person in people"
:key="person.id"
:value="person"
:disabled="person.unavailable"
>
{{ person.name }}
</ListboxOption>
</ListboxOptions>
</transition>
</Listbox>
</template>
<script>
import { ref } from 'vue'
import {
Listbox,
ListboxLabel,
ListboxButton,
ListboxOptions,
ListboxOption,
} from '@headlessui/vue'
export default {
components: {
Listbox,
ListboxLabel,
ListboxButton,
ListboxOptions,
ListboxOption,
},
setup() {
const people = [
{ id: 1, name: 'Durward Reynolds', unavailable: false },
{ id: 2, name: 'Kenton Towne', unavailable: false },
{ id: 3, name: 'Therese Wunsch', unavailable: false },
{ id: 4, name: 'Benedict Kessler', unavailable: true },
{ id: 5, name: 'Katelyn Rohan', unavailable: false },
]
const selectedPerson = ref(people[0])
return {
people,
selectedPerson,
}
},
}
</script>
```
### Rendering a different element for a component
By default, the `Listbox` and its subcomponents each render a default element that is sensible for that component.
For example, `ListboxLabel` renders a `label` by default, `ListboxButton` renders a `button` by default, `ListboxOptions` renders a `ul` and `ListboxOption` renders a `li` by default. `Listbox` interestingly _does not render an extra element_, and instead renders its children directly by default.
This is easy to change using the `as` prop, which exists on every component.
```vue
<template>
<Listbox as="div" v-model="selectedPerson">
<ListboxButton>{{ selectedPerson.name }}</ListboxButton>
<ListboxOptions as="div">
<ListboxOption as="span" v-for="person in people" :key="person.id" :value="person">
{{ person.name }}
</ListboxOption>
</ListboxOptions>
</Listbox>
</template>
<script>
import { ref } from 'vue'
import {
Listbox,
ListboxLabel,
ListboxButton,
ListboxOptions,
ListboxOption,
} from '@headlessui/vue'
export default {
components: {
Listbox,
ListboxLabel,
ListboxButton,
ListboxOptions,
ListboxOption,
},
setup() {
const people = [
{ id: 1, name: 'Durward Reynolds' },
{ id: 2, name: 'Kenton Towne' },
{ id: 3, name: 'Therese Wunsch' },
{ id: 4, name: 'Benedict Kessler' },
{ id: 5, name: 'Katelyn Rohan' },
]
const selectedPerson = ref(people[0])
return {
people,
selectedPerson,
}
},
}
</script>
```
To tell an element to render its children directly with no wrapper element, use `as="template"`.
```vue
<template>
<Listbox v-model="selectedPerson">
<!-- Render no wrapper, instead pass in a button manually. -->
<ListboxButton as="template">
<button>{{ selectedPerson.name }}</button>
</ListboxButton>
<ListboxOptions>
<ListboxOption v-for="person in people" :key="person.id" :value="person">
{{ person.name }}
</ListboxOption>
</ListboxOptions>
</Listbox>
</template>
<script>
import { ref } from 'vue'
import {
Listbox,
ListboxLabel,
ListboxButton,
ListboxOptions,
ListboxOption,
} from '@headlessui/vue'
export default {
components: {
Listbox,
ListboxLabel,
ListboxButton,
ListboxOptions,
ListboxOption,
},
setup() {
const people = [
{ id: 1, name: 'Durward Reynolds' },
{ id: 2, name: 'Kenton Towne' },
{ id: 3, name: 'Therese Wunsch' },
{ id: 4, name: 'Benedict Kessler' },
{ id: 5, name: 'Katelyn Rohan' },
]
const selectedPerson = ref(people[0])
return {
people,
selectedPerson,
}
},
}
</script>
```
### Component API
#### Listbox
```vue
<template>
<Listbox v-model="selectedPerson">
<ListboxButton>
{{ selectedPerson.name }}
</ListboxButton>
<ListboxOptions>
<ListboxOption v-for="person in people" :key="person.id" :value="person">
{{ person.name }}
</ListboxOption>
</ListboxOptions>
</Listbox>
</template>
<script>
import { ref } from 'vue'
import {
Listbox,
ListboxLabel,
ListboxButton,
ListboxOptions,
ListboxOption,
} from '@headlessui/vue'
export default {
components: {
Listbox,
ListboxLabel,
ListboxButton,
ListboxOptions,
ListboxOption,
},
setup() {
const people = [
{ id: 1, name: 'Durward Reynolds' },
{ id: 2, name: 'Kenton Towne' },
{ id: 3, name: 'Therese Wunsch' },
{ id: 4, name: 'Benedict Kessler' },
{ id: 5, name: 'Katelyn Rohan' },
]
const selectedPerson = ref(people[0])
return {
people,
selectedPerson,
}
},
}
</script>
```
##### Props
| Prop | Type | Default | Description |
| :--------- | :------------------ | :-------------------------------- | :------------------------------------------------------- |
| `as` | String \| Component | `template` _(no wrapper element_) | The element or component the `Listbox` should render as. |
| `v-model` | `T` | - | The selected value. |
| `disabled` | Boolean | `false` | Enable/Disable the `Listbox` component. |
##### Slot props
| Prop | Type | Description |
| :--------- | :------ | :-------------------------------------- |
| `open` | Boolean | Whether or not the listbox is open. |
| `disabled` | Boolean | Whether or not the listbox is disabled. |
#### ListboxButton
```vue
<ListboxButton v-slot="{ open }">
<span>{{ selectedPerson.name }}</span>
<ChevronRightIcon class={`${open ? 'transform rotate-90' : ''}`} />
</ListboxButton>
```
##### Props
| Prop | Type | Default | Description |
| :--- | :------------------ | :------- | :------------------------------------------------------------- |
| `as` | String \| Component | `button` | The element or component the `ListboxButton` should render as. |
##### Slot props
| Prop | Type | Description |
| :--------- | :------ | :-------------------------------------- |
| `open` | Boolean | Whether or not the listbox is open. |
| `disabled` | Boolean | Whether or not the listbox is disabled. |
#### ListboxLabel
```vue
<ListboxLabel>Enable notifications</ListboxLabel>
```
##### Props
| Prop | Type | Default | Description |
| :--- | :------------------ | :------ | :------------------------------------------------------------ |
| `as` | String \| Component | `label` | The element or component the `ListboxLabel` should render as. |
##### Slot props
| Prop | Type | Description |
| :--------- | :------ | :-------------------------------------- |
| `open` | Boolean | Whether or not the listbox is open. |
| `disabled` | Boolean | Whether or not the listbox is disabled. |
#### ListboxOptions
```vue
<ListboxOptions>
<ListboxOption value="option-a"><!-- ... --></ListboxOption>
<!-- ... -->
</ListboxOptions>
```
##### Props
| Prop | Type | Default | Description |
| :-------- | :------------------ | :------ | :-------------------------------------------------------------------------------- |
| `as` | String \| Component | `ul` | The element or component the `ListboxOptions` should render as. |
| `static` | Boolean | `false` | Whether the element should ignore the internally managed open/closed state. |
| `unmount` | Boolean | `true` | Whether the element should be unmounted or hidden based on the open/closed state. |
##### Slot props
| Prop | Type | Description |
| :----- | :------ | :---------------------------------- |
| `open` | Boolean | Whether or not the listbox is open. |
#### ListboxOption
```vue
<ListboxOption value="option-a">Option A</ListboxOption>
```
##### Props
| Prop | Type | Default | Description |
| :--------- | :------------------ | :------ | :-------------------------------------------------------------------------------------- |
| `as` | String \| Component | `li` | The element or component the `ListboxOption` should render as. |
| `value` | `T` | - | The option value. |
| `disabled` | Boolean | `false` | Whether or not the option should be disabled for keyboard navigation and ARIA purposes. |
##### Slot props
| Prop | Type | Description |
| :--------- | :------ | :----------------------------------------------------------------------------------- |
| `active` | Boolean | Whether or not the option is the active/focused option in the list. |
| `selected` | Boolean | Whether or not the option is the selected option in the list. |
| `disabled` | Boolean | Whether or not the option is the disabled for keyboard navigation and ARIA purposes. |
@@ -0,0 +1,335 @@
## Menu Button (Dropdown)
[View live demo on CodeSandbox](https://codesandbox.io/s/headlessuivue-menu-example-70br3?file=/src/App.vue)
The `Menu` component and related child components are used to quickly build custom dropdown components that are fully accessible out of the box, including correct ARIA attribute management and robust keyboard navigation support.
- [Installation](#installation)
- [Basic example](#basic-example)
- [Styling](#styling)
- [Transitions](#transitions)
- [Component API](#component-api)
## Installation
Please note that **this library only supports Vue 3**.
```sh
# npm
npm install @headlessui/vue
# Yarn
yarn add @headlessui/vue
```
### Basic example
Menu Buttons are built using the `Menu`, `MenuButton`, `MenuItems`, and `MenuItem` components.
The `MenuButton` will automatically open/close the `MenuItems` when clicked, and when the menu is open, the list of items receives focus and is automatically navigable via the keyboard.
```vue
<template>
<Menu>
<MenuButton> More </MenuButton>
<MenuItems>
<MenuItem v-slot="{ active }">
<a :class="{ 'bg-blue-500': active }" href="/account-settings"> Account settings </a>
</MenuItem>
<MenuItem v-slot="{ active }">
<a :class="{ 'bg-blue-500': active }" href="/account-settings"> Documentation </a>
</MenuItem>
<MenuItem v-slot="{ active }" disabled>
<span :class="{ 'bg-blue-500': active }"> Invite a friend (coming soon!) </span>
</MenuItem>
</MenuItems>
</Menu>
</template>
<script>
import { Menu, MenuButton, MenuItems, MenuItem } from '@headlessui/vue'
export default {
components: {
Menu,
MenuButton,
MenuItems,
MenuItem,
},
}
</script>
```
### Styling the active item
This is a headless component so there are no styles included by default. Instead, the components expose useful information via [scoped slots](https://v3.vuejs.org/guide/component-slots.html#scoped-slots) that you can use to apply the styles you'd like to apply yourself.
To style the active `MenuItem` you can read the `active` slot prop, which tells you whether or not that menu item is the item that is currently focused via the mouse or keyboard.
You can use this state to conditionally apply whatever active/focus styles you like, for instance a blue background like is typical in most operating systems.
```vue
<template>
<Menu>
<MenuButton> More </MenuButton>
<MenuItems>
<!-- Use the `active` state to conditionally style the active item. -->
<MenuItem v-slot="{ active }">
<a href="/settings" :class="active ? 'bg-blue-500 text-white' : 'bg-white text-black'">
Settings
</a>
</MenuItem>
<!-- ... -->
</MenuItems>
</Menu>
</template>
```
### Showing/hiding the menu
By default, your `MenuItems` instance will be shown/hidden automatically based on the internal `open` state tracked within the `Menu` component itself.
```vue
<template>
<Menu>
<MenuButton> More </MenuButton>
<!-- By default, this will automatically show/hide when the MenuButton is pressed. -->
<MenuItems>
<MenuItem v-slot="{ active }">
<a :class="{ 'bg-blue-500': active }" href="/account-settings"> Account settings </a>
</MenuItem>
<!-- ... -->
</MenuItems>
</Menu>
</template>
```
If you'd rather handle this yourself (perhaps because you need to add an extra wrapper element for one reason or another), you can add a `static` prop to the `MenuItems` instance to tell it to always render, and inspect the `open` slot prop provided by the `Menu` to control which element is shown/hidden yourself.
```vue
<template>
<Menu v-slot="{ open }">
<MenuButton> More </MenuButton>
<div v-show="open">
<!-- Using `static`, `MenuItems` is always rendered and ignores the `open` state. -->
<MenuItems static>
<MenuItem v-slot="{ active }">
<a :class="{ 'bg-blue-500': active }" href="/account-settings"> Account settings </a>
</MenuItem>
<!-- ... -->
</MenuItems>
</div>
</Menu>
</template>
```
### Disabling an item
Use the `disabled` prop to disable a `MenuItem`. This will make it unselectable via keyboard navigation, and it will be skipped when pressing the up/down arrows.
```vue
<template>
<Menu>
<MenuButton> More </MenuButton>
<MenuItems>
<MenuItem disabled>
<span class="opacity-75">Invite a friend (coming soon!)</span>
</MenuItem>
<!-- ... -->
</MenuItems>
</Menu>
</template>
```
### Transitions
To animate the opening/closing of the menu panel, use Vue's built-in `transition` component. All you need to do is wrap your `MenuItems` instance in a `<transition>` element and the transition will be applied automatically.
```vue
<template>
<Menu>
<MenuButton> More </MenuButton>
<transition
enter-active-class="transition duration-100 ease-out"
enter-from-class="transform scale-95 opacity-0"
enter-to-class="transform scale-100 opacity-100"
leave-active-class="transition duration-75 ease-out"
leave-from-class="transform scale-100 opacity-100"
leave-to-class="transform scale-95 opacity-0"
>
<MenuItems>
<MenuItem v-slot="{ active }">
<a :class="{ 'bg-blue-500': active }" href="/account-settings"> Account settings </a>
</MenuItem>
<!-- ... -->
</MenuItems>
</transition>
</Menu>
</template>
```
### Rendering additional content
The `Menu` component is not limited to rendering only its related subcomponents. You can render anything you like within a menu, which gives you complete control over exactly what you are building.
For example, if you'd like to add a little header section to the menu with some extra information in it, just render an extra `div` with your content in it.
```vue
<template>
<Menu>
<MenuButton> More </MenuButton>
<MenuItems>
<div class="px-4 py-3">
<p class="text-sm leading-5">Signed in as</p>
<p class="text-sm font-medium leading-5 text-gray-900 truncate">tom@example.com</p>
</div>
<MenuItem v-slot="{ active }">
<a :class="{ 'bg-blue-500': active }" href="/account-settings"> Account settings </a>
</MenuItem>
<!-- ... -->
</MenuItems>
</Menu>
</template>
```
Note that only `MenuItem` instances will be navigable via the keyboard.
### Rendering a different element for a component
By default, the `Menu` and its subcomponents each render a default element that is sensible for that component.
For example, `MenuButton` renders a `button` by default, and `MenuItems` renders a `div`. `Menu` and `MenuItem` interestingly _do not render an extra element_, and instead render their children directly by default.
This is easy to change using the `as` prop, which exists on every component.
```vue
<template>
<!-- Render a `div` instead of no wrapper element -->
<Menu as="div">
<MenuButton> More </MenuButton>
<!-- Render a `ul` instead of a `div` -->
<MenuItems as="ul">
<!-- Render an `li` instead of no wrapper element -->
<MenuItem as="li" v-slot="{ active }">
<a href="/account-settings" :class="{ 'bg-blue-500': active }"> Account settings </a>
</MenuItem>
<!-- ... -->
</MenuItems>
</Menu>
</template>
```
To tell an element to render its children directly with no wrapper element, use `as="template"`.
```vue
<template>
<Menu>
<!-- Render no wrapper, instead pass in a button manually -->
<MenuButton as="template">
<button>More</button>
</MenuButton>
<MenuItems>
<MenuItem v-slot="{ active }">
<a href="/account-settings" :class="{ 'bg-blue-500': active }"> Account settings </a>
</MenuItem>
<!-- ... -->
</MenuItems>
</Menu>
</template>
```
### Component API
#### Menu
```vue
<Menu v-slot="{ open }">
<MenuButton>More options</MenuButton>
<MenuItems>
<MenuItem><!-- ... --></MenuItem>
<!-- ... -->
</MenuItems>
</Menu>
```
##### Props
| Prop | Type | Default | Description |
| :--- | :------------------ | :-------------------------------- | :---------------------------------------------------- |
| `as` | String \| Component | `template` _(no wrapper element_) | The element or component the `Menu` should render as. |
##### Slot props
| Prop | Type | Description |
| :----- | :------ | :------------------------------- |
| `open` | Boolean | Whether or not the menu is open. |
#### MenuButton
```vue
<MenuButton v-slot="{ open }">
<span>More options</span>
<ChevronRightIcon :class="open ? 'transform rotate-90' : ''" />
</MenuButton>
```
##### Props
| Prop | Type | Default | Description |
| :--- | :------------------ | :------- | :---------------------------------------------------------- |
| `as` | String \| Component | `button` | The element or component the `MenuButton` should render as. |
##### Slot props
| Prop | Type | Description |
| :----- | :------ | :------------------------------- |
| `open` | Boolean | Whether or not the menu is open. |
#### MenuItems
```vue
<MenuItems>
<MenuItem><!-- ... --></MenuItem>
<!-- ... -->
</MenuItem>
```
##### Props
| Prop | Type | Default | Description |
| :-------- | :------------------ | :------ | :-------------------------------------------------------------------------------- |
| `as` | String \| Component | `div` | The element or component the `MenuItems` should render as. |
| `static` | Boolean | `false` | Whether the element should ignore the internally managed open/closed state. |
| `unmount` | Boolean | `true` | Whether the element should be unmounted or hidden based on the open/closed state. |
##### Slot props
| Prop | Type | Description |
| :----- | :------ | :------------------------------- |
| `open` | Boolean | Whether or not the menu is open. |
#### MenuItem
```vue
<MenuItem v-slot="{ active }">
<a href="/settings" :class="active ? 'bg-blue-500 text-white' : 'bg-white text-black'">
Settings
</a>
</MenuItem>
```
##### Props
| Prop | Type | Default | Description |
| :--------- | :------------------ | :-------------------------------- | :------------------------------------------------------------------------------------ |
| `as` | String \| Component | `template` _(no wrapper element)_ | The element or component the `MenuItem` should render as. |
| `disabled` | Boolean | `false` | Whether or not the item should be disabled for keyboard navigation and ARIA purposes. |
##### Slot props
| Prop | Type | Description |
| :--------- | :------ | :--------------------------------------------------------------------------------- |
| `active` | Boolean | Whether or not the item is the active/focused item in the list. |
| `disabled` | Boolean | Whether or not the item is the disabled for keyboard navigation and ARIA purposes. |
@@ -0,0 +1,186 @@
## Switch (Toggle)
[View live demo on CodeSandbox](https://codesandbox.io/s/headlessuivue-switch-example-8ycp6?file=/src/App.vue)
The `Switch` component and related child components are used to quickly build custom switch/toggle components that are fully accessible out of the box, including correct ARIA attribute management and robust keyboard support.
- [Installation](#installation)
- [Basic example](#basic-example)
- [Using a custom label](#using-a-custom-label)
- [Component API](#component-api)
## Installation
Please note that **this library only supports Vue 3**.
```sh
# npm
npm install @headlessui/vue
# Yarn
yarn add @headlessui/vue
```
### Basic example
Switches are built using the `Switch` component. Optionally you can also use the `SwitchGroup`, `SwitchLabel` and `SwitchDescription` components.
```vue
<template>
<Switch
as="button"
v-model="switchValue"
class="relative inline-flex items-center h-6 rounded-full w-11"
:class="switchValue ? 'bg-blue-600' : 'bg-gray-200'"
v-slot="{ checked }"
>
<span
class="inline-block w-4 h-4 transform bg-white rounded-full"
:class="{ 'translate-x-6': checked, 'translate-x-1': !checked }"
/>
</Switch>
</template>
<script>
import { ref } from 'vue'
import { SwitchGroup, Switch, SwitchLabel, SwitchDescription } from '@headlessui/vue'
export default {
components: {
SwitchGroup,
Switch,
SwitchLabel,
SwitchDescription,
},
setup() {
const switchValue = ref(false)
return {
switchValue,
}
},
}
</script>
```
### Using a custom label
By default the `Switch` will use the contents as the label for screenreaders. If you need more control, you can render a `SwitchLabel` outside of the `Switch`, as long as both the switch and label are within a parent `SwitchGroup`.
Clicking the label will toggle the switch state, like you'd expect from a native checkbox.
```vue
<template>
<SwitchGroup as="div" class="flex items-center space-x-4">
<SwitchLabel>Enable notifications</SwitchLabel>
<Switch
as="button"
v-model="switchValue"
class="relative inline-flex items-center h-6 rounded-full w-11"
:class="switchValue ? 'bg-blue-600' : 'bg-gray-200'"
v-slot="{ checked }"
>
<span
class="inline-block w-4 h-4 transform bg-white rounded-full"
:class="{ 'translate-x-6': checked, 'translate-x-1': !checked }"
/>
</Switch>
</SwitchGroup>
</template>
<script>
import { ref } from 'vue'
import { SwitchGroup, Switch, SwitchLabel } from '@headlessui/vue'
export default {
components: {
SwitchGroup,
Switch,
SwitchLabel,
},
setup() {
const switchValue = ref(false)
return {
switchValue,
}
},
}
</script>
```
### Component API
#### Switch
```html
<Switch v-model="switchState">
<span class="sr-only">Enable notifications</span>
<!-- ... -->
</Switch>
```
##### Props
| Prop | Type | Default | Description |
| :-------- | :------------------ | :------- | :------------------------------------------------------ |
| `as` | String \| Component | `button` | The element or component the `Switch` should render as. |
| `v-model` | `T` | - | The switch value. |
##### Slot props
| Prop | Type | Description |
| :-------- | :------ | :------------------------------------ |
| `checked` | Boolean | Whether or not the switch is checked. |
#### SwitchLabel
```html
<SwitchGroup>
<SwitchLabel>Enable notifications</SwitchLabel>
<Switch v-model="switchState">
<!-- ... -->
</Switch>
</SwitchGroup>
```
##### Props
| Prop | Type | Default | Description |
| :--- | :------------------ | :------ | :----------------------------------------------------------- |
| `as` | String \| Component | `label` | The element or component the `SwitchLabel` should render as. |
#### SwitchDescription
```html
<SwitchGroup>
<SwitchDescription>Enable notifications</SwitchDescription>
<Switch v-model="switchState">
<!-- ... -->
</Switch>
</SwitchGroup>
```
##### Props
| Prop | Type | Default | Description |
| :--- | :------------------ | :------ | :----------------------------------------------------------------- |
| `as` | String \| Component | `p` | The element or component the `SwitchDescription` should render as. |
#### SwitchGroup
```html
<SwitchGroup>
<SwitchLabel>Enable notifications</SwitchLabel>
<Switch v-model="switchState">
<!-- ... -->
</Switch>
</SwitchGroup>
```
##### Props
| Prop | Type | Default | Description |
| :--- | :------------------ | :-------------------------------- | :----------------------------------------------------------- |
| `as` | String \| Component | `template` _(no wrapper element)_ | The element or component the `SwitchGroup` should render as. |