1 | /*
|
2 | * Copyright 2020 Adobe. All rights reserved.
|
3 | * This file is licensed to you under the Apache License, Version 2.0 (the "License");
|
4 | * you may not use this file except in compliance with the License. You may obtain a copy
|
5 | * of the License at http://www.apache.org/licenses/LICENSE-2.0
|
6 | *
|
7 | * Unless required by applicable law or agreed to in writing, software distributed under
|
8 | * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
|
9 | * OF ANY KIND, either express or implied. See the License for the specific language
|
10 | * governing permissions and limitations under the License.
|
11 | */
|
12 |
|
13 | import {AriaLabelingProps, DOMProps} from '@react-types/shared';
|
14 | import {useId} from './useId';
|
15 |
|
16 | /**
|
17 | * Merges aria-label and aria-labelledby into aria-labelledby when both exist.
|
18 | * @param props - Aria label props.
|
19 | * @param defaultLabel - Default value for aria-label when not present.
|
20 | */
|
21 | export function useLabels(props: DOMProps & AriaLabelingProps, defaultLabel?: string): DOMProps & AriaLabelingProps {
|
22 | let {
|
23 | id,
|
24 | 'aria-label': label,
|
25 | 'aria-labelledby': labelledBy
|
26 | } = props;
|
27 |
|
28 | // If there is both an aria-label and aria-labelledby,
|
29 | // combine them by pointing to the element itself.
|
30 | id = useId(id);
|
31 | if (labelledBy && label) {
|
32 | let ids = new Set([id, ...labelledBy.trim().split(/\s+/)]);
|
33 | labelledBy = [...ids].join(' ');
|
34 | } else if (labelledBy) {
|
35 | labelledBy = labelledBy.trim().split(/\s+/).join(' ');
|
36 | }
|
37 |
|
38 | // If no labels are provided, use the default
|
39 | if (!label && !labelledBy && defaultLabel) {
|
40 | label = defaultLabel;
|
41 | }
|
42 |
|
43 | return {
|
44 | id,
|
45 | 'aria-label': label,
|
46 | 'aria-labelledby': labelledBy
|
47 | };
|
48 | }
|