import { useEffect, useLayoutEffect, useRef, useState, type KeyboardEvent, type ReactNode } from "react"; import { Check, ExternalLink, X } from "lucide-react"; import type { SavedPalette } from "../../../shared/api-types.js"; import type { Theme } from "../../../shared/validation.js"; import { api, errorMessage, useApi } from "../../api.js"; import { Button } from "../../components/ui/button.js"; import { useConfirm } from "../../components/ui/dialog.js"; import { ColorInput, Input } from "../../components/ui/form.js"; import { useToast } from "../../components/ui/toast.js"; import { cx } from "../../lib/cx.js"; import { parseCoolorsInput, themeFromPalette, TRENDING_PALETTES, type Variant } from "../../lib/palette.js"; export const COLOR_FIELDS: [keyof Theme, string][] = [ ["background", "Background"], ["text", "Text"], ["button", "Buttons"], ["buttonText", "Button text"], ]; export const sameTheme = (a: Theme, b: Theme) => COLOR_FIELDS.every(([k]) => a[k].toLowerCase() === b[k].toLowerCase()); const PRESETS: { name: string; theme: Theme }[] = [ { name: "Midnight", theme: { background: "#111827", text: "#e5e7eb", button: "#475569", buttonText: "#ffffff" } }, { name: "Paper", theme: { background: "#fafaf9", text: "#1c1917", button: "#1c1917", buttonText: "#fafaf9" } }, ]; const paletteKey = (colors: string[]) => colors.join("-").toLowerCase(); const cardClass = (selected: boolean) => cx( "relative overflow-hidden rounded-xl border transition", selected ? "border-accent ring-3 ring-accent/20" : "border-border hover:border-border-strong", ); function SectionLabel({ children, actions, hint }: { children: ReactNode; actions?: ReactNode; hint?: ReactNode }) { return (

{children}

{hint &&

{hint}

}
{actions}
); } function PresetCard({ name, theme, selected, onClick }: { name: string; theme: Theme; selected: boolean; onClick: () => void }) { return ( ); } // Miniature of a link page (background, a text line and a button) that applies one version of a palette. function VariantThumb({ theme, label, selected, onClick }: { theme: Theme; label: string; selected: boolean; onClick: () => void }) { return ( ); } // A palette: each color opens the role menu, the two thumbnails apply a dark or light version of it. function PaletteCard({ colors, label, selected, onApply, onPickColor, onRemove, }: { colors: string[]; label: string; selected: Variant | null; onApply: (variant: Variant) => void; onPickColor: (color: string, anchor: HTMLElement) => void; onRemove?: () => void; }) { return (
{colors.map((c, i) => (
{label} {(["dark", "light"] as const).map((v) => ( onApply(v)} /> ))} {onRemove && ( )}
); } // Small menu next to a clicked color: "use as background / text / buttons / button text". function ColorRoleMenu({ color, anchor, theme, onPick, onClose, }: { color: string; anchor: HTMLElement; theme: Theme; onPick: (role: keyof Theme) => void; onClose: () => void; }) { const ref = useRef(null); const [position, setPosition] = useState<{ top: number; left: number } | null>(null); // Place below the color (or above when there's no room), kept inside the viewport. useLayoutEffect(() => { const menu = ref.current; if (!menu) return; const a = anchor.getBoundingClientRect(); const { width, height } = menu.getBoundingClientRect(); const below = a.bottom + 6; const top = below + height > innerHeight - 8 ? Math.max(8, a.top - height - 6) : below; const left = Math.min(Math.max(8, a.left + a.width / 2 - width / 2), innerWidth - width - 8); setPosition({ top, left }); }, [anchor]); // Focus the first item once the menu is visible (hidden elements can't take focus). useEffect(() => { if (position) ref.current?.querySelector("[role=menuitem]")?.focus({ preventScroll: true }); }, [position]); useEffect(() => { const outside = (e: PointerEvent) => { if (!ref.current?.contains(e.target as Node) && e.target !== anchor) onClose(); }; const dismiss = () => onClose(); const escape = (e: globalThis.KeyboardEvent) => { if (e.key !== "Escape") return; onClose(); anchor.focus(); }; document.addEventListener("pointerdown", outside); document.addEventListener("keydown", escape); window.addEventListener("resize", dismiss); window.addEventListener("scroll", dismiss, true); return () => { document.removeEventListener("pointerdown", outside); document.removeEventListener("keydown", escape); window.removeEventListener("resize", dismiss); window.removeEventListener("scroll", dismiss, true); }; }, [anchor, onClose]); const onKeyDown = (e: KeyboardEvent) => { const items = [...(ref.current?.querySelectorAll("[role=menuitem]") ?? [])]; const index = items.indexOf(document.activeElement as HTMLButtonElement); if (e.key === "ArrowDown" || e.key === "ArrowUp") { e.preventDefault(); const next = (index + (e.key === "ArrowDown" ? 1 : -1) + items.length) % items.length; items[next]?.focus(); } }; return (
{color} use for…
{COLOR_FIELDS.map(([key, label]) => { const current = theme[key].toLowerCase() === color.toLowerCase(); return ( ); })}
); } // Theme picker: basic presets, trending and saved coolors.co palettes, and custom colors. export function ThemePicker({ theme, onChange }: { theme: Theme; onChange: (theme: Theme) => void }) { const saved = useApi("/palettes"); const toast = useToast(); const confirm = useConfirm(); // The palette version the current theme was generated from, to mark it as selected. const [source, setSource] = useState<{ colors: string[]; variant: Variant } | null>(null); const [link, setLink] = useState(""); const [linkError, setLinkError] = useState(); const [importing, setImporting] = useState(false); const [menu, setMenu] = useState<{ color: string; anchor: HTMLElement } | null>(null); const toggleMenu = (color: string, anchor: HTMLElement) => setMenu((m) => (m?.anchor === anchor ? null : { color, anchor })); const applyPalette = (colors: string[], variant: Variant) => { setSource({ colors, variant }); onChange(themeFromPalette(colors, variant)); }; const setColor = (role: keyof Theme, color: string) => { setSource(null); onChange({ ...theme, [role]: color }); }; // Which version of this palette is in use, if any (editing a single color deselects it). const selectedVariant = (colors: string[]): Variant | null => source && paletteKey(source.colors) === paletteKey(colors) && sameTheme(themeFromPalette(colors, source.variant), theme) ? source.variant : null; const importLink = async () => { const colors = parseCoolorsInput(link); if (!colors) { setLinkError("That doesn't look like a coolors.co palette link."); return; } setImporting(true); try { await api("POST", "/palettes", { colors }); await saved.reload(); applyPalette(colors, "dark"); setLink(""); setLinkError(undefined); } catch (err) { setLinkError(errorMessage(err)); } finally { setImporting(false); } }; const removePalette = async (palette: SavedPalette) => { const ok = await confirm({ title: "Remove this palette?", description: "Pages that already use its colors keep them.", confirmLabel: "Remove", danger: true }); if (!ok) return; try { await api("DELETE", `/palettes/${palette.id}`); await saved.reload(); toast("Palette removed"); } catch (err) { toast(errorMessage(err), true); } }; const pickHint = "Pick the dark or light version of a palette, or click a single color to use it for one part."; return (
Basic
{PRESETS.map((preset) => ( { setSource(null); onChange(preset.theme); }} /> ))}
Trending on{" "} coolors.co
{TRENDING_PALETTES.map((p) => ( applyPalette(p.colors, v)} onPickColor={toggleMenu} /> ))}
Your palettes
{ e.preventDefault(); void importLink(); }} > { setLink(e.target.value); setLinkError(undefined); }} />
{linkError ? (

{linkError}

) : (

Create or pick a palette on{" "} coolors.co {" "} and paste its URL here.

)} {!!saved.data?.length && (
{saved.data.map((p) => ( applyPalette(p.colors, v)} onPickColor={toggleMenu} onRemove={() => void removePalette(p)} /> ))}
)}
Custom colors
{COLOR_FIELDS.map(([key, label]) => (
{label} setColor(key, v)} />
))}
{menu && ( setMenu(null)} onPick={(role) => { setColor(role, menu.color); setMenu(null); menu.anchor.focus(); }} /> )}
); }