forked from carbon-design-system/carbon
-
Notifications
You must be signed in to change notification settings - Fork 0
/
getAttributes.ts
56 lines (51 loc) · 1.5 KB
/
getAttributes.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
/**
* Copyright IBM Corp. 2018, 2024
*
* This source code is licensed under the Apache-2.0 license found in the
* LICENSE file in the root directory of this source tree.
*/
export const defaultAttributes = {
// Reference:
// https://github.com/IBM/carbon-components-react/issues/1392
// https://github.com/PolymerElements/iron-iconset-svg/pull/47
// `focusable` is a string attribute which is why we do not use a boolean here
focusable: 'false',
preserveAspectRatio: 'xMidYMid meet',
};
/**
* Get supplementary HTML attributes for a given <svg> element based on existing
* attributes.
*/
export default function getAttributes({
width,
height,
viewBox = `0 0 ${width} ${height}`,
...attributes
}: Record<string, unknown> = {}): Record<string, unknown> {
const { tabindex, ...rest } = attributes;
const iconAttributes: Record<string, unknown> = {
...defaultAttributes,
...rest,
width,
height,
viewBox,
};
// TODO: attributes.title assumes that the consumer will implement <title> and
// correctly set `aria-labelledby`.
if (
iconAttributes['aria-label'] ||
iconAttributes['aria-labelledby'] ||
iconAttributes.title
) {
iconAttributes.role = 'img';
// Reference:
// https://allyjs.io/tutorials/focusing-in-svg.html
if (tabindex !== undefined && tabindex !== null) {
iconAttributes.focusable = 'true';
iconAttributes.tabindex = tabindex;
}
} else {
iconAttributes['aria-hidden'] = true;
}
return iconAttributes;
}