import { useCallback, useEffect, useRef, useState } from "react"; import { getColor } from "./ColorPicker"; import type { ColorPickerType } from "./colorPickerUtils"; import { activeColorPickerSectionAtom } from "./colorPickerUtils"; import { eyeDropperIcon } from "../icons"; import { useAtom } from "../../editor-jotai"; import { KEYS } from "../../keys"; import { activeEyeDropperAtom } from "../EyeDropper"; import clsx from "clsx"; import { t } from "../../i18n"; import { useDevice } from "../App"; import { getShortcutKey } from "../../utils"; interface ColorInputProps { color: string; onChange: (color: string) => void; label: string; colorPickerType: ColorPickerType; } export const ColorInput = ({ color, onChange, label, colorPickerType, }: ColorInputProps) => { const device = useDevice(); const [innerValue, setInnerValue] = useState(color); const [activeSection, setActiveColorPickerSection] = useAtom( activeColorPickerSectionAtom, ); useEffect(() => { setInnerValue(color); }, [color]); const changeColor = useCallback( (inputValue: string) => { const value = inputValue.toLowerCase(); const color = getColor(value); if (color) { onChange(color); } setInnerValue(value); }, [onChange], ); const inputRef = useRef(null); const eyeDropperTriggerRef = useRef(null); useEffect(() => { if (inputRef.current) { inputRef.current.focus(); } }, [activeSection]); const [eyeDropperState, setEyeDropperState] = useAtom(activeEyeDropperAtom); useEffect(() => { return () => { setEyeDropperState(null); }; }, [setEyeDropperState]); return (
#
{ changeColor(event.target.value); }} value={(innerValue || "").replace(/^#/, "")} onBlur={() => { setInnerValue(color); }} tabIndex={-1} onFocus={() => setActiveColorPickerSection("hex")} onKeyDown={(event) => { if (event.key === KEYS.TAB) { return; } else if (event.key === KEYS.ESCAPE) { eyeDropperTriggerRef.current?.focus(); } event.stopPropagation(); }} /> {/* TODO reenable on mobile with a better UX */} {!device.editor.isMobile && ( <>
setEyeDropperState((s) => s ? null : { keepOpenOnAlt: false, onSelect: (color) => onChange(color), colorPickerType, }, ) } title={`${t( "labels.eyeDropper", )} — ${KEYS.I.toLocaleUpperCase()} or ${getShortcutKey("Alt")} `} > {eyeDropperIcon}
)}
); };