示例工程 21-keyboard-focus-a11y

21-keyboard-focus-a11y/app/.tsc/src/lib/contrast.js

javascript · 1.3 KB

function channel(value) {
    const srgb = value / 255;
    return srgb <= 0.04045 ? srgb / 12.92 : Math.pow((srgb + 0.055) / 1.055, 2.4);
}
export function hexToRgb(hex) {
    const clean = hex.replace("#", "").trim();
    const full = clean.length === 3
        ? clean
            .split("")
            .map((char) => char + char)
            .join("")
        : clean;
    if (!/^[0-9a-fA-F]{6}$/.test(full))
        throw new Error("BAD_HEX");
    return [
        Number.parseInt(full.slice(0, 2), 16),
        Number.parseInt(full.slice(2, 4), 16),
        Number.parseInt(full.slice(4, 6), 16),
    ];
}
export function relativeLuminance(hex) {
    const [r, g, b] = hexToRgb(hex);
    return 0.2126 * channel(r) + 0.7152 * channel(g) + 0.0722 * channel(b);
}
export function contrastRatio(foreground, background) {
    const first = relativeLuminance(foreground);
    const second = relativeLuminance(background);
    const lighter = Math.max(first, second);
    const darker = Math.min(first, second);
    return Math.round(((lighter + 0.05) / (darker + 0.05)) * 100) / 100;
}
export function gradeContrast(ratio) {
    return {
        ratio,
        aaNormal: ratio >= 4.5,
        aaLarge: ratio >= 3,
        aaaNormal: ratio >= 7,
    };
}
//# sourceMappingURL=contrast.js.map