Repository navigation
Expand file tree
/
Copy pathutils.js
More file actions
90 lines (83 loc) · 2.16 KB
/
Copy pathutils.js
File metadata and controls
90 lines (83 loc) · 2.16 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
// utils.js
function extractStyleBlocks($) {
let css = "";
$("style").each((i, el) => {
css += $(el).html() + "\n";
});
return css;
}
function parseCssRules(cssText) {
const rules = [];
const blockRegex = /([^{}]+)\{([^{}]+)\}/g;
let match;
while ((match = blockRegex.exec(cssText)) !== null) {
const selector = match[1].trim();
const body = match[2].trim();
const decls = body.split(";").filter(Boolean);
for (const decl of decls) {
const [prop, ...rest] = decl.split(":");
if (!prop || rest.length === 0) continue;
rules.push({
selector,
property: prop.trim().toLowerCase(),
value: rest.join(":").trim().toLowerCase(),
});
}
}
return rules;
}
function parseInlineStyles($) {
const rules = [];
$("[style]").each((i, el) => {
const styleAttr = $(el).attr("style") || "";
const decls = styleAttr.split(";").filter(Boolean);
for (const decl of decls) {
const [prop, ...rest] = decl.split(":");
if (!prop || rest.length === 0) continue;
rules.push({
selector: `<${el.tagName}> (inline)`,
property: prop.trim().toLowerCase(),
value: rest.join(":").trim().toLowerCase(),
element: el,
});
}
});
return rules;
}
function hexToRgb(hex) {
hex = hex.replace("#", "");
if (hex.length === 3) {
hex = hex.split("").map((c) => c + c).join("");
}
if (hex.length !== 6) return null;
const num = parseInt(hex, 16);
return {
r: (num >> 16) & 255,
g: (num >> 8) & 255,
b: num & 255,
};
}
function luminance({ r, g, b }) {
const a = [r, g, b].map((v) => {
v /= 255;
return v <= 0.03928 ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4);
});
return a[0] * 0.2126 + a[1] * 0.7152 + a[2] * 0.0722;
}
function contrastRatio(hex1, hex2) {
const c1 = hexToRgb(hex1);
const c2 = hexToRgb(hex2);
if (!c1 || !c2) return null;
const l1 = luminance(c1);
const l2 = luminance(c2);
const lighter = Math.max(l1, l2);
const darker = Math.min(l1, l2);
return (lighter + 0.05) / (darker + 0.05);
}
module.exports = {
extractStyleBlocks,
parseCssRules,
parseInlineStyles,
hexToRgb,
contrastRatio,
};