Public
HTTP
Forked from jxnblk/color_contrast
jxnblk-color_contrast_api.web.val.run
May 16, 2024
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
import { Color } from "https://deno.land/x/color/mod.ts";
const HEXRE = /^[A-Fa-f0-9]{3,6}$/;
const HASHRE = /^#[A-Fa-f0-9]{3,6}$/;
const LARGE = 3;
const AA = 4.5;
const AAA = 7;
const toHex = str => HEXRE.test(str) ? "#" + str : str;
const stripHash = str => HASHRE.test(str) ? str.slice(1) : str;
export function colorContrast (color, bg) : any {
const data = {
color,
bg,
};
const contrast = data.color.contrast(data.bg).toFixed(2);
const level = getLevel(contrast);
const title = `${contrast} ${level}`;
const image = encodeURI(
`https://jxnblk-png_card.web.val.run/?color=${stripHash(data.color.hex())}&bg=${
stripHash(data.bg.hex())
}&text=${title}&fontSize=128`,
);
return {
...data,
hex: {
color: data.color.hex(),
bg: data.bg.hex(),
},
params: {
color,
bg,
},
contrast,
level,
image,
};
}
export default async function(req: Request): Promise<Response> {
const path = new URL(req.url).pathname;
const [
color = "fff",
bg = "000",
] = path.split("/").filter(Boolean);
const data = colorContrast(Color.string(toHex(color)), Color.string(toHex(bg)));
return Response.json(data);
}
const getLevel = contrast => {
if (contrast >= AAA) {
return "AAA";
} else if (contrast >= AA) {
return "AA";
} else if (contrast >= LARGE) {
return "AA LARGE";
} else {
return "FAIL";
}
};
Val Town is a social website to write and deploy JavaScript.
Build APIs and schedule functions from your browser.
Comments
Nobody has commented on this val yet: be the first!
May 16, 2024