-
-
Notifications
You must be signed in to change notification settings - Fork 639
/
Copy pathisInteractiveRole.js
55 lines (49 loc) · 1.94 KB
/
isInteractiveRole.js
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
// @flow
import { roles as rolesMap } from 'aria-query';
import type { Node } from 'ast-types-flow';
import { getProp, getLiteralPropValue } from 'jsx-ast-utils';
import includes from 'array-includes';
import flatMap from 'array.prototype.flatmap';
const roles = rolesMap.keys();
const interactiveRoles = roles.filter((name) => (
!rolesMap.get(name).abstract
&& rolesMap.get(name).superClass.some((klasses) => includes(klasses, 'widget'))
));
// 'toolbar' does not descend from widget, but it does support
// aria-activedescendant, thus in practice we treat it as a widget.
interactiveRoles.push('toolbar');
/**
* Returns boolean indicating whether the given element has a role
* that is associated with an interactive component. Used when an element
* has a dynamic handler on it and we need to discern whether or not
* its intention is to be interacted with in the DOM.
*
* isInteractiveRole is a Logical Disjunction:
* https://en.wikipedia.org/wiki/Logical_disjunction
* The JSX element does not have a tagName or it has a tagName and a role
* attribute with a value in the set of non-interactive roles.
*/
const isInteractiveRole = (
tagName: string,
attributes: Array<Node>,
): boolean => {
const value = getLiteralPropValue(getProp(attributes, 'role'));
// If value is undefined, then the role attribute will be dropped in the DOM.
// If value is null, then getLiteralAttributeValue is telling us that the
// value isn't in the form of a literal
if (value === undefined || value === null) {
return false;
}
let isInteractive = false;
const normalizedValues = String(value).toLowerCase().split(' ');
const validRoles = flatMap(
normalizedValues,
(name: string) => (includes(roles, name) ? [name] : []),
);
if (validRoles.length > 0) {
// The first role value is a series takes precedence.
isInteractive = includes(interactiveRoles, validRoles[0]);
}
return isInteractive;
};
export default isInteractiveRole;