@carbon/react
Version:
React components for the Carbon Design System
124 lines (120 loc) • 3.13 kB
JavaScript
/**
* Copyright IBM Corp. 2016, 2023
*
* This source code is licensed under the Apache-2.0 license found in the
* LICENSE file in the root directory of this source tree.
*/
import { extends as _extends } from '../../_virtual/_rollupPluginBabelHelpers.js';
import React, { forwardRef } from 'react';
import cx from 'classnames';
import PropTypes from 'prop-types';
import Link from './Link.js';
import { usePrefix } from '../../internal/usePrefix.js';
import { ArrowDown, ArrowUp } from '../../internal/keyboard/keys.js';
import { match } from '../../internal/keyboard/match.js';
import { AriaLabelPropType } from '../../prop-types/AriaPropTypes.js';
const SwitcherItem = /*#__PURE__*/forwardRef(function SwitcherItem(props, forwardRef) {
const {
'aria-label': ariaLabel,
'aria-labelledby': ariaLabelledBy,
className: customClassName,
children,
isSelected,
expanded,
tabIndex = expanded ? 0 : -1,
index,
handleSwitcherItemFocus,
onKeyDown = () => {},
href,
target,
rel,
...rest
} = props;
const prefix = usePrefix();
const classNames = cx(`${prefix}--switcher__item`, {
[customClassName || '']: !!customClassName
});
const accessibilityLabel = {
'aria-label': ariaLabel,
'aria-labelledby': ariaLabelledBy
};
const linkClassName = cx(`${prefix}--switcher__item-link`, {
[`${prefix}--switcher__item-link--selected`]: isSelected
});
function setTabFocus(evt) {
if (match(evt, ArrowDown)) {
evt.preventDefault();
handleSwitcherItemFocus?.({
currentIndex: index || -1,
direction: 1
});
}
if (match(evt, ArrowUp)) {
evt.preventDefault();
handleSwitcherItemFocus?.({
currentIndex: index || -1,
direction: -1
});
}
}
return /*#__PURE__*/React.createElement("li", {
className: classNames
}, /*#__PURE__*/React.createElement(Link, _extends({
onKeyDown: evt => {
setTabFocus(evt);
onKeyDown(evt);
},
href: href,
target: target,
rel: rel,
ref: forwardRef
}, rest, {
className: linkClassName,
tabIndex: tabIndex
}, accessibilityLabel), children));
});
SwitcherItem.displayName = 'SwitcherItem';
SwitcherItem.propTypes = {
...AriaLabelPropType,
/**
* Specify the text content for the link
*/
children: PropTypes.node.isRequired,
/**
* Optionally provide a custom class to apply to the underlying `<li>` node
*/
className: PropTypes.string,
/**
* event handlers
*/
handleSwitcherItemFocus: PropTypes.func,
/**
* Optionally provide an href for the underlying li`
*/
href: PropTypes.string,
/**
* Specify the index of the SwitcherItem
*/
index: PropTypes.number,
/**
* event handlers
*/
onClick: PropTypes.func,
/**
* event handlers
*/
onKeyDown: PropTypes.func,
/**
* Specify the tab index of the Link
*/
tabIndex: PropTypes.number,
/**
* Specify where to open the link.
*/
target: PropTypes.string,
/**
* The rel property for the link.
*/
rel: PropTypes.string
};
export { SwitcherItem as default };