-
Notifications
You must be signed in to change notification settings - Fork 9.4k
/
Copy pathfont-size.js
347 lines (302 loc) · 12.3 KB
/
font-size.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
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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
/**
* @license Copyright 2017 Google Inc. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
*/
'use strict';
/** @typedef {LH.Artifacts.FontSize['analyzedFailingNodesData'][0]} FailingNodeData */
const URL = require('../../lib/url-shim.js');
const i18n = require('../../lib/i18n/i18n.js');
const Audit = require('../audit.js');
const ComputedViewportMeta = require('../../computed/viewport-meta.js');
const MINIMAL_PERCENTAGE_OF_LEGIBLE_TEXT = 60;
const UIStrings = {
/** Title of a Lighthouse audit that provides detail on the font sizes used on the page. This descriptive title is shown to users when the fonts used on the page are large enough to be considered legible. */
title: 'Document uses legible font sizes',
/** Title of a Lighthouse audit that provides detail on the font sizes used on the page. This descriptive title is shown to users when there is a font that may be too small to be read by users. */
failureTitle: 'Document doesn\'t use legible font sizes',
/** Description of a Lighthouse audit that tells the user *why* they need to use a larger font size. This is displayed after a user expands the section to see more. No character length limits. 'Learn More' becomes link text to additional documentation. */
description: 'Font sizes less than 12px are too small to be legible and require mobile visitors to “pinch to zoom” in order to read. Strive to have >60% of page text ≥12px. [Learn more](https://developers.google.com/web/tools/lighthouse/audits/font-sizes).',
/** Label for the audit identifying font sizes that are too small. */
displayValue: '{decimalProportion, number, extendedPercent} legible text',
/** Explanatory message stating that there was a failure in an audit caused by a missing page viewport meta tag configuration. "viewport" and "meta" are HTML terms and should not be translated. */
explanationViewport: 'Text is illegible because there\'s no viewport meta tag optimized ' +
'for mobile screens.',
/** Explanatory message stating that there was a failure in an audit caused by a certain percentage of the text on the page being too small. "decimalProportion" will be replaced by a percentage between 0 and 100%. */
explanation: '{decimalProportion, number, extendedPercent} of text is too small.',
/** Explanatory message stating that there was a failure in an audit caused by a certain percentage of the text on the page being too small, based on a sample size of text that was less than 100% of the text on the page. "decimalProportion" will be replaced by a percentage between 0 and 100%. */
explanationWithDisclaimer: '{decimalProportion, number, extendedPercent} of text is too ' +
'small (based on {decimalProportionVisited, number, extendedPercent} sample).',
};
const str_ = i18n.createMessageInstanceIdFn(__filename, UIStrings);
/**
* @param {Array<FailingNodeData>} fontSizeArtifact
* @returns {Array<FailingNodeData>}
*/
function getUniqueFailingRules(fontSizeArtifact) {
/** @type {Map<string, FailingNodeData>} */
const failingRules = new Map();
fontSizeArtifact.forEach(({cssRule, fontSize, textLength, node}) => {
const artifactId = getFontArtifactId(cssRule, node);
const failingRule = failingRules.get(artifactId);
if (!failingRule) {
failingRules.set(artifactId, {
node,
cssRule,
fontSize,
textLength,
});
} else {
failingRule.textLength += textLength;
}
});
return [...failingRules.values()];
}
/**
* @param {Array<string>=} attributes
* @returns {Map<string, string>}
*/
function getAttributeMap(attributes = []) {
const map = new Map();
for (let i = 0; i < attributes.length; i += 2) {
const name = attributes[i].toLowerCase();
const value = attributes[i + 1].trim();
if (value) {
map.set(name, value);
}
}
return map;
}
/**
* TODO: return unique selector, like axe-core does, instead of just id/class/name of a single node
* @param {FailingNodeData['node']} node
* @returns {string}
*/
function getSelector(node) {
const attributeMap = getAttributeMap(node.attributes);
if (attributeMap.has('id')) {
return '#' + attributeMap.get('id');
} else {
const attrClass = attributeMap.get('class');
if (attrClass) {
return '.' + attrClass.split(/\s+/).join('.');
}
}
return node.localName.toLowerCase();
}
/**
* @param {FailingNodeData['node']} node
* @return {{type: 'node', selector: string, snippet: string}}
*/
function nodeToTableNode(node) {
const attributes = node.attributes || [];
const attributesString = attributes.map((value, idx) =>
(idx % 2 === 0) ? ` ${value}` : `="${value}"`
).join('');
return {
type: 'node',
selector: node.parentNode ? getSelector(node.parentNode) : '',
snippet: `<${node.localName}${attributesString}>`,
};
}
/**
* @param {string} baseURL
* @param {FailingNodeData['cssRule']} styleDeclaration
* @param {FailingNodeData['node']} node
* @returns {{source: string, selector: string | {type: 'node', selector: string, snippet: string}}}
*/
function findStyleRuleSource(baseURL, styleDeclaration, node) {
if (
!styleDeclaration ||
styleDeclaration.type === 'Attributes' ||
styleDeclaration.type === 'Inline'
) {
return {
selector: nodeToTableNode(node),
source: baseURL,
};
}
if (styleDeclaration.parentRule &&
styleDeclaration.parentRule.origin === 'user-agent') {
return {
selector: styleDeclaration.parentRule.selectors.map(item => item.text).join(', '),
source: 'User Agent Stylesheet',
};
}
if (styleDeclaration.type === 'Regular' && styleDeclaration.parentRule) {
const rule = styleDeclaration.parentRule;
const stylesheet = styleDeclaration.stylesheet;
if (stylesheet) {
let source;
const selector = rule.selectors.map(item => item.text).join(', ');
if (stylesheet.sourceURL) {
const url = new URL(stylesheet.sourceURL, baseURL);
const range = styleDeclaration.range;
source = `${url.href}`;
// !!range == has defined location in a source file (.css or .html)
if (range) {
let line = range.startLine + 1;
let column = range.startColumn;
// Add the startLine/startColumn of the <style> element to the range, if stylesheet
// is inline.
// Always use the rule's location if a sourceURL magic comment is
// present (`hasSourceURL` is true) - this makes the line/col relative to the start
// of the style tag, which makes them relevant when the "file" is open in DevTool's
// Sources panel.
const addHtmlLocationOffset = stylesheet.isInline && !stylesheet.hasSourceURL;
if (addHtmlLocationOffset) {
line += stylesheet.startLine;
// The column the stylesheet begins on is only relevant if the rule is declared on the same line.
if (range.startLine === 0) {
column += stylesheet.startColumn;
}
}
source += `:${line}:${column}`;
}
} else {
// dynamically injected to page
source = 'dynamic';
}
return {
selector,
source,
};
}
}
// The responsible style declaration was not captured in the font-size gatherer due to
// the rate limiting we do in `fetchFailingNodeSourceRules`.
return {
selector: '',
source: 'Unknown',
};
}
/**
* @param {FailingNodeData['cssRule']} styleDeclaration
* @param {FailingNodeData['node']} node
* @return {string}
*/
function getFontArtifactId(styleDeclaration, node) {
if (styleDeclaration && styleDeclaration.type === 'Regular') {
const startLine = styleDeclaration.range ? styleDeclaration.range.startLine : 0;
const startColumn = styleDeclaration.range ? styleDeclaration.range.startColumn : 0;
return `${styleDeclaration.styleSheetId}@${startLine}:${startColumn}`;
} else {
return `node_${node.nodeId}`;
}
}
class FontSize extends Audit {
/**
* @return {LH.Audit.Meta}
*/
static get meta() {
return {
id: 'font-size',
title: str_(UIStrings.title),
failureTitle: str_(UIStrings.failureTitle),
description: str_(UIStrings.description),
requiredArtifacts: ['FontSize', 'URL', 'MetaElements', 'TestedAsMobileDevice'],
};
}
/**
* @param {LH.Artifacts} artifacts
* @param {LH.Audit.Context} context
* @return {Promise<LH.Audit.Product>}
*/
static async audit(artifacts, context) {
if (!artifacts.TestedAsMobileDevice) {
// Font size isn't important to desktop SEO
return {
score: 1,
notApplicable: true,
};
}
const viewportMeta = await ComputedViewportMeta.request(artifacts.MetaElements, context);
if (!viewportMeta.isMobileOptimized) {
return {
score: 0,
explanation: str_(UIStrings.explanationViewport),
};
}
const {
analyzedFailingNodesData,
analyzedFailingTextLength,
failingTextLength,
visitedTextLength,
totalTextLength,
} = artifacts.FontSize;
if (totalTextLength === 0) {
return {
score: 1,
};
}
const failingRules = getUniqueFailingRules(analyzedFailingNodesData);
const percentageOfPassingText =
(visitedTextLength - failingTextLength) / visitedTextLength * 100;
const pageUrl = artifacts.URL.finalUrl;
/** @type {LH.Audit.Details.Table['headings']} */
const headings = [
{key: 'source', itemType: 'url', text: 'Source'},
{key: 'selector', itemType: 'code', text: 'Selector'},
{key: 'coverage', itemType: 'text', text: '% of Page Text'},
{key: 'fontSize', itemType: 'text', text: 'Font Size'},
];
const tableData = failingRules.sort((a, b) => b.textLength - a.textLength)
.map(({cssRule, textLength, fontSize, node}) => {
const percentageOfAffectedText = textLength / visitedTextLength * 100;
const origin = findStyleRuleSource(pageUrl, cssRule, node);
return {
source: origin.source,
selector: origin.selector,
coverage: `${percentageOfAffectedText.toFixed(2)}%`,
fontSize: `${fontSize}px`,
};
});
// all failing nodes that were not fully analyzed will be displayed in a single row
if (analyzedFailingTextLength < failingTextLength) {
const percentageOfUnanalyzedFailingText =
(failingTextLength - analyzedFailingTextLength) / visitedTextLength * 100;
tableData.push({
source: 'Add\'l illegible text',
selector: '',
coverage: `${percentageOfUnanalyzedFailingText.toFixed(2)}%`,
fontSize: '< 12px',
});
}
if (percentageOfPassingText > 0) {
tableData.push({
source: 'Legible text',
selector: '',
coverage: `${percentageOfPassingText.toFixed(2)}%`,
fontSize: '≥ 12px',
});
}
const decimalProportion = (percentageOfPassingText / 100);
const displayValue = str_(UIStrings.displayValue, {decimalProportion});
const details = Audit.makeTableDetails(headings, tableData);
const passed = percentageOfPassingText >= MINIMAL_PERCENTAGE_OF_LEGIBLE_TEXT;
let explanation;
if (!passed) {
const percentageOfFailingText = (100 - percentageOfPassingText) / 100;
// if we were unable to visit all text nodes we should disclose that information
if (visitedTextLength < totalTextLength) {
const percentageOfVisitedText = (visitedTextLength / totalTextLength);
explanation = str_(UIStrings.explanationWithDisclaimer,
{
decimalProportion: percentageOfFailingText,
decimalProportionVisited: percentageOfVisitedText,
});
} else {
explanation = str_(UIStrings.explanation,
{decimalProportion: percentageOfFailingText});
}
}
return {
score: Number(passed),
details,
displayValue,
explanation,
};
}
}
module.exports = FontSize;
module.exports.UIStrings = UIStrings;