2019-08-23 16:35:34 +00:00
|
|
|
/**
|
|
|
|
* External dependencies
|
|
|
|
*/
|
|
|
|
import PropTypes from 'prop-types';
|
|
|
|
import { Fragment } from 'react';
|
|
|
|
import classNames from 'classnames';
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Component used to render an accessible text given a label and/or a
|
|
|
|
* screenReaderLabel. The wrapper element and wrapper props can also be
|
|
|
|
* specified via props.
|
2020-09-20 23:54:08 +00:00
|
|
|
*
|
|
|
|
* @param {Object} props Incoming props for the component.
|
2020-10-12 12:43:52 +00:00
|
|
|
* @param {string} [props.label] Label content.
|
|
|
|
* @param {string} [props.screenReaderLabel] Content for screen readers.
|
|
|
|
* @param {string} [props.wrapperElement] What element is used to wrap the label.
|
|
|
|
* @param {Object} [props.wrapperProps] Props passed into wrapper element.
|
2019-08-23 16:35:34 +00:00
|
|
|
*/
|
2019-09-05 15:09:31 +00:00
|
|
|
const Label = ( {
|
|
|
|
label,
|
|
|
|
screenReaderLabel,
|
|
|
|
wrapperElement,
|
2020-10-12 12:43:52 +00:00
|
|
|
wrapperProps = {},
|
2019-09-05 15:09:31 +00:00
|
|
|
} ) => {
|
2019-08-23 16:35:34 +00:00
|
|
|
let Wrapper;
|
|
|
|
|
2019-12-06 15:36:55 +00:00
|
|
|
const hasLabel = typeof label !== 'undefined' && label !== null;
|
|
|
|
const hasScreenReaderLabel =
|
|
|
|
typeof screenReaderLabel !== 'undefined' && screenReaderLabel !== null;
|
|
|
|
|
|
|
|
if ( ! hasLabel && hasScreenReaderLabel ) {
|
2019-08-23 16:35:34 +00:00
|
|
|
Wrapper = wrapperElement || 'span';
|
|
|
|
wrapperProps = {
|
|
|
|
...wrapperProps,
|
2019-09-09 10:52:48 +00:00
|
|
|
className: classNames(
|
|
|
|
wrapperProps.className,
|
|
|
|
'screen-reader-text'
|
|
|
|
),
|
2019-08-23 16:35:34 +00:00
|
|
|
};
|
|
|
|
|
2019-09-05 15:09:31 +00:00
|
|
|
return <Wrapper { ...wrapperProps }>{ screenReaderLabel }</Wrapper>;
|
2019-08-23 16:35:34 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
Wrapper = wrapperElement || Fragment;
|
|
|
|
|
2019-12-06 15:36:55 +00:00
|
|
|
if ( hasLabel && hasScreenReaderLabel && label !== screenReaderLabel ) {
|
2019-08-23 16:35:34 +00:00
|
|
|
return (
|
|
|
|
<Wrapper { ...wrapperProps }>
|
2019-09-05 15:09:31 +00:00
|
|
|
<span aria-hidden="true">{ label }</span>
|
2019-09-09 10:52:48 +00:00
|
|
|
<span className="screen-reader-text">
|
|
|
|
{ screenReaderLabel }
|
|
|
|
</span>
|
2019-08-23 16:35:34 +00:00
|
|
|
</Wrapper>
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
2019-09-05 15:09:31 +00:00
|
|
|
return <Wrapper { ...wrapperProps }>{ label }</Wrapper>;
|
2019-08-23 16:35:34 +00:00
|
|
|
};
|
|
|
|
|
|
|
|
Label.propTypes = {
|
2019-12-03 13:39:11 +00:00
|
|
|
label: PropTypes.node,
|
|
|
|
screenReaderLabel: PropTypes.node,
|
2019-08-23 16:35:34 +00:00
|
|
|
wrapperElement: PropTypes.elementType,
|
|
|
|
wrapperProps: PropTypes.object,
|
|
|
|
};
|
|
|
|
|
|
|
|
export default Label;
|