forked from dequelabs/axe-core
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpreload-cssom.js
More file actions
256 lines (230 loc) · 7.24 KB
/
preload-cssom.js
File metadata and controls
256 lines (230 loc) · 7.24 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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
import getStyleSheetFactory from './get-stylesheet-factory';
import uniqueArray from './unique-array';
import getRootNode from './get-root-node';
import parseStylesheet from './parse-stylesheet';
import querySelectorAllFilter from './query-selector-all-filter';
/**
* Given a rootNode - construct CSSOM
* -> get all source nodes (document & document fragments) within given root node
* -> recursively call `parseStylesheets` to resolve styles for each node
*
* @method preloadCssom
* @memberof `axe.utils`
* @param {Object} options composite options object
* @property {Array<String>} options.assets array of preloaded assets requested, eg: [`cssom`]
* @property {Number} options.timeout timeout
* @property {Object} options.treeRoot (optional) the DOM tree to be inspected
* @returns {Promise}
*/
// TODO: es-modules_tree
function preloadCssom({ treeRoot = axe._tree[0] }) {
/**
* get all `document` and `documentFragment` with in given `tree`
*/
const rootNodes = getAllRootNodesInTree(treeRoot);
if (!rootNodes.length) {
return Promise.resolve();
}
const dynamicDoc = document.implementation.createHTMLDocument(
'Dynamic document for loading cssom'
);
const convertDataToStylesheet = getStyleSheetFactory(dynamicDoc);
return getCssomForAllRootNodes(rootNodes, convertDataToStylesheet).then(
assets => flattenAssets(assets)
);
}
export default preloadCssom;
/**
* Returns am array of source nodes containing `document` and `documentFragment` in a given `tree`.
*
* @param {Object} treeRoot tree
* @returns {Array<Object>} array of objects, which each object containing a root and an optional `shadowId`
*/
function getAllRootNodesInTree(tree) {
const ids = [];
const rootNodes = querySelectorAllFilter(tree, '*', node => {
if (ids.includes(node.shadowId)) {
return false;
}
ids.push(node.shadowId);
return true;
}).map(node => {
return {
shadowId: node.shadowId,
rootNode: getRootNode(node.actualNode)
};
});
return uniqueArray(rootNodes, []);
}
/**
* Process CSSOM on all root nodes
*
* @param {Array<Object>} rootNodes array of root nodes, where node is an enhanced `document` or `documentFragment` object returned from `getAllRootNodesInTree`
* @param {Function} convertDataToStylesheet fn to convert given data to Stylesheet object
* @returns {Promise}
*/
function getCssomForAllRootNodes(rootNodes, convertDataToStylesheet) {
const promises = [];
rootNodes.forEach(({ rootNode, shadowId }, index) => {
const sheets = getStylesheetsOfRootNode(
rootNode,
shadowId,
convertDataToStylesheet
);
if (!sheets) {
return Promise.all(promises);
}
const rootIndex = index + 1;
const parseOptions = {
rootNode,
shadowId,
convertDataToStylesheet,
rootIndex
};
/**
* Note:
* `importedUrls` - keeps urls of already imported stylesheets, to prevent re-fetching
* eg: nested, cyclic or cross referenced `@import` urls
*/
const importedUrls = [];
const p = Promise.all(
sheets.map((sheet, sheetIndex) => {
const priority = [rootIndex, sheetIndex];
return parseStylesheet(sheet, parseOptions, priority, importedUrls);
})
);
promises.push(p);
});
return Promise.all(promises);
}
/**
* Flatten CSSOM assets
*
* @param {Array.<Object[]>} assets nested assets (varying depth)
* @returns {Array<Object>} Array of CSSOM object
*/
function flattenAssets(assets) {
return assets.reduce(
(acc, val) =>
Array.isArray(val) ? acc.concat(flattenAssets(val)) : acc.concat(val),
[]
);
}
/**
* Get stylesheet(s) for root
*
* @param {Object} options.rootNode `document` or `documentFragment`
* @param {String} options.shadowId an id if undefined denotes that given root is a document fragment/ shadowDOM
* @param {Function} options.convertDataToStylesheet a utility function to generate a style sheet from given data (text)
* @returns {Array<Object>} an array of stylesheets
*/
function getStylesheetsOfRootNode(rootNode, shadowId, convertDataToStylesheet) {
let sheets;
// nodeType === 11 -> DOCUMENT_FRAGMENT
if (rootNode.nodeType === 11 && shadowId) {
sheets = getStylesheetsFromDocumentFragment(
rootNode,
convertDataToStylesheet
);
} else {
sheets = getStylesheetsFromDocument(rootNode);
}
return filterStylesheetsWithSameHref(sheets);
}
/**
* Get stylesheets from `documentFragment`
*
* @property {Object} options.rootNode `documentFragment`
* @property {Function} options.convertDataToStylesheet a utility function to generate a stylesheet from given data
* @returns {Array<Object>}
*/
function getStylesheetsFromDocumentFragment(rootNode, convertDataToStylesheet) {
return (
Array.from(rootNode.children)
.filter(filerStyleAndLinkAttributesInDocumentFragment)
// Reducer to convert `<style></style>` and `<link>` references to `CSSStyleSheet` object
.reduce((out, node) => {
const nodeName = node.nodeName.toUpperCase();
const data = nodeName === 'STYLE' ? node.textContent : node;
const isLink = nodeName === 'LINK';
const stylesheet = convertDataToStylesheet({
data,
isLink,
root: rootNode
});
// prevent error in jsdom with style elements not having a `sheet` property
// @see https://github.com/jsdom/jsdom/issues/3179
if (stylesheet.sheet) {
out.push(stylesheet.sheet);
}
return out;
}, [])
);
}
/**
* Get stylesheets from `document`
* -> filter out stylesheet that are `media=print`
*
* @param {Object} rootNode `document`
* @returns {Array<Object>}
*/
function getStylesheetsFromDocument(rootNode) {
return Array.from(rootNode.styleSheets).filter(sheet => {
if (!sheet.media) {
return false;
}
return filterMediaIsPrint(sheet.media.mediaText);
});
}
/**
* Get all `<style></style>` and `<link>` attributes
* -> limit to only `style` or `link` attributes with `rel=stylesheet` and `media != print`
*
* @param {Object} node HTMLElement
* @returns {Boolean}
*/
function filerStyleAndLinkAttributesInDocumentFragment(node) {
const nodeName = node.nodeName.toUpperCase();
const linkHref = node.getAttribute('href');
const linkRel = node.getAttribute('rel');
const isLink =
nodeName === 'LINK' &&
linkHref &&
linkRel &&
node.rel.toUpperCase().includes('STYLESHEET');
const isStyle = nodeName === 'STYLE';
return isStyle || (isLink && filterMediaIsPrint(node.media));
}
/**
* Exclude `link[rel='stylesheet]` attributes where `media=print`
*
* @param {String} media media value eg: 'print'
* @returns {Boolean}
*/
function filterMediaIsPrint(media) {
if (!media) {
return true;
}
return !media.toUpperCase().includes('PRINT');
}
/**
* Exclude any duplicate `stylesheets`, that share the same `href`
*
* @param {Array<Object>} sheets stylesheets
* @returns {Array<Object>}
*/
function filterStylesheetsWithSameHref(sheets) {
const hrefs = [];
return sheets.filter(sheet => {
if (!sheet.href) {
// include sheets without `href`
return true;
}
// if `href` is present, ensure they are not duplicates
if (hrefs.includes(sheet.href)) {
return false;
}
hrefs.push(sheet.href);
return true;
});
}