This repository has been archived by the owner on Aug 24, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
analyzeWCAGContrast.tsx
112 lines (99 loc) · 2.67 KB
/
analyzeWCAGContrast.tsx
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
import React, { ReactElement, ReactNodeArray } from 'react';
import { hex, score, Score } from 'wcag-contrast';
export interface Scores {
background: Score;
paper: Score;
}
export interface WCAGContrastReport {
scores: Record<string, Scores>;
svg: ReactElement;
}
export interface AnalyzeWCAGContrastParams {
backgroundColor: string;
paperColor: string;
colors: Record<string, string>;
}
const width: number = 700;
const height: number = 140;
const margin: number = 10;
const scoreFontSize: number = 70;
const colorFontSize: number = 18;
export function analyzeWCAGContrast({
backgroundColor,
paperColor,
colors,
}: AnalyzeWCAGContrastParams): WCAGContrastReport {
const scores: Record<string, Scores> = {};
const elements: ReactNodeArray = [];
const colorNames: string[] = Object.keys(colors);
let i: number = -1;
const max: number = colorNames.length;
while (++i < max) {
const colorName: string = colorNames[i];
const color: string = colors[colorName];
const backgroundScore: Score = score(hex(backgroundColor, color));
const paperScore: Score = score(hex(paperColor, color));
scores[colorName] = {
background: backgroundScore,
paper: paperScore,
};
elements.push(
<g key={color} transform={`translate(0 ${(height + margin) * i})`}>
<rect width={width} height={height} fill={backgroundColor} />
<text x={20} y={80} fontSize={scoreFontSize} fill={color}>
{backgroundScore}
</text>
<text
x={20}
y={115}
fontSize={colorFontSize}
fill={color}
opacity={0.5}
>
{colorName.toUpperCase()} {backgroundColor.toUpperCase()}{' '}
{color.toUpperCase()}
</text>
<rect
x={width / 2}
y={10}
width={width / 2 - margin}
height={height - margin * 2}
fill={paperColor}
/>
<text x={width / 2 + 20} y={80} fontSize={scoreFontSize} fill={color}>
{paperScore}
</text>
<text
x={width / 2 + 20}
y={115}
fontSize={colorFontSize}
fill={color}
opacity={0.5}
>
{colorName.toUpperCase()} {paperColor.toUpperCase()}{' '}
{color.toUpperCase()}
</text>
</g>,
);
}
return {
scores,
svg: (
<svg
xmlns="http://www.w3.org/2000/svg"
version="1.1"
width={width}
height={max * height + (max - 1) * margin}
>
<style>
{`
text {
font-family: "Times New Roman", Times, serif;
}
`}
</style>
{elements}
</svg>
),
};
}