2019-08-23 16:35:34 +00:00
|
|
|
/**
|
|
|
|
* External dependencies
|
|
|
|
*/
|
2021-02-26 11:57:49 +00:00
|
|
|
import { Fragment } from '@wordpress/element';
|
2019-08-23 16:35:34 +00:00
|
|
|
import classNames from 'classnames';
|
2021-05-19 09:55:15 +00:00
|
|
|
import type { ReactElement, HTMLProps } from 'react';
|
2021-02-26 11:57:49 +00:00
|
|
|
|
2021-05-19 09:55:15 +00:00
|
|
|
interface LabelProps extends HTMLProps< HTMLElement > {
|
2022-11-10 10:05:41 +00:00
|
|
|
label?: string | undefined;
|
|
|
|
screenReaderLabel?: string | undefined;
|
2021-02-26 11:57:49 +00:00
|
|
|
wrapperElement?: string;
|
2021-05-19 09:55:15 +00:00
|
|
|
wrapperProps?: HTMLProps< HTMLElement >;
|
2021-02-26 11:57:49 +00:00
|
|
|
}
|
2019-08-23 16:35:34 +00:00
|
|
|
|
|
|
|
/**
|
|
|
|
* 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
|
|
|
*
|
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 = {},
|
2021-03-05 14:03:48 +00:00
|
|
|
}: LabelProps ): ReactElement => {
|
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
|
|
|
};
|
|
|
|
|
|
|
|
export default Label;
|