From 00cc8c50e36ebac689d1b65dfb09a4357ac7c24d Mon Sep 17 00:00:00 2001 From: Robin Malfait Date: Mon, 15 Mar 2021 12:07:36 +0100 Subject: [PATCH] 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 --- CHANGELOG.md | 2 + packages/@headlessui-react/README.md | 1838 +---------------- .../pages/dialog/dialog-with-alert.tsx | 126 ++ .../pages/radio-group/radio-group.tsx | 101 + .../src/components/alert/README.md | 49 + .../src/components/alert/alert.test.tsx | 31 + .../src/components/alert/alert.tsx | 48 + .../description/description.test.tsx | 108 + .../components/description/description.tsx | 86 + .../src/components/dialog/README.md | 155 ++ .../src/components/dialog/dialog.tsx | 45 +- .../src/components/disclosure/README.md | 81 + .../src/components/disclosure/disclosure.tsx | 10 +- .../src/components/focus-trap/README.md | 64 + .../src/components/keyboard.ts | 2 + .../src/components/label/label.test.tsx | 108 + .../src/components/label/label.tsx | 82 + .../src/components/listbox/README.md | 520 +++++ .../src/components/listbox/listbox.tsx | 2 +- .../src/components/menu/README.md | 406 ++++ .../src/components/menu/menu.tsx | 2 +- .../src/components/popover/README.md | 164 ++ .../src/components/popover/popover.tsx | 26 +- .../src/components/portal/README.md | 45 + .../src/components/portal/portal.test.tsx | 31 +- .../src/components/portal/portal.tsx | 76 +- .../src/components/radio-group/README.md | 89 + .../radio-group/radio-group.test.tsx | 664 ++++++ .../components/radio-group/radio-group.tsx | 333 +++ .../src/components/switch/README.md | 160 ++ .../src/components/switch/switch.tsx | 2 +- .../src/components/transitions/README.md | 308 +++ .../src/components/transitions/transition.tsx | 14 +- .../@headlessui-react/src/hooks/use-flags.ts | 12 + packages/@headlessui-react/src/index.test.ts | 2 + packages/@headlessui-react/src/index.ts | 2 + .../src/internal/portal-force-root.tsx | 26 + .../test-utils/accessibility-assertions.ts | 68 + .../src/test-utils/interactions.ts | 2 + packages/@headlessui-vue/README.md | 1205 +---------- .../src/components/listbox/README.md | 712 +++++++ .../src/components/menu/README.md | 335 +++ .../src/components/switch/README.md | 186 ++ 43 files changed, 5239 insertions(+), 3089 deletions(-) create mode 100644 packages/@headlessui-react/pages/dialog/dialog-with-alert.tsx create mode 100644 packages/@headlessui-react/pages/radio-group/radio-group.tsx create mode 100644 packages/@headlessui-react/src/components/alert/README.md create mode 100644 packages/@headlessui-react/src/components/alert/alert.test.tsx create mode 100644 packages/@headlessui-react/src/components/alert/alert.tsx create mode 100644 packages/@headlessui-react/src/components/description/description.test.tsx create mode 100644 packages/@headlessui-react/src/components/description/description.tsx create mode 100644 packages/@headlessui-react/src/components/dialog/README.md create mode 100644 packages/@headlessui-react/src/components/disclosure/README.md create mode 100644 packages/@headlessui-react/src/components/focus-trap/README.md create mode 100644 packages/@headlessui-react/src/components/label/label.test.tsx create mode 100644 packages/@headlessui-react/src/components/label/label.tsx create mode 100644 packages/@headlessui-react/src/components/listbox/README.md create mode 100644 packages/@headlessui-react/src/components/menu/README.md create mode 100644 packages/@headlessui-react/src/components/popover/README.md create mode 100644 packages/@headlessui-react/src/components/portal/README.md create mode 100644 packages/@headlessui-react/src/components/radio-group/README.md create mode 100644 packages/@headlessui-react/src/components/radio-group/radio-group.test.tsx create mode 100644 packages/@headlessui-react/src/components/radio-group/radio-group.tsx create mode 100644 packages/@headlessui-react/src/components/switch/README.md create mode 100644 packages/@headlessui-react/src/components/transitions/README.md create mode 100644 packages/@headlessui-react/src/hooks/use-flags.ts create mode 100644 packages/@headlessui-react/src/internal/portal-force-root.tsx create mode 100644 packages/@headlessui-vue/src/components/listbox/README.md create mode 100644 packages/@headlessui-vue/src/components/menu/README.md create mode 100644 packages/@headlessui-vue/src/components/switch/README.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 3026e33..b049bc8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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] diff --git a/packages/@headlessui-react/README.md b/packages/@headlessui-react/README.md index fd52844..a72221d 100644 --- a/packages/@headlessui-react/README.md +++ b/packages/@headlessui-react/README.md @@ -27,15 +27,17 @@ yarn add @headlessui/react _This project is still in early development. New components will be added regularly over the coming months._ -- [Transition](#transition) -- [Menu Button (Dropdown)](#menu-button-dropdown) -- [Listbox (Select)](#listbox-select) -- [Switch (Toggle)](#switch-toggle) -- [Disclosure](#disclosure) -- [FocusTrap](#focustrap) -- [Portal](#portal) -- [Dialog](#dialog) -- [Popover](#popover) +- [Transition](./src/components/transitions/README.md) +- [Menu Button (Dropdown)](./src/components/menu/README.md) +- [Listbox (Select)](./src/components/listbox/README.md) +- [Switch (Toggle)](./src/components/switch/README.md) +- [Disclosure](./src/components/disclosure/README.md) +- [FocusTrap](./src/components/focus-trap/README.md) +- [Portal](./src/components/portal/README.md) +- [Dialog](./src/components/dialog/README.md) +- [Popover](./src/components/popover/README.md) +- [Radio Group](./src/components/radio-group/README.md) +- [Alert](./src/components/alert/README.md) ### Roadmap @@ -49,1821 +51,3 @@ This includes things like: ...and more in the future. We'll be continuing to develop new components on an on-going basis, with a goal of reaching a pretty fleshed out v1.0 by the end of the year. - ---- - -## 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. - -- [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) - -### 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 ( - <> - - - I will fade in and out - - - ) -} -``` - -### Showing and hiding content - -Wrap the content that should be conditionally rendered in a `` 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 ( - <> - - - I will fade in and out - - - ) -} -``` - -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 ( - <> - - - I will fade in and out - - - ) -} -``` - -### 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 ( - <> - - - I will fade in and out - - - ) -} -``` - -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 ( - - {/* Background overlay */} - - {/* ... */} - - - {/* Sliding sidebar */} - - {/* ... */} - - - ) -} -``` - -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 ( - - {/* Your content goes here*/} - - ) -} -``` - -### Component API - -#### Transition - -```jsx - - {/* Your content goes here*/} - -``` - -##### 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 - - - {/* ... */} - - {/* ... */} - -``` - -##### 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 - ---- - -## 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. - -- [Basic example](#basic-example-1) -- [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-1) - -### 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 ( - - More - - - {({ active }) => ( - - Account settings - - )} - - - {({ active }) => ( - - Documentation - - )} - - - Invite a friend (coming soon!) - - - - ) -} -``` - -### 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 ( - - More - - {/* Use the `active` state to conditionally style the active item. */} - - {({ active }) => ( - - Account settings - - )} - - {/* ... */} - - - ) -} -``` - -### 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 ( - - More - - {/* By default, this will automatically show/hide when the Menu.Button is pressed. */} - - {/* ... */} - {/* ... */} - - - ) -} -``` - -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 ( - - {({ open }) => ( - More - {open && ( -
- {/* Using `static`, `Menu.Items` is always rendered and ignores the `open` state. */} - - {/* ... */} - {/* ... */} - -
- )} - )} -
- ) -} -``` - -### 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 ( - - More - - {/* ... */} - - {/* This item will be skipped by keyboard navigation. */} - - Invite a friend (coming soon!) - - - {/* ... */} - - - ) -} -``` - -### 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 ``, and the transition will be applied automatically. - -```jsx -import { Menu, Transition } from '@headlessui/react' - -function MyDropdown() { - return ( - - {({ open }) => ( - <> - More - - {/* Use the Transition + open render prop argument to add transitions. */} - - - {/* ... */} - {/* ... */} - - - - )} - - ) -} -``` - -### 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 ( - - More - -
-

