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.
|
|
|
|
*/
|
2019-09-05 15:09:31 +00:00
|
|
|
const Label = ( {
|
|
|
|
label,
|
|
|
|
screenReaderLabel,
|
|
|
|
wrapperElement,
|
|
|
|
wrapperProps,
|
|
|
|
} ) => {
|
2019-08-23 16:35:34 +00:00
|
|
|
let Wrapper;
|
|
|
|
|
|
|
|
if ( ! label && screenReaderLabel ) {
|
|
|
|
Wrapper = wrapperElement || 'span';
|
|
|
|
wrapperProps = {
|
|
|
|
...wrapperProps,
|
|
|
|
className: classNames( wrapperProps.className, 'screen-reader-text' ),
|
|
|
|
};
|
|
|
|
|
2019-09-05 15:09:31 +00:00
|
|
|
return <Wrapper { ...wrapperProps }>{ screenReaderLabel }</Wrapper>;
|
2019-08-23 16:35:34 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
Wrapper = wrapperElement || Fragment;
|
|
|
|
|
|
|
|
if ( label && screenReaderLabel && label !== screenReaderLabel ) {
|
|
|
|
return (
|
|
|
|
<Wrapper { ...wrapperProps }>
|
2019-09-05 15:09:31 +00:00
|
|
|
<span aria-hidden="true">{ label }</span>
|
|
|
|
<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 = {
|
|
|
|
label: PropTypes.string,
|
|
|
|
screenReaderLabel: PropTypes.string,
|
|
|
|
wrapperElement: PropTypes.elementType,
|
|
|
|
wrapperProps: PropTypes.object,
|
|
|
|
};
|
|
|
|
|
|
|
|
Label.defaultProps = {
|
|
|
|
wrapperProps: {},
|
|
|
|
};
|
|
|
|
|
|
|
|
export default Label;
|