forked from dequelabs/axe-core
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathselector-cache.js
More file actions
211 lines (181 loc) · 6.33 KB
/
selector-cache.js
File metadata and controls
211 lines (181 loc) · 6.33 KB
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
import { matchesExpression } from './matches';
import tokenList from './token-list';
// since attribute names can't contain whitespace, this will be
// a reserved list for ids so we can perform virtual id lookups
const idsKey = ' [idsMap]';
/**
* Get nodes from the selector cache that match the selector.
* @param {VirtualTree[]} domTree flattened tree collection to search
* @param {Object} expressions
* @param {Function} filter function (optional)
* @return {Mixed} Array of nodes that match the selector or undefined if the selector map is not setup
*/
export function getNodesMatchingExpression(domTree, expressions, filter) {
// check to see if the domTree is the root and has the selector
// map. if not we just return and let our QSA code do the finding
const selectorMap = domTree[0]._selectorMap;
if (!selectorMap) {
return;
}
const shadowId = domTree[0].shadowId;
// if the selector uses a global selector with a combinator
// (e.g. A *, A > *) it's actually faster to use our QSA code than
// getting all nodes and using matchesExpression
for (let i = 0; i < expressions.length; i++) {
if (
expressions[i].length > 1 &&
expressions[i].some(expression => isGlobalSelector(expression))
) {
return;
}
}
// it turned out to be more performant to use a Set to generate a
// unique list of nodes rather than an array and array.includes
// (~3 seconds total on a benchmark site)
const nodeSet = new Set();
expressions.forEach(expression => {
const matchingNodes = findMatchingNodes(expression, selectorMap, shadowId);
matchingNodes?.nodes?.forEach(node => {
// for complex selectors we need to verify that the node
// actually matches the entire selector since we only have
// nodes that partially match the last part of the selector
if (
matchingNodes.isComplexSelector &&
!matchesExpression(node, expression)
) {
return;
}
nodeSet.add(node);
});
});
// Sets in ie11 do not work with Array.from without a polyfill
//(missing `.entries`), but do have forEach
let matchedNodes = [];
nodeSet.forEach(node => matchedNodes.push(node));
if (filter) {
matchedNodes = matchedNodes.filter(filter);
}
return matchedNodes.sort((a, b) => a.nodeIndex - b.nodeIndex);
}
/**
* Add nodes to the passed in Set that match just a part of the selector in order to speed up traversing the entire tree.
* @param {Object} expression Selector Expression
* @param {Object} selectorMap Selector map cache
* @param {String} shadowId ShadowID of the root node
*/
function findMatchingNodes(expression, selectorMap, shadowId) {
// use the last part of the expression to find nodes as it's more
// specific. e.g. for `body h1` use `h1` and not `body`
const exp = expression[expression.length - 1];
let nodes = null;
// a complex selector is one that will require using
// matchesExpression to determine if it matches. these include
// pseudo selectors (:not), combinators (A > B), and any
// attribute value ([class=foo]).
let isComplexSelector =
expression.length > 1 || !!exp.pseudos || !!exp.classes;
if (isGlobalSelector(exp)) {
nodes = selectorMap['*'];
} else {
if (exp.id) {
// a selector must match all parts, otherwise we can just exit early
if (
!selectorMap[idsKey] ||
!Object.hasOwn(selectorMap[idsKey], exp.id) ||
!selectorMap[idsKey][exp.id]?.length
) {
return;
}
// when using id selector (#one) we only find nodes that
// match the shadowId of the root
nodes = selectorMap[idsKey][exp.id].filter(
node => node.shadowId === shadowId
);
}
if (exp.tag && exp.tag !== '*') {
if (!selectorMap[exp.tag]?.length) {
return;
}
const cachedNodes = selectorMap[exp.tag];
nodes = nodes ? getSharedValues(cachedNodes, nodes) : cachedNodes;
}
if (exp.classes) {
if (!selectorMap['[class]']?.length) {
return;
}
const cachedNodes = selectorMap['[class]'];
nodes = nodes ? getSharedValues(cachedNodes, nodes) : cachedNodes;
}
if (exp.attributes) {
for (let i = 0; i < exp.attributes.length; i++) {
const attr = exp.attributes[i];
// an attribute selector that looks for a specific value is
// a complex selector
if (attr.type === 'attrValue') {
isComplexSelector = true;
}
if (!selectorMap[`[${attr.key}]`]?.length) {
return;
}
const cachedNodes = selectorMap[`[${attr.key}]`];
nodes = nodes ? getSharedValues(cachedNodes, nodes) : cachedNodes;
}
}
}
return { nodes, isComplexSelector };
}
/**
* Non-tag selectors use `*` for the tag name so a global selector won't have any other properties of the expression. Pseudo selectors that use `*` (e.g. `*:not([class])`) will still be considered a global selector since we don't cache anything for pseudo selectors and will rely on filtering with matchesExpression.
* @param {Object} expression Selector Expression
* @returns {Boolean}
*/
function isGlobalSelector(expression) {
return (
expression.tag === '*' &&
!expression.attributes &&
!expression.id &&
!expression.classes
);
}
/**
* Find all nodes in A that are also in B.
* @param {Mixed[]} a
* @param {Mixed[]} b
* @returns {Mixed[]}
*/
function getSharedValues(a, b) {
return a.filter(node => b.includes(node));
}
/**
* Save a selector and vNode to the selectorMap.
* @param {String} key
* @param {VirtualNode} vNode
* @param {Object} map
*/
function cacheSelector(key, vNode, map) {
if (!Object.hasOwn(map, key)) {
map[key] = [];
}
map[key].push(vNode);
}
/**
* Cache selector information about a VirtalNode.
* @param {VirtualNode} vNode
*/
export function cacheNodeSelectors(vNode, selectorMap) {
if (vNode.props.nodeType !== 1) {
return;
}
cacheSelector(vNode.props.nodeName, vNode, selectorMap);
cacheSelector('*', vNode, selectorMap);
vNode.attrNames.forEach(attrName => {
// element ids are the only values we'll match
if (attrName === 'id') {
selectorMap[idsKey] = selectorMap[idsKey] || {};
tokenList(vNode.attr(attrName)).forEach(value => {
cacheSelector(value, vNode, selectorMap[idsKey]);
});
}
cacheSelector(`[${attrName}]`, vNode, selectorMap);
});
}