import { Color } from "https://deno.land/x/color/mod.ts";
import { render } from "https://deno.land/x/resvg_wasm/mod.ts";
import { render as preact } from "npm:preact-render-to-string";
const HEXRE = /^[A-Fa-f0-9]{3,6}$/;
const toHex = str => HEXRE.test(str) ? "#" + str : str;
export default async function(req: Request): Promise<Response> {
const url = new URL(req.url);
const [a, b] = url.pathname.split("/").slice(1);
const size = 256;
const fontSize = 64;
const color = !!a ? toHex(a) : "#fff";
const bg = !!b ? toHex(b) : "#000";
const data = {
color: Color.string(color),
bg: Color.string(bg),
};
data.contrast = data.color.contrast(data.bg);
const text = data.contrast.toFixed(2);
const svg = preact(
<svg
xmlns="http://www.w3.org/2000/svg"
width={size}
height={size}
viewBox={`0 0 ${size} ${size}`}
fill={color}
style={{
fontFamily: "sans-serif",
fontWeight: "bold",
fontSize,
}}
>
<rect
x="0"
y="0"
width={size}
height={size}
fill={bg}
/>
<text
x="50%"
y={size / 2 + fontSize * 0.25}
textAnchor="middle"
dominantBaseline="middle"
>
{text}
</text>
</svg>,
);
const png = await render(svg);
return new Response(png, {
headers: {
"Content-Type": "image/png",
},
});
}