Files
headlessui/packages/@headlessui-react/src/components/switch/switch.tsx
T
Robin Malfait 648a2843e6 Multiple new components (#220)
* add Disclosure component

* expose the Disclosure component

* add Disclosure example component page

* temporary fix selector because of JSDOM bug

* add useFocusTrap hook

* add FocusTrap component

* expose FocusTrap

* add Dialog component

* add Dialog example component page

* expose Dialog

* random cleanup

* make TypeScript a bit more happy

* add Switch.Description component for React

* add Switch.Description component for Vue

* ensure focus event is triggered on click when element is focusable

* remove Dialog.Button and Dialog.Panel from accessibility assertions

* add Portal component

* expose Portal

* always render Dialog in a Portal

* add useInertOthers hook

This will allow us to mark everything but the current ref as "inert".
This is important for screenreaders, to ensure that screenreaders and
assistive technology can't interact with other content but the current
ref.

This implementation is not ideal yet. It doesn't take into account that
you can use the hook in 2 different components. For now this is fine,
since we only use it in a Dialog and you should also probably only have
a single Dialog open at a time.

Will improve this in the future!

* use the useInertOthers hook

* add scroll lock to the dialog

* ensure we respect autoFocus on form elements within the Dialog

If we have an autoFocus on an input, that input will receive focus. Once
we try to focus the first focusable element in the Dialog this could be
lead to unwanted behaviour. Therefore we check if the focus already is
within the Dialog, if it is, keep it like that.

* only mark aria-modal when Dialog is open

* add initialFocus option to Dialog, FocusTrap & useFocusTrap

* add tests and a few fixes for the initialFocusRef functionality

* forward ref to underlying Dialog component

* close Dialog when it becomes hidden

Could happen when this is in md:hidden for example

* prevent infinite loop

When we `Tab` in a FocusTrap it will try and focus the Next element. If
we are in a state where none of the elements inside the FocusTrap can be
focused, then we keep trying to focus the next one in line. This results
in an infinite loop...

To mitigate this issue, we check if we looped around, if we did, it
means that we tried all the other focusable elements, therefore we can
stop.

* isIntersecting doesn't work in every scenario

When page is scrollable, when dialog is translated of the page. Now just checking for sizes, which should be enough for md:hiden cases

* render Portal contents in a div

Otherwise you can't use multiple Portal components if you render multiple children inside each Portal

* ensure the props bag is typed

* add getByText and assertContainsActiveElement helpers

* add Popover component

* expose Popover

* add Popover example component page

* add quick checks to prevent useless renders

* drop incorrect close function

* update Changelog

* make test error more readable when comparing DOM nodes

* actually call .focus() on the element

This ensures that the document.activeElement becomes the focused element.

* improve useSyncRefs, because ...refs is *always* different

* add dedicated focus management utilities

* refactor useFocusTrap, use focus management utilities

* fix regression while using outside click

There might be a chance that you didn't even notice this *bug*. The idea
is that when you click outside, that the Menu or Listbox closes. However
there is another step that happens:

1. When you click on a focusable item, keep the focus on that item.
2. When you click on a non-focusable item, move focus back to the
   Menu.Button or Listbox.Button

We broke part 2, we never returned to the Menu.Button or Listbox.Button.
This is (might) be important for screenreaders so that they don't "get lost",
because if you click on a non-focusable item, the document.body becomes
the active element. Confusing.

* add outside-click to Dialog itself

* update docs
2021-04-02 15:55:14 +02:00

202 lines
5.6 KiB
TypeScript

import React, {
createContext,
useCallback,
useContext,
useMemo,
useState,
Fragment,
// Types
ElementType,
KeyboardEvent as ReactKeyboardEvent,
MouseEvent as ReactMouseEvent,
} from 'react'
import { Props } from '../../types'
import { render } from '../../utils/render'
import { useId } from '../../hooks/use-id'
import { Keys } from '../keyboard'
import { resolvePropValue } from '../../utils/resolve-prop-value'
import { isDisabledReactIssue7711 } from '../../utils/bugs'
interface StateDefinition {
switch: HTMLButtonElement | null
label: HTMLLabelElement | null
description: HTMLParagraphElement | null
setSwitch(element: HTMLButtonElement): void
setLabel(element: HTMLLabelElement): void
setDescription(element: HTMLParagraphElement): void
}
let GroupContext = createContext<StateDefinition | null>(null)
GroupContext.displayName = 'GroupContext'
function useGroupContext(component: string) {
let context = useContext(GroupContext)
if (context === null) {
let err = new Error(`<${component} /> is missing a parent <Switch.Group /> component.`)
if (Error.captureStackTrace) Error.captureStackTrace(err, useGroupContext)
throw err
}
return context
}
// ---
let DEFAULT_GROUP_TAG = Fragment
function Group<TTag extends ElementType = typeof DEFAULT_GROUP_TAG>(props: Props<TTag>) {
let [switchElement, setSwitchElement] = useState<HTMLButtonElement | null>(null)
let [labelElement, setLabelElement] = useState<HTMLLabelElement | null>(null)
let [descriptionElement, setDescriptionElement] = useState<HTMLParagraphElement | null>(null)
let context = useMemo<StateDefinition>(
() => ({
switch: switchElement,
setSwitch: setSwitchElement,
label: labelElement,
setLabel: setLabelElement,
description: descriptionElement,
setDescription: setDescriptionElement,
}),
[
switchElement,
setSwitchElement,
labelElement,
setLabelElement,
descriptionElement,
setDescriptionElement,
]
)
return (
<GroupContext.Provider value={context}>
{render(props, {}, DEFAULT_GROUP_TAG)}
</GroupContext.Provider>
)
}
// ---
let DEFAULT_SWITCH_TAG = 'button' as const
interface SwitchRenderPropArg {
checked: boolean
}
type SwitchPropsWeControl =
| 'id'
| 'role'
| 'tabIndex'
| 'aria-checked'
| 'aria-labelledby'
| 'aria-describedby'
| 'onClick'
| 'onKeyUp'
| 'onKeyPress'
export function Switch<TTag extends ElementType = typeof DEFAULT_SWITCH_TAG>(
props: Props<
TTag,
SwitchRenderPropArg,
SwitchPropsWeControl | 'checked' | 'onChange' | 'className'
> & {
checked: boolean
onChange(checked: boolean): void
// Special treatment, can either be a string or a function that resolves to a string
className?: ((bag: SwitchRenderPropArg) => string) | string
}
) {
let { checked, onChange, className, ...passThroughProps } = props
let id = `headlessui-switch-${useId()}`
let groupContext = useContext(GroupContext)
let toggle = useCallback(() => onChange(!checked), [onChange, checked])
let handleClick = useCallback(
(event: ReactMouseEvent) => {
if (isDisabledReactIssue7711(event.currentTarget)) return event.preventDefault()
event.preventDefault()
toggle()
},
[toggle]
)
let handleKeyUp = useCallback(
(event: ReactKeyboardEvent<HTMLElement>) => {
if (event.key !== Keys.Tab) event.preventDefault()
if (event.key === Keys.Space) toggle()
},
[toggle]
)
// This is needed so that we can "cancel" the click event when we use the `Enter` key on a button.
let handleKeyPress = useCallback(
(event: ReactKeyboardEvent<HTMLElement>) => event.preventDefault(),
[]
)
let propsBag = useMemo<SwitchRenderPropArg>(() => ({ checked }), [checked])
let propsWeControl = {
id,
ref: groupContext === null ? undefined : groupContext.setSwitch,
role: 'switch',
tabIndex: 0,
className: resolvePropValue(className, propsBag),
'aria-checked': checked,
'aria-labelledby': groupContext?.label?.id,
'aria-describedby': groupContext?.description?.id,
onClick: handleClick,
onKeyUp: handleKeyUp,
onKeyPress: handleKeyPress,
}
if (passThroughProps.as === 'button') {
Object.assign(propsWeControl, { type: 'button' })
}
return render({ ...passThroughProps, ...propsWeControl }, propsBag, DEFAULT_SWITCH_TAG)
}
// ---
let DEFAULT_LABEL_TAG = 'label' as const
interface LabelRenderPropArg {}
type LabelPropsWeControl = 'id' | 'ref' | 'onClick'
function Label<TTag extends ElementType = typeof DEFAULT_LABEL_TAG>(
props: Props<TTag, LabelRenderPropArg, LabelPropsWeControl>
) {
let state = useGroupContext([Switch.name, Label.name].join('.'))
let id = `headlessui-switch-label-${useId()}`
let handleClick = useCallback(() => {
if (!state.switch) return
state.switch.click()
state.switch.focus({ preventScroll: true })
}, [state.switch])
let propsWeControl = { ref: state.setLabel, id, onClick: handleClick }
return render({ ...props, ...propsWeControl }, {}, DEFAULT_LABEL_TAG)
}
// ---
let DEFAULT_DESCRIPTIONL_TAG = 'p' as const
interface DescriptionRenderPropArg {}
type DescriptionPropsWeControl = 'id' | 'ref'
function Description<TTag extends ElementType = typeof DEFAULT_LABEL_TAG>(
props: Props<TTag, DescriptionRenderPropArg, DescriptionPropsWeControl>
) {
let state = useGroupContext([Switch.name, Description.name].join('.'))
let id = `headlessui-switch-description-${useId()}`
let propsWeControl = { ref: state.setDescription, id }
return render({ ...props, ...propsWeControl }, {}, DEFAULT_DESCRIPTIONL_TAG)
}
// ---
Switch.Group = Group
Switch.Label = Label
Switch.Description = Description