"use client";
import { useState } from "react";
import { contrastRatio, readableColor } from "@/lib/theme-contrast";
type ColorFieldProps = {
name: string;
label: string;
description: string;
defaultValue: string;
/** Background color to check the foreground contrast against. */
bgValue?: string;
};
export function ColorField({
name,
label,
description,
defaultValue,
bgValue,
}: ColorFieldProps) {
const [val, setVal] = useState(defaultValue);
const ratio = bgValue ? contrastRatio(val, bgValue) : null;
const poor = ratio != null && ratio < 4.5;
const ok = ratio != null && ratio >= 4.5;
return (
{
const next = e.target.value;
if (bgValue) {
const nextRatio = contrastRatio(next, bgValue);
if (nextRatio != null && nextRatio < 4.5) {
setVal(readableColor("#ffffff", [bgValue]));
return;
}
}
setVal(next);
}}
style={{
width: 42,
height: 36,
padding: 0,
border: "none",
background: "none",
cursor: "pointer",
flexShrink: 0,
}}
/>
{label}
{ratio != null ? (
{ratio.toFixed(1)}:1 {ok ? "✓" : "⚠"}
) : null}
{description}
{bgValue ? (
Aa Text preview
) : null}
{poor && bgValue ? (
) : null}
);
}