From 8c07757c7a969d0ad54ac48f303a49b9cfa3f5c3 Mon Sep 17 00:00:00 2001 From: Erica Marigold Date: Sat, 6 Jul 2024 22:50:49 +0530 Subject: [PATCH] Add color metadata to site embeds --- src/layouts/Layout.astro | 3 ++ src/utils/color-utils.ts | 63 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 66 insertions(+) create mode 100644 src/utils/color-utils.ts diff --git a/src/layouts/Layout.astro b/src/layouts/Layout.astro index b596842..cac7634 100644 --- a/src/layouts/Layout.astro +++ b/src/layouts/Layout.astro @@ -16,6 +16,7 @@ import { } from "../constants/constants"; import { defaultFavicons } from "../constants/icon"; import type { Favicon } from "../types/config"; +import { hslToHex } from "../utils/color-utils"; import { url } from "../utils/url-utils"; interface Props { @@ -101,6 +102,8 @@ const siteLang = siteConfig.lang.replace("_", "-"); + + {favicons.map(favicon => ( { + const k = (n + h / 30) % 12; + const color = l - a * Math.max(Math.min(k - 3, 9 - k, 1), -1); + return Math.round(255 * color) + .toString(16) + .padStart(2, "0"); // convert to Hex and prefix "0" if needed + }; + return `#${f(0)}${f(8)}${f(4)}`; +} + +/** + * Converts an HSL color value to RGB. Conversion formula + * adapted from http://en.wikipedia.org/wiki/HSL_color_space. + * Assumes h, s, and l are contained in the set [0, 1] and + * returns r, g, and b in the set [0, 255]. + * + * @param {number} h The hue + * @param {number} s The saturation + * @param {number} l The lightness + * @return {Array} The RGB representation + */ +export function hslToRgb( + h: number, + s: number, + l: number, +): [number, number, number] { + let r: number; + let g: number; + let b: number; + + if (s === 0) { + r = g = b = l; // achromatic + } else { + const hue2rgb = (p: number, q: number, t: number) => { + if (t < 0) t += 1; + if (t > 1) t -= 1; + if (t < 1 / 6) return p + (q - p) * 6 * t; + if (t < 1 / 2) return q; + if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6; + return p; + }; + + const q = l < 0.5 ? l * (1 + s) : l + s - l * s; + const p = 2 * l - q; + r = hue2rgb(p, q, h + 1 / 3); + g = hue2rgb(p, q, h); + b = hue2rgb(p, q, h - 1 / 3); + } + + return [Math.round(r * 255), Math.round(g * 255), Math.round(b * 255)]; +}