77 lines
3.1 KiB
TypeScript
77 lines
3.1 KiB
TypeScript
import { useEffect, useState } from 'react';
|
|
import { Pipette } from 'lucide-react';
|
|
import { Input } from '~/components/ui/input';
|
|
import { normalizeHex } from '~/lib/color';
|
|
import { cn } from '~/lib/utils';
|
|
import type { ColorPreset } from '~/types/project';
|
|
|
|
const swatch = 'relative h-[26px] w-[26px] shrink-0 cursor-pointer rounded-full transition-shadow';
|
|
const ring = (selected: boolean) => (selected ? 'ring-2 ring-text-primary ring-offset-2 ring-offset-surface-dialog' : 'ring-1 ring-inset ring-text-primary/15');
|
|
|
|
interface ColorPickerProps {
|
|
id: string;
|
|
label: string;
|
|
value: string;
|
|
presets: ColorPreset[];
|
|
onChange: (hex: string) => void;
|
|
}
|
|
|
|
// Preset swatches, a custom swatch that opens the system colour picker, and a hex field
|
|
export function ColorPicker({ id, label, value, presets, onChange }: ColorPickerProps) {
|
|
const [draft, setDraft] = useState(value);
|
|
const isCustom = !presets.some((preset) => preset.value === value);
|
|
|
|
// Keep the hex field in step when a swatch or the system picker changes the colour
|
|
useEffect(() => setDraft(value), [value]);
|
|
|
|
return (
|
|
<div className='flex flex-wrap items-center gap-2.5'>
|
|
<div role='radiogroup' aria-label={label} className='flex flex-wrap items-center gap-2.5'>
|
|
{presets.map((preset) => (
|
|
<button
|
|
key={preset.value}
|
|
type='button'
|
|
role='radio'
|
|
aria-checked={preset.value === value}
|
|
aria-label={preset.label}
|
|
title={preset.label}
|
|
onClick={() => onChange(preset.value)}
|
|
style={{ backgroundColor: preset.value }}
|
|
className={cn(swatch, ring(preset.value === value))}
|
|
/>
|
|
))}
|
|
<label
|
|
title='Custom colour'
|
|
style={isCustom ? { backgroundColor: value } : undefined}
|
|
className={cn(swatch, 'flex items-center justify-center bg-surface-control text-text-subtle hover:text-text-primary', ring(isCustom))}
|
|
>
|
|
{!isCustom && <Pipette size={12} />}
|
|
<input
|
|
type='color'
|
|
aria-label={`${label}: custom colour`}
|
|
value={value}
|
|
onChange={(e) => onChange(e.target.value)}
|
|
className='absolute inset-0 cursor-pointer opacity-0'
|
|
/>
|
|
</label>
|
|
</div>
|
|
<Input
|
|
id={id}
|
|
size='sm'
|
|
mono
|
|
aria-label={`${label} hex code`}
|
|
value={draft}
|
|
maxLength={7}
|
|
spellCheck={false}
|
|
className='w-[92px]'
|
|
onChange={(e) => {
|
|
setDraft(e.target.value);
|
|
const hex = normalizeHex(e.target.value);
|
|
if (hex) onChange(hex);
|
|
}}
|
|
onBlur={() => setDraft(value)}
|
|
/>
|
|
</div>
|
|
);
|
|
}
|