2019-08-23 16:35:34 +00:00
|
|
|
/**
|
|
|
|
* External dependencies
|
|
|
|
*/
|
2021-02-26 11:57:49 +00:00
|
|
|
import { Fragment } from '@wordpress/element';
|
2024-05-31 03:49:36 +00:00
|
|
|
import clsx from 'clsx';
|
2021-05-19 09:55:15 +00:00
|
|
|
import type { ReactElement, HTMLProps } from 'react';
|
2021-02-26 11:57:49 +00:00
|
|
|
|
2023-11-14 09:58:57 +00:00
|
|
|
export interface LabelProps extends HTMLProps< HTMLElement > {
|
2023-11-20 13:08:16 +00:00
|
|
|
label?: string | undefined;
|
|
|
|
screenReaderLabel?: string | undefined;
|
|
|
|
wrapperElement?: string | undefined;
|
|
|
|
wrapperProps?: HTMLProps< HTMLElement > | undefined;
|
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,
|
2024-05-31 03:49:36 +00:00
|
|
|
className: clsx( 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;
|