UNPKG

@base-ui-components/react

Version:

Base UI is a library of headless ('unstyled') React components and low-level hooks. You gain complete control over your app's CSS and accessibility features.

43 lines (41 loc) 1.52 kB
'use client'; import * as React from 'react'; export function useFocusableWhenDisabled(parameters) { const { focusableWhenDisabled, disabled, composite = false, tabIndex: tabIndexProp = 0, isNativeButton } = parameters; const isFocusableComposite = composite && focusableWhenDisabled !== false; const isNonFocusableComposite = composite && focusableWhenDisabled === false; // we can't explicitly assign `undefined` to any of these props because it // would otherwise prevent subsequently merged props from setting them const props = React.useMemo(() => { const additionalProps = { // allow Tabbing away from focusableWhenDisabled elements onKeyDown(event) { if (disabled && focusableWhenDisabled && event.key !== 'Tab') { event.preventDefault(); } } }; if (!composite) { additionalProps.tabIndex = tabIndexProp; if (!isNativeButton && disabled) { additionalProps.tabIndex = focusableWhenDisabled ? tabIndexProp : -1; } } if (isNativeButton && (focusableWhenDisabled || isFocusableComposite) || !isNativeButton && disabled) { additionalProps['aria-disabled'] = disabled; } if (isNativeButton && (!focusableWhenDisabled || isNonFocusableComposite)) { additionalProps.disabled = disabled; } return additionalProps; }, [composite, disabled, focusableWhenDisabled, isFocusableComposite, isNonFocusableComposite, isNativeButton, tabIndexProp]); return { props }; }