-
Notifications
You must be signed in to change notification settings - Fork 742
/
color-contrast.js
85 lines (71 loc) · 2.4 KB
/
color-contrast.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
const { dom, color, text } = axe.commons;
if (!dom.isVisible(node, false)) {
return true;
}
const visibleText = text.visibleVirtual(virtualNode, false, true);
const ignoreUnicode = !!(options || {}).ignoreUnicode;
const textContainsOnlyUnicode = !text.sanitize(
text.removeUnicode(visibleText, {
emoji: false,
nonBmp: true,
punctuations: false
})
).length;
if (textContainsOnlyUnicode && ignoreUnicode) {
this.data({ messageKey: 'nonBmp' });
return undefined;
}
const noScroll = !!(options || {}).noScroll;
const bgNodes = [];
const bgColor = color.getBackgroundColor(node, bgNodes, noScroll);
const fgColor = color.getForegroundColor(node, noScroll, bgColor);
const nodeStyle = window.getComputedStyle(node);
const fontSize = parseFloat(nodeStyle.getPropertyValue('font-size'));
const fontWeight = nodeStyle.getPropertyValue('font-weight');
const bold =
['bold', 'bolder', '600', '700', '800', '900'].indexOf(fontWeight) !== -1;
const cr = color.hasValidContrastRatio(bgColor, fgColor, fontSize, bold);
// truncate ratio to three digits while rounding down
// 4.499 = 4.49, 4.019 = 4.01
const truncatedResult = Math.floor(cr.contrastRatio * 100) / 100;
// if fgColor or bgColor are missing, get more information.
let missing;
if (bgColor === null) {
missing = color.incompleteData.get('bgColor');
}
const equalRatio = truncatedResult === 1;
const shortTextContent = visibleText.length === 1;
const ignoreLength = !!(options || {}).ignoreLength;
if (equalRatio) {
missing = color.incompleteData.set('bgColor', 'equalRatio');
} else if (shortTextContent && !ignoreLength) {
// Check that the text content is a single character long
missing = 'shortTextContent';
}
// need both independently in case both are missing
const data = {
fgColor: fgColor ? fgColor.toHexString() : undefined,
bgColor: bgColor ? bgColor.toHexString() : undefined,
contrastRatio: cr ? truncatedResult : undefined,
fontSize: `${((fontSize * 72) / 96).toFixed(1)}pt (${fontSize}px)`,
fontWeight: bold ? 'bold' : 'normal',
messageKey: missing,
expectedContrastRatio: cr.expectedContrastRatio + ':1'
};
this.data(data);
// We don't know, so we'll put it into Can't Tell
if (
fgColor === null ||
bgColor === null ||
equalRatio ||
(shortTextContent && !ignoreLength && !cr.isValid)
) {
missing = null;
color.incompleteData.clear();
this.relatedNodes(bgNodes);
return undefined;
}
if (!cr.isValid) {
this.relatedNodes(bgNodes);
}
return cr.isValid;