Signed in as

-

tom@example.com

-
- - {({ active }) => ( - - Account settings - - )} - - - {/* ... */} -
-
- ) -} -``` - -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 */} - - More - {/* Render a `ul` instead of a `div` */} - - {/* Render an `li` instead of no wrapper element */} - - {({ active }) => ( - - Account settings - - )} - - - {/* ... */} - - - ) -} -``` - -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 ( - - {/* Render no wrapper, instead pass in a button manually. */} - - - - - - {({ active }) => ( - - Account settings - - )} - - {/* ... */} - - - ) -} -``` - -### Component API - -#### Menu - -```jsx - - More - - {/* ... */} - {/* ... */} - - -``` - -##### 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 - - {({ open }) => ( - <> - More options - - - )} - -``` - -##### 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 - - {/* ... */}> - {/* ... */}> - -``` - -##### 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 - - {({ active }) => ( - - Account settings - - )} - -``` - -##### 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. | - -## 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. - -- [Basic example](#basic-example-2) -- [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-1) -- [Rendering additional content](#rendering-additional-content-1) -- [Rendering a different element for a component](#rendering-a-different-element-for-a-component-1) -- [Component API](#component-api-2) - -### 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 ( - - {selectedPerson.name} - - {people.map(person => ( - - {person.name} - - ))} - - - ) -} -``` - -### 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 ( - - {selectedPerson.name} - - {people.map(person => ( - /* Use the `active` state to conditionally style the active option. */ - /* Use the `selected` state to conditionally style the selected option. */ - - {({ active, selected }) => ( -
  • - {selected && } - {person.name} -
  • - )} -
    - ))} -
    -
    - ) -} -``` - -### 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 ( - - Assignee: - {selectedPerson.name} - - {people.map(person => ( - - {person.name} - - ))} - - - ) -} -``` - -### 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 ( - - {selectedPerson.name} - - {/* By default, this will automatically show/hide when the Listbox.Button is pressed. */} - - {people.map(person => ( - - {person.name} - - ))} - - - ) -} -``` - -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 ( - - {({ open }) => ( - <> - {selectedPerson.name} - {open && ( -
    - {/* Using `static`, `Listbox.Options` is always rendered and ignores the `open` state. */} - - {people.map(person => ( - - {person.name} - - ))} - -
    - )} - - )} -
    - ) -} -``` - -### 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 ( - - {selectedPerson.name} - - {people.map(person => ( - /* Disabled options will be skipped by keyboard navigation. */ - - {person.name} - - ))} - - - ) -} -``` - -### 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 ``, 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 ( - - {({ open }) => ( - <> - {selectedPerson.name} - {/* Use the Transition + open render prop argument to add transitions. */} - - - {people.map(person => ( - - {person.name} - - ))} - - - - )} - - ) -} -``` - -### 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 ( - - {selectedPerson.name} - - {people.map(person => ( - - {person.name} - - ))} - - - ) -} -``` - -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 ( - - {selectedPerson.name} - - {people.map(person => ( - - {person.name} - - ))} - - - ) -} -``` - -### 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 ( - - {selectedPerson.name} - - {people.map(person => ( - - {person.name} - - ))} - - - ) -} -``` - -##### 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 - - {({ open }) => ( - <> - More options - - - )} - -``` - -##### 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 -Enable notifications -``` - -##### 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 - - {/* ... */}> - {/* ... */}> - -``` - -##### 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 -Option A -``` - -##### 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. | - -## 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. - -- [Basic example](#basic-example-3) -- [Using a custom label](#using-a-custom-label-1) -- [Component API](#component-api-3) - -### 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 ( - - Enable notifications - - - ) -} -``` - -### 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 ( - - Enable notifications - - - - - ) -} -``` - -### Component API - -#### Switch - -```jsx - - Enable notifications - {/* ... */} - -``` - -##### 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 - - Enable notifications - - {/* ... */} - - -``` - -##### Props - -| Prop | Type | Default | Description | -| :--- | :------------------ | :------ | :------------------------------------------------------------ | -| `as` | String \| Component | `label` | The element or component the `Switch.Label` should render as. | - -#### Switch.Description - -```jsx - - Enable notifications - - {/* ... */} - - -``` - -##### Props - -| Prop | Type | Default | Description | -| :--- | :------------------ | :------ | :------------------------------------------------------------------ | -| `as` | String \| Component | `label` | The element or component the `Switch.Description` should render as. | - -#### Switch.Group - -```jsx - - Enable notifications - - {/* ... */} - - -``` - -##### Props - -| Prop | Type | Default | Description | -| :--- | :------------------ | :-------------------------------------- | :------------------------------------------------------------ | -| `as` | String \| Component | `React.Fragment` _(no wrapper element)_ | The element or component the `Switch.Group` should render as. | - -## Disclosure - -A component for showing/hiding content. - -- [Basic example](#basic-example-4) -- [Component API](#component-api-4) - -### Basic example - -```jsx - - Toggle - Contents - -``` - -### Component API - -#### Disclosure - -```jsx - - Toggle - Contents - -``` - -##### 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. | - ---- - -## FocusTrap - -- [Basic example](#basic-example-5) -- [Component API](#component-api-5) - -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. - -### Basic example - -```jsx - -
    - - - -
    -
    -``` - -### Component API - -#### FocusTrap - -```jsx - -
    - - - -
    -
    -``` - -##### 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. | - ---- - -## Portal - -- [Basic example](#basic-example-6) -- [Component API](#component-api-6) - -A component for rendering your contents within a Portal (at the end of `document.body`). - -### Basic example - -```jsx - -

    This will be rendered inside a Portal, at the end of `document.body`

    -
    -``` - -### Component API - -#### Portal - -```jsx - -

    This will be rendered inside a Portal, at the end of `document.body`

    -
    -``` - -##### 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 - ---- - -## Dialog - -- [Basic example](#basic-example-7) -- [Component API](#component-api-7) - -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) -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` - -### Basic example - -```jsx -import { useState } from 'react' -import { Dialog } from '@headlessui/react' - -function Example() { - let [isOpen, setIsOpen] = useState(true) - - return ( - - - - Deactivate account - This will permanently deactivate your account - -

    - Are you sure you want to deactivate your account? All of your data will be permanently - removed. This action cannot be undone. -

    - - - -
    - ) -} -``` - -### Component API - -#### Dialog - -```jsx -import { useState } from 'react' -import { Dialog } from '@headlessui/react' - -function Example() { - let [isOpen, setIsOpen] = useState(true) - - return ( - - - - Deactivate account - This will permanently deactivate your account - -

    - Are you sure you want to deactivate your account? All of your data will be permanently - removed. This action cannot be undone. -

    - - - -
    - ) -} -``` - -##### 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. | - ---- - -## Popover - -- [Basic example](#basic-example-8) -- [Component API](#component-api-8) - -This component can be used for navigation menu's, mobile menu's and flyout menu's. - -### Basic example - -```jsx - - - Solutions - - Analytics - Engagement - Security - Integrations - Automations - - - - Pricing - Docs - - - More - - Help Center - Guides - Events - Security - - - -``` - -### Component API - -#### Popover - -```jsx - - - Solutions - - Analytics - Engagement - Security - Integrations - Automations - - - - Pricing - Docs - - - More - - Help Center - Guides - Events - Security - - - -``` - -##### 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 diff --git a/packages/@headlessui-react/pages/dialog/dialog-with-alert.tsx b/packages/@headlessui-react/pages/dialog/dialog-with-alert.tsx new file mode 100644 index 0000000..f76678a --- /dev/null +++ b/packages/@headlessui-react/pages/dialog/dialog-with-alert.tsx @@ -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 ( + <> + + + + +
    +
    + + +
    +
    +
    + + + {/* This element is to trick the browser into centering the modal contents. */} + +
    +
    +
    +
    + {/* Heroicon name: exclamation */} + +
    +
    + + Deactivate account + +
    +

    + Are you sure you want to deactivate your account? All of your data will + be permanently removed. This action cannot be undone. +

    + {deleted && ( + +
    + I am now deleted! +
    +
    + )} +
    +
    +
    +
    +
    +
    + + +
    +
    +
    +
    +
    +
    +
    + + ) +} diff --git a/packages/@headlessui-react/pages/radio-group/radio-group.tsx b/packages/@headlessui-react/pages/radio-group/radio-group.tsx new file mode 100644 index 0000000..56e2772 --- /dev/null +++ b/packages/@headlessui-react/pages/radio-group/radio-group.tsx @@ -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 ( +
    + Link before + +
    + +

    Privacy setting

    +
    + +
    + {access.map(({ id, name, description }, i) => { + return ( + + 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 }) => ( +
    +
    + + {name} + + + {description} + +
    +
    + {checked && ( + + + + )} +
    +
    + )} +
    + ) + })} +
    +
    +
    + Link after +
    + ) +} diff --git a/packages/@headlessui-react/src/components/alert/README.md b/packages/@headlessui-react/src/components/alert/README.md new file mode 100644 index 0000000..487a979 --- /dev/null +++ b/packages/@headlessui-react/src/components/alert/README.md @@ -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 +Notifications have been enabled +``` + +### Component API + +#### Alert + +```jsx +Notifications have been enabled +``` + +##### 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 diff --git a/packages/@headlessui-react/src/components/alert/alert.test.tsx b/packages/@headlessui-react/src/components/alert/alert.test.tsx new file mode 100644 index 0000000..7ed4033 --- /dev/null +++ b/packages/@headlessui-react/src/components/alert/alert.test.tsx @@ -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(This is an alert) + + expect(getByText('This is an alert')).toHaveAttribute('role', 'status') + }) + + it('should be possible to render an Alert using a render prop', () => { + render({() => 'This is an 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(This is a polite message) + + 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(This is a assertive message) + + expect(getByText('This is a assertive message')).toHaveAttribute('role', 'alert') + }) +}) diff --git a/packages/@headlessui-react/src/components/alert/alert.tsx b/packages/@headlessui-react/src/components/alert/alert.tsx new file mode 100644 index 0000000..4f21576 --- /dev/null +++ b/packages/@headlessui-react/src/components/alert/alert.tsx @@ -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( + props: Props & { + importance?: Importance + } +) { + let { importance = 'polite', ...passThroughProps } = props + let propsWeControl = match(importance, { + polite: () => ({ role: 'status' }), + assertive: () => ({ role: 'alert' }), + }) + + let bag = useMemo(() => ({ importance }), [importance]) + + return render({ ...passThroughProps, ...propsWeControl }, bag, DEFAULT_ALERT_TAG) +} diff --git a/packages/@headlessui-react/src/components/description/description.test.tsx b/packages/@headlessui-react/src/components/description/description.test.tsx new file mode 100644 index 0000000..8fdf2e3 --- /dev/null +++ b/packages/@headlessui-react/src/components/description/description.test.tsx @@ -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 ( + +
    {props.children}
    +
    + ) + } + + function Example() { + return No description + } + + let { container } = render() + expect(container.firstChild).toMatchInlineSnapshot(` +
    + No description +
    + `) +}) + +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 ( + +
    {props.children}
    +
    + ) + } + + function Example() { + return ( + + I am a description + Contents + + ) + } + + let { container } = render() + expect(container.firstChild).toMatchInlineSnapshot(` +
    +

    + I am a description +

    + + Contents + +
    + `) +}) + +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 ( + +
    {props.children}
    +
    + ) + } + + function Example() { + return ( + + I am a description + Contents + I am also a description + + ) + } + + let { container } = render() + expect(container.firstChild).toMatchInlineSnapshot(` +
    +

    + I am a description +

    + + Contents + +

    + I am also a description +

    +
    + `) +}) diff --git a/packages/@headlessui-react/src/components/description/description.tsx b/packages/@headlessui-react/src/components/description/description.tsx new file mode 100644 index 0000000..8cf2b68 --- /dev/null +++ b/packages/@headlessui-react/src/components/description/description.tsx @@ -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([]) + + 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 ( + + {props.children} + + ) + } + }, [setDescriptionIds]), + ] +} + +// --- + +let DEFAULT_DESCRIPTION_TAG = 'p' as const +interface DescriptionRenderPropArg {} +type DescriptionPropsWeControl = 'id' + +export function Description( + props: Props +) { + let { register } = useDescriptionContext() + let id = `headlessui-description-${useId()}` + + useIsoMorphicEffect(() => register(id), [id, register]) + + let passThroughProps = props + let propsWeControl = { id } + let bag = useMemo(() => ({}), []) + + return render({ ...passThroughProps, ...propsWeControl }, bag, DEFAULT_DESCRIPTION_TAG) +} diff --git a/packages/@headlessui-react/src/components/dialog/README.md b/packages/@headlessui-react/src/components/dialog/README.md new file mode 100644 index 0000000..f23dee0 --- /dev/null +++ b/packages/@headlessui-react/src/components/dialog/README.md @@ -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 ( + + + + Deactivate account + This will permanently deactivate your account + +

    + Are you sure you want to deactivate your account? All of your data will be permanently + removed. This action cannot be undone. +

    + + + +
    + ) +} +``` + +### Component API + +#### Dialog + +```jsx +import { useState } from 'react' +import { Dialog } from '@headlessui/react' + +function Example() { + let [isOpen, setIsOpen] = useState(true) + + return ( + + + + Deactivate account + This will permanently deactivate your account + +

    + Are you sure you want to deactivate your account? All of your data will be permanently + removed. This action cannot be undone. +

    + + + +
    + ) +} +``` + +##### 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. | diff --git a/packages/@headlessui-react/src/components/dialog/dialog.tsx b/packages/@headlessui-react/src/components/dialog/dialog.tsx index 1be5b71..502b61e 100644 --- a/packages/@headlessui-react/src/components/dialog/dialog.tsx +++ b/packages/@headlessui-react/src/components/dialog/dialog.tsx @@ -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< }) }} > - - - {render( - { ...passthroughProps, ...propsWeControl }, - propsBag, - DEFAULT_DIALOG_TAG, - DialogRenderFeatures, - dialogState === DialogStates.Open - )} - - + + + + + + {render( + { ...passthroughProps, ...propsWeControl }, + propsBag, + DEFAULT_DIALOG_TAG, + DialogRenderFeatures, + dialogState === DialogStates.Open + )} + + + + + ) }) diff --git a/packages/@headlessui-react/src/components/disclosure/README.md b/packages/@headlessui-react/src/components/disclosure/README.md new file mode 100644 index 0000000..a7404ee --- /dev/null +++ b/packages/@headlessui-react/src/components/disclosure/README.md @@ -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 + + Toggle + Contents + +``` + +### Component API + +#### Disclosure + +```jsx + + Toggle + Contents + +``` + +##### 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. | diff --git a/packages/@headlessui-react/src/components/disclosure/disclosure.tsx b/packages/@headlessui-react/src/components/disclosure/disclosure.tsx index ef753d5..a479ce3 100644 --- a/packages/@headlessui-react/src/components/disclosure/disclosure.tsx +++ b/packages/@headlessui-react/src/components/disclosure/disclosure.tsx @@ -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' diff --git a/packages/@headlessui-react/src/components/focus-trap/README.md b/packages/@headlessui-react/src/components/focus-trap/README.md new file mode 100644 index 0000000..718c223 --- /dev/null +++ b/packages/@headlessui-react/src/components/focus-trap/README.md @@ -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 + +
    + + + +
    +
    +``` + +### Component API + +#### FocusTrap + +```jsx + +
    + + + +
    +
    +``` + +##### 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. | diff --git a/packages/@headlessui-react/src/components/keyboard.ts b/packages/@headlessui-react/src/components/keyboard.ts index 41d6fee..b0f02ed 100644 --- a/packages/@headlessui-react/src/components/keyboard.ts +++ b/packages/@headlessui-react/src/components/keyboard.ts @@ -6,7 +6,9 @@ export enum Keys { Escape = 'Escape', Backspace = 'Backspace', + ArrowLeft = 'ArrowLeft', ArrowUp = 'ArrowUp', + ArrowRight = 'ArrowRight', ArrowDown = 'ArrowDown', Home = 'Home', diff --git a/packages/@headlessui-react/src/components/label/label.test.tsx b/packages/@headlessui-react/src/components/label/label.test.tsx new file mode 100644 index 0000000..bbc654b --- /dev/null +++ b/packages/@headlessui-react/src/components/label/label.test.tsx @@ -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 ( + +
    {props.children}
    +
    + ) + } + + function Example() { + return No label + } + + let { container } = render() + expect(container.firstChild).toMatchInlineSnapshot(` +
    + No label +
    + `) +}) + +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 ( + +
    {props.children}
    +
    + ) + } + + function Example() { + return ( + + + Contents + + ) + } + + let { container } = render() + expect(container.firstChild).toMatchInlineSnapshot(` +
    + + + Contents + +
    + `) +}) + +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 ( + +
    {props.children}
    +
    + ) + } + + function Example() { + return ( + + + Contents + + + ) + } + + let { container } = render() + expect(container.firstChild).toMatchInlineSnapshot(` +
    + + + Contents + + +
    + `) +}) diff --git a/packages/@headlessui-react/src/components/label/label.tsx b/packages/@headlessui-react/src/components/label/label.tsx new file mode 100644 index 0000000..7ec2f3d --- /dev/null +++ b/packages/@headlessui-react/src/components/label/label.tsx @@ -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([]) + + 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 {props.children} + } + }, [setLabelIds]), + ] +} + +// --- + +let DEFAULT_LABEL_TAG = 'label' as const +interface LabelRenderPropArg {} +type LabelPropsWeControl = 'id' + +export function Label( + props: Props +) { + let { register } = useLabelContext() + let id = `headlessui-label-${useId()}` + + useIsoMorphicEffect(() => register(id), [id, register]) + + let passThroughProps = props + let propsWeControl = { id } + let bag = useMemo(() => ({}), []) + + return render({ ...passThroughProps, ...propsWeControl }, bag, DEFAULT_LABEL_TAG) +} diff --git a/packages/@headlessui-react/src/components/listbox/README.md b/packages/@headlessui-react/src/components/listbox/README.md new file mode 100644 index 0000000..d212ba3 --- /dev/null +++ b/packages/@headlessui-react/src/components/listbox/README.md @@ -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 ( + + {selectedPerson.name} + + {people.map(person => ( + + {person.name} + + ))} + + + ) +} +``` + +### 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 ( + + {selectedPerson.name} + + {people.map(person => ( + /* Use the `active` state to conditionally style the active option. */ + /* Use the `selected` state to conditionally style the selected option. */ + + {({ active, selected }) => ( +
  • + {selected && } + {person.name} +
  • + )} +
    + ))} +
    +
    + ) +} +``` + +### 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 ( + + Assignee: + {selectedPerson.name} + + {people.map(person => ( + + {person.name} + + ))} + + + ) +} +``` + +### 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 ( + + {selectedPerson.name} + + {/* By default, this will automatically show/hide when the Listbox.Button is pressed. */} + + {people.map(person => ( + + {person.name} + + ))} + + + ) +} +``` + +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 ( + + {({ open }) => ( + <> + {selectedPerson.name} + {open && ( +
    + {/* Using `static`, `Listbox.Options` is always rendered and ignores the `open` state. */} + + {people.map(person => ( + + {person.name} + + ))} + +
    + )} + + )} +
    + ) +} +``` + +### 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 ( + + {selectedPerson.name} + + {people.map(person => ( + /* Disabled options will be skipped by keyboard navigation. */ + + {person.name} + + ))} + + + ) +} +``` + +### 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 ``, 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 ( + + {({ open }) => ( + <> + {selectedPerson.name} + {/* Use the Transition + open render prop argument to add transitions. */} + + + {people.map(person => ( + + {person.name} + + ))} + + + + )} + + ) +} +``` + +### 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 ( + + {selectedPerson.name} + + {people.map(person => ( + + {person.name} + + ))} + + + ) +} +``` + +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 ( + + {selectedPerson.name} + + {people.map(person => ( + + {person.name} + + ))} + + + ) +} +``` + +### 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 ( + + {selectedPerson.name} + + {people.map(person => ( + + {person.name} + + ))} + + + ) +} +``` + +##### 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 + + {({ open }) => ( + <> + More options + + + )} + +``` + +##### 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 +Enable notifications +``` + +##### 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 + + {/* ... */}> + {/* ... */}> + +``` + +##### 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 +Option A +``` + +##### 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. | diff --git a/packages/@headlessui-react/src/components/listbox/listbox.tsx b/packages/@headlessui-react/src/components/listbox/listbox.tsx index 5dae4bc..027d347 100644 --- a/packages/@headlessui-react/src/components/listbox/listbox.tsx +++ b/packages/@headlessui-react/src/components/listbox/listbox.tsx @@ -1,4 +1,5 @@ import React, { + Fragment, createContext, createRef, useCallback, @@ -7,7 +8,6 @@ import React, { useMemo, useReducer, useRef, - Fragment, // Types Dispatch, diff --git a/packages/@headlessui-react/src/components/menu/README.md b/packages/@headlessui-react/src/components/menu/README.md new file mode 100644 index 0000000..a28a032 --- /dev/null +++ b/packages/@headlessui-react/src/components/menu/README.md @@ -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 ( + + More + + + {({ active }) => ( + + Account settings + + )} + + + {({ active }) => ( + + Documentation + + )} + + + Invite a friend (coming soon!) + + + + ) +} +``` + +### 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 ( + + More + + {/* Use the `active` state to conditionally style the active item. */} + + {({ active }) => ( + + Account settings + + )} + + {/* ... */} + + + ) +} +``` + +### 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 ( + + More + + {/* By default, this will automatically show/hide when the Menu.Button is pressed. */} + + {/* ... */} + {/* ... */} + + + ) +} +``` + +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 ( + + {({ open }) => ( + More + {open && ( +
    + {/* Using `static`, `Menu.Items` is always rendered and ignores the `open` state. */} + + {/* ... */} + {/* ... */} + +
    + )} + )} +
    + ) +} +``` + +### 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 ( + + More + + {/* ... */} + + {/* This item will be skipped by keyboard navigation. */} + + Invite a friend (coming soon!) + + + {/* ... */} + + + ) +} +``` + +### 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 ``, and the transition will be applied automatically. + +```jsx +import { Menu, Transition } from '@headlessui/react' + +function MyDropdown() { + return ( + + {({ open }) => ( + <> + More + + {/* Use the Transition + open render prop argument to add transitions. */} + + + {/* ... */} + {/* ... */} + + + + )} + + ) +} +``` + +### 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 ( + + More + +
    +

    Signed in as

    +

    tom@example.com

    +
    + + {({ active }) => ( + + Account settings + + )} + + + {/* ... */} +
    +
    + ) +} +``` + +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 */} + + More + {/* Render a `ul` instead of a `div` */} + + {/* Render an `li` instead of no wrapper element */} + + {({ active }) => ( + + Account settings + + )} + + + {/* ... */} + + + ) +} +``` + +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 ( + + {/* Render no wrapper, instead pass in a button manually. */} + + + + + + {({ active }) => ( + + Account settings + + )} + + {/* ... */} + + + ) +} +``` + +### Component API + +#### Menu + +```jsx + + More + + {/* ... */} + {/* ... */} + + +``` + +##### 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 + + {({ open }) => ( + <> + More options + + + )} + +``` + +##### 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 + + {/* ... */}> + {/* ... */}> + +``` + +##### 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 + + {({ active }) => ( + + Account settings + + )} + +``` + +##### 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. | diff --git a/packages/@headlessui-react/src/components/menu/menu.tsx b/packages/@headlessui-react/src/components/menu/menu.tsx index f7bca3a..d920733 100644 --- a/packages/@headlessui-react/src/components/menu/menu.tsx +++ b/packages/@headlessui-react/src/components/menu/menu.tsx @@ -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, diff --git a/packages/@headlessui-react/src/components/popover/README.md b/packages/@headlessui-react/src/components/popover/README.md new file mode 100644 index 0000000..90e8f89 --- /dev/null +++ b/packages/@headlessui-react/src/components/popover/README.md @@ -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 + + + Solutions + + Analytics + Engagement + Security + Integrations + Automations + + + + Pricing + Docs + + + More + + Help Center + Guides + Events + Security + + + +``` + +### Component API + +#### Popover + +```jsx + + + Solutions + + Analytics + Engagement + Security + Integrations + Automations + + + + Pricing + Docs + + + More + + Help Center + Guides + Events + Security + + + +``` + +##### 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 diff --git a/packages/@headlessui-react/src/components/popover/popover.tsx b/packages/@headlessui-react/src/components/popover/popover.tsx index 33afb49..de7e6b2 100644 --- a/packages/@headlessui-react/src/components/popover/popover.tsx +++ b/packages/@headlessui-react/src/components/popover/popover.tsx @@ -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( - props: Props +export function Popover( + props: Props ) { let buttonId = `headlessui-popover-button-${useId()}` let panelId = `headlessui-popover-panel-${useId()}` @@ -228,7 +228,7 @@ export function Popover( return ( - {render(props, propsBag, DEFAULT_FLYOUT_TAG)} + {render(props, propsBag, DEFAULT_POPOVER_TAG)} ) } diff --git a/packages/@headlessui-react/src/components/portal/README.md b/packages/@headlessui-react/src/components/portal/README.md new file mode 100644 index 0000000..12f7af2 --- /dev/null +++ b/packages/@headlessui-react/src/components/portal/README.md @@ -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 + +

    This will be rendered inside a Portal, at the end of `document.body`

    +
    +``` + +### Component API + +#### Portal + +```jsx + +

    This will be rendered inside a Portal, at the end of `document.body`

    +
    +``` + +##### 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 diff --git a/packages/@headlessui-react/src/components/portal/portal.test.tsx b/packages/@headlessui-react/src/components/portal/portal.test.tsx index db4c9c6..f80a1a2 100644 --- a/packages/@headlessui-react/src/components/portal/portal.test.tsx +++ b/packages/@headlessui-react/src/components/portal/portal.test.tsx @@ -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 ( +
    + + + +
    + B +
    + Next to A +
    + + I am in the portal root +
    + ) + } + + render() + + expect(document.body.innerHTML).toMatchInlineSnapshot( + `"
    B
    I am in the portal root
    "` + ) +}) diff --git a/packages/@headlessui-react/src/components/portal/portal.tsx b/packages/@headlessui-react/src/components/portal/portal.tsx index 8b4aa96..ccdb97f 100644 --- a/packages/@headlessui-react/src/components/portal/portal.tsx +++ b/packages/@headlessui-react/src/components/portal/portal.tsx @@ -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( props: Props ) { - let [target, setTarget] = useState(resolvePortalRoot) + let passthroughProps = props + let target = usePortalTarget() let [element] = useState(() => typeof window === 'undefined' ? null : document.createElement('div') ) @@ -39,7 +61,7 @@ export function Portal( useElemenStack(element) useIsoMorphicEffect(() => { - if (!target) return setTarget(resolvePortalRoot()) + if (!target) return if (!element) return target.appendChild(element) @@ -49,13 +71,43 @@ export function Portal( 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 ( - {!target || !element ? null : createPortal(render(props, {}, DEFAULT_PORTAL_TAG), element)} + {!target || !element + ? null + : createPortal(render(passthroughProps, {}, DEFAULT_PORTAL_TAG), element)} ) } + +// --- + +let DEFAULT_GROUP_TAG = Fragment +interface GroupRenderPropArg {} + +let PortalGroupContext = createContext | null>(null) + +function Group( + props: Props & { + target: MutableRefObject + } +) { + let { target, ...passthroughProps } = props + + return ( + + {render(passthroughProps, {}, DEFAULT_GROUP_TAG)} + + ) +} + +// --- + +Portal.Group = Group diff --git a/packages/@headlessui-react/src/components/radio-group/README.md b/packages/@headlessui-react/src/components/radio-group/README.md new file mode 100644 index 0000000..f9dee11 --- /dev/null +++ b/packages/@headlessui-react/src/components/radio-group/README.md @@ -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 ( + + Pizza Delivery + Pickup + Home delivery + Dine in + + ) +} +``` + +### Component API + +#### RadioGroup + +```jsx +let [deliveryMethod, setDeliveryMethod] = useState(undefined) + + + Pickup + Home delivery + Dine in + +``` + +##### 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) + + + Pickup + Home delivery + Dine in + +``` + +##### 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. | diff --git a/packages/@headlessui-react/src/components/radio-group/radio-group.test.tsx b/packages/@headlessui-react/src/components/radio-group/radio-group.test.tsx new file mode 100644 index 0000000..5f2030b --- /dev/null +++ b/packages/@headlessui-react/src/components/radio-group/radio-group.test.tsx @@ -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 ', + suppressConsoleLogs((name, Component) => { + expect(() => render(createElement(Component))).toThrowError( + `<${name} /> is missing a parent component.` + ) + }) + ) + + it( + 'should be possible to render a RadioGroup without crashing', + suppressConsoleLogs(async () => { + render( + + Pizza Delivery + Pickup + Home delivery + Dine in + + ) + + assertRadioGroupLabel({ textContent: 'Pizza Delivery' }) + }) + ) + + it('should be possible to render a RadioGroup without options and without crashing', () => { + render() + }) +}) + +describe('Rendering', () => { + it('should be possible to render a RadioGroup, where the first element is tabbable', async () => { + render( + + Pizza Delivery + Pickup + Home delivery + Dine in + + ) + + 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( + + Pizza Delivery + Pickup + Home delivery + Dine in + + ) + + 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 ( + <> + + + Pizza Delivery + {showFirst && Pickup} + Home delivery + Dine in + + + ) + } + + render() + + 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( + + Pizza Delivery + Pickup + Home delivery + Dine in + + ) + + await press(Keys.Tab) + + assertActiveElement(getByText('Pickup')) + }) + + it('should not change the selected element on focus', async () => { + let changeFn = jest.fn() + render( + + Pizza Delivery + Pickup + Home delivery + Dine in + + ) + + await press(Keys.Tab) + + assertActiveElement(getByText('Pickup')) + + expect(changeFn).toHaveBeenCalledTimes(0) + }) + + it('should be possible to tab to the active item', async () => { + render( + + Pizza Delivery + Pickup + Home delivery + Dine in + + ) + + 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( + + Pizza Delivery + Pickup + Home delivery + Dine in + + ) + + 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( + <> + + + Pizza Delivery + Pickup + Home delivery + Dine in + + + + ) + + 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( + <> + + + Pizza Delivery + Pickup + Home delivery + Dine in + + + + ) + + 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( + <> + + Pizza Delivery + Pickup + Home delivery + Dine in + + + + ) + + 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( + <> + + Pizza Delivery + Pickup + Home delivery + Dine in + + + + ) + + 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( + <> + + Pizza Delivery + Pickup + Home delivery + Dine in + + + + ) + + 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( + <> + + Pizza Delivery + Pickup + Home delivery + Dine in + + + + ) + + 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( + <> + + + Pizza Delivery + Pickup + Home delivery + Dine in + + + + ) + + 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( + <> + + + Pizza Delivery + Pickup + Home delivery + Dine in + + + + ) + + 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( + <> + + + Pizza Delivery + Pickup + Home delivery + Dine in + + + + ) + + // 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( + <> + + + Pizza Delivery + Pickup + Home delivery + Dine in + + + + ) + + // 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( + <> + + + Pizza Delivery + Pickup + Home delivery + Dine in + + + + ) + + // 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( + <> + + + Pizza Delivery + Pickup + Home delivery + Dine in + + + + ) + + // 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( + <> + + + Pizza Delivery + Pickup + Home delivery + Dine in + + + + ) + + // 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 ( + <> + + { + setValue(v) + changeFn(v) + }} + > + Pizza Delivery + Pickup + Home delivery + Dine in + + + + ) + } + render() + + // 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( + <> + + + Pizza Delivery + Pickup + Home delivery + Dine in + + + + ) + + 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 ( + <> + + { + setValue(v) + changeFn(v) + }} + > + Pizza Delivery + Pickup + Home delivery + Dine in + + + + ) + } + render() + + 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) + }) +}) diff --git a/packages/@headlessui-react/src/components/radio-group/radio-group.tsx b/packages/@headlessui-react/src/components/radio-group/radio-group.tsx new file mode 100644 index 0000000..a36fd66 --- /dev/null +++ b/packages/@headlessui-react/src/components/radio-group/radio-group.tsx @@ -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 + 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 + ) => 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] | 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(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(() => ({}), []) + + return ( + + + + {render({ ...passThroughProps, ...propsWeControl }, bag, DEFAULT_RADIO_GROUP_TAG)} + + + + ) +} + +// --- + +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[0]['value'] +>( + props: Props & { + value: TType + } +) { + let optionRef = useRef(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(() => ({ checked, active: hasFlag(OptionState.Active) }), [ + checked, + hasFlag, + ]) + + return ( + + + {render({ ...passThroughProps, ...propsWeControl }, bag, DEFAULT_OPTION_TAG)} + + + ) +} + +// --- + +RadioGroup.Option = Option +RadioGroup.Label = Label +RadioGroup.Description = Description diff --git a/packages/@headlessui-react/src/components/switch/README.md b/packages/@headlessui-react/src/components/switch/README.md new file mode 100644 index 0000000..2df6a1f --- /dev/null +++ b/packages/@headlessui-react/src/components/switch/README.md @@ -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 ( + + Enable notifications + + + ) +} +``` + +### 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 ( + + Enable notifications + + + + + ) +} +``` + +### Component API + +#### Switch + +```jsx + + Enable notifications + {/* ... */} + +``` + +##### 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 + + Enable notifications + + {/* ... */} + + +``` + +##### Props + +| Prop | Type | Default | Description | +| :--- | :------------------ | :------ | :------------------------------------------------------------ | +| `as` | String \| Component | `label` | The element or component the `Switch.Label` should render as. | + +#### Switch.Description + +```jsx + + Enable notifications + + {/* ... */} + + +``` + +##### Props + +| Prop | Type | Default | Description | +| :--- | :------------------ | :------ | :------------------------------------------------------------------ | +| `as` | String \| Component | `label` | The element or component the `Switch.Description` should render as. | + +#### Switch.Group + +```jsx + + Enable notifications + + {/* ... */} + + +``` + +##### Props + +| Prop | Type | Default | Description | +| :--- | :------------------ | :-------------------------------------- | :------------------------------------------------------------ | +| `as` | String \| Component | `React.Fragment` _(no wrapper element)_ | The element or component the `Switch.Group` should render as. | diff --git a/packages/@headlessui-react/src/components/switch/switch.tsx b/packages/@headlessui-react/src/components/switch/switch.tsx index cc952c0..d8a1ffa 100644 --- a/packages/@headlessui-react/src/components/switch/switch.tsx +++ b/packages/@headlessui-react/src/components/switch/switch.tsx @@ -1,10 +1,10 @@ import React, { + Fragment, createContext, useCallback, useContext, useMemo, useState, - Fragment, // Types ElementType, diff --git a/packages/@headlessui-react/src/components/transitions/README.md b/packages/@headlessui-react/src/components/transitions/README.md new file mode 100644 index 0000000..16e3213 --- /dev/null +++ b/packages/@headlessui-react/src/components/transitions/README.md @@ -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 ( + <> + + + I will fade in and out + + + ) +} +``` + +### Showing and hiding content + +Wrap the content that should be conditionally rendered in a `` 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 ( + <> + + + I will fade in and out + + + ) +} +``` + +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 ( + <> + + + I will fade in and out + + + ) +} +``` + +### 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 ( + <> + + + I will fade in and out + + + ) +} +``` + +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 ( + + {/* Background overlay */} + + {/* ... */} + + + {/* Sliding sidebar */} + + {/* ... */} + + + ) +} +``` + +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 ( + + {/* Your content goes here*/} + + ) +} +``` + +### Component API + +#### Transition + +```jsx + + {/* Your content goes here*/} + +``` + +##### 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 + + + {/* ... */} + + {/* ... */} + +``` + +##### 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 diff --git a/packages/@headlessui-react/src/components/transitions/transition.tsx b/packages/@headlessui-react/src/components/transitions/transition.tsx index a39b481..6b14a7e 100644 --- a/packages/@headlessui-react/src/components/transitions/transition.tsx +++ b/packages/@headlessui-react/src/components/transitions/transition.tsx @@ -1,12 +1,12 @@ import React, { - useMemo, - createContext, - useContext, - useRef, - useEffect, - useCallback, - useState, Fragment, + createContext, + useCallback, + useContext, + useEffect, + useMemo, + useRef, + useState, // Types ElementType, diff --git a/packages/@headlessui-react/src/hooks/use-flags.ts b/packages/@headlessui-react/src/hooks/use-flags.ts new file mode 100644 index 0000000..1cb5448 --- /dev/null +++ b/packages/@headlessui-react/src/hooks/use-flags.ts @@ -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 } +} diff --git a/packages/@headlessui-react/src/index.test.ts b/packages/@headlessui-react/src/index.test.ts index 9f4d602..689321e 100644 --- a/packages/@headlessui-react/src/index.test.ts +++ b/packages/@headlessui-react/src/index.test.ts @@ -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', ]) diff --git a/packages/@headlessui-react/src/index.ts b/packages/@headlessui-react/src/index.ts index 7bca534..10f0a73 100644 --- a/packages/@headlessui-react/src/index.ts +++ b/packages/@headlessui-react/src/index.ts @@ -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' diff --git a/packages/@headlessui-react/src/internal/portal-force-root.tsx b/packages/@headlessui-react/src/internal/portal-force-root.tsx new file mode 100644 index 0000000..d688f28 --- /dev/null +++ b/packages/@headlessui-react/src/internal/portal-force-root.tsx @@ -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 ( + + {props.children} + + ) +} diff --git a/packages/@headlessui-react/src/test-utils/accessibility-assertions.ts b/packages/@headlessui-react/src/test-utils/accessibility-assertions.ts index 0e5673d..e807cf7 100644 --- a/packages/@headlessui-react/src/test-utils/accessibility-assertions.ts +++ b/packages/@headlessui-react/src/test-utils/accessibility-assertions.ts @@ -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 + 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) { diff --git a/packages/@headlessui-react/src/test-utils/interactions.ts b/packages/@headlessui-react/src/test-utils/interactions.ts index 2d839ce..d78f9b6 100644 --- a/packages/@headlessui-react/src/test-utils/interactions.ts +++ b/packages/@headlessui-react/src/test-utils/interactions.ts @@ -14,7 +14,9 @@ export let Keys: Record> = { 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 }, diff --git a/packages/@headlessui-vue/README.md b/packages/@headlessui-vue/README.md index 46fe2dc..632e1a1 100644 --- a/packages/@headlessui-vue/README.md +++ b/packages/@headlessui-vue/README.md @@ -29,9 +29,9 @@ yarn add @headlessui/vue _This project is still in early development. New components will be added regularly over the coming months._ -- [Menu Button (Dropdown)](#menu-button-dropdown) -- [Listbox (Select)](#listbox-select) -- [Switch (Toggle)](#switch-toggle) +- [Menu Button (Dropdown)](./src/components/menu/README.md) +- [Listbox (Select)](./src/components/listbox/README.md) +- [Switch (Toggle)](./src/components/switch/README.md) ### Roadmap @@ -48,1202 +48,3 @@ This includes things like: ...and more in the future. We'll be continuing to develop new components on an on-going basis, with a goal of reaching a pretty fleshed out v1.0 by the end of the year. - ---- - -## Menu Button (Dropdown) - -[View live demo on CodeSandbox](https://codesandbox.io/s/headlessuivue-menu-example-forked-24f9d?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. - -- [Basic example](#basic-example) -- [Styling](#styling) -- [Transitions](#transitions) -- [Component API](#component-api) - -### 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 - - - -``` - -### 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 - -``` - -### 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 - -``` - -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 - -``` - -### 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 - -``` - -### 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 `` element and the transition will be applied automatically. - -```vue - -``` - -### 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 - -``` - -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 - -``` - -To tell an element to render its children directly with no wrapper element, use `as="template"`. - -```vue - -``` - -### Component API - -#### Menu - -```vue - - More options - - - - - -``` - -##### 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 - - More options - - -``` - -##### 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 - - - - -``` - -##### 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 - - - Settings - - -``` - -##### 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. | - -## Listbox (Select) - -[View live demo on CodeSandbox](https://codesandbox.io/s/headlessuivue-listbox-example-forked-070j0?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. - -- [Basic example](#basic-example-1) -- [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-1) -- [Rendering additional content](#rendering-additional-content-1) -- [Rendering a different element for a component](#rendering-a-different-element-for-a-component-1) -- [Component API](#component-api-1) - -### 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 - - - -``` - -### 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 - - - -``` - -### 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 - - - -``` - -### 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 - - - -``` - -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 - - - -``` - -### 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 - - - -``` - -### 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 `` element and the transition will be applied automatically. - -```vue - - - -``` - -### 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 - - - -``` - -To tell an element to render its children directly with no wrapper element, use `as="template"`. - -```vue - - - -``` - -### Component API - -#### Listbox - -```vue - - - -``` - -##### 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 - - {{ selectedPerson.name }} - - -``` - -##### 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 -Enable notifications -``` - -##### 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 - - - - -``` - -##### 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 -Option A -``` - -##### 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. | - -## 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. - -- [Basic example](#basic-example-2) -- [Using a custom label](#using-a-custom-label-1) -- [Component API](#component-api-2) - -### Basic example - -Switches are built using the `Switch` component. Optionally you can also use the `SwitchGroup`, `SwitchLabel` and `SwitchDescription` components. - -```vue - - - -``` - -### 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 - - - -``` - -### Component API - -#### Switch - -```html - - Enable notifications - - -``` - -##### 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 - - Enable notifications - - - - -``` - -##### Props - -| Prop | Type | Default | Description | -| :--- | :------------------ | :------ | :----------------------------------------------------------- | -| `as` | String \| Component | `label` | The element or component the `SwitchLabel` should render as. | - -#### SwitchDescription - -```html - - Enable notifications - - - - -``` - -##### Props - -| Prop | Type | Default | Description | -| :--- | :------------------ | :------ | :----------------------------------------------------------------- | -| `as` | String \| Component | `p` | The element or component the `SwitchDescription` should render as. | - -#### SwitchGroup - -```html - - Enable notifications - - - - -``` - -##### Props - -| Prop | Type | Default | Description | -| :--- | :------------------ | :-------------------------------- | :----------------------------------------------------------- | -| `as` | String \| Component | `template` _(no wrapper element)_ | The element or component the `SwitchGroup` should render as. | diff --git a/packages/@headlessui-vue/src/components/listbox/README.md b/packages/@headlessui-vue/src/components/listbox/README.md new file mode 100644 index 0000000..03e094c --- /dev/null +++ b/packages/@headlessui-vue/src/components/listbox/README.md @@ -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 + + + +``` + +### 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 + + + +``` + +### 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 + + + +``` + +### 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 + + + +``` + +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 + + + +``` + +### 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 + + + +``` + +### 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 `` element and the transition will be applied automatically. + +```vue + + + +``` + +### 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 + + + +``` + +To tell an element to render its children directly with no wrapper element, use `as="template"`. + +```vue + + + +``` + +### Component API + +#### Listbox + +```vue + + + +``` + +##### 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 + + {{ selectedPerson.name }} + + +``` + +##### 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 +Enable notifications +``` + +##### 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 + + + + +``` + +##### 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 +Option A +``` + +##### 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. | diff --git a/packages/@headlessui-vue/src/components/menu/README.md b/packages/@headlessui-vue/src/components/menu/README.md new file mode 100644 index 0000000..9bf5e02 --- /dev/null +++ b/packages/@headlessui-vue/src/components/menu/README.md @@ -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 + + + +``` + +### 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 + +``` + +### 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 + +``` + +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 + +``` + +### 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 + +``` + +### 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 `` element and the transition will be applied automatically. + +```vue + +``` + +### 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 + +``` + +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 + +``` + +To tell an element to render its children directly with no wrapper element, use `as="template"`. + +```vue + +``` + +### Component API + +#### Menu + +```vue + + More options + + + + + +``` + +##### 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 + + More options + + +``` + +##### 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 + + + + +``` + +##### 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 + + + Settings + + +``` + +##### 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. | diff --git a/packages/@headlessui-vue/src/components/switch/README.md b/packages/@headlessui-vue/src/components/switch/README.md new file mode 100644 index 0000000..f7cdceb --- /dev/null +++ b/packages/@headlessui-vue/src/components/switch/README.md @@ -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 + + + +``` + +### 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 + + + +``` + +### Component API + +#### Switch + +```html + + Enable notifications + + +``` + +##### 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 + + Enable notifications + + + + +``` + +##### Props + +| Prop | Type | Default | Description | +| :--- | :------------------ | :------ | :----------------------------------------------------------- | +| `as` | String \| Component | `label` | The element or component the `SwitchLabel` should render as. | + +#### SwitchDescription + +```html + + Enable notifications + + + + +``` + +##### Props + +| Prop | Type | Default | Description | +| :--- | :------------------ | :------ | :----------------------------------------------------------------- | +| `as` | String \| Component | `p` | The element or component the `SwitchDescription` should render as. | + +#### SwitchGroup + +```html + + Enable notifications + + + + +``` + +##### Props + +| Prop | Type | Default | Description | +| :--- | :------------------ | :-------------------------------- | :----------------------------------------------------------- | +| `as` | String \| Component | `template` _(no wrapper element)_ | The element or component the `SwitchGroup` should render as. |