Skip to content

Commit

Permalink
fix(ColorEditor): fix rgb to other colors conversion
Browse files Browse the repository at this point in the history
  • Loading branch information
nurikk committed Oct 2, 2022
1 parent ba978e0 commit 8a7fa80
Showing 1 changed file with 11 additions and 24 deletions.
35 changes: 11 additions & 24 deletions src/components/color-editor/color-editor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ type Payload = AnyColor;
export type ColorFormat = "color_xy" | "color_hs";
type ColorProps = {
value: Payload;
steps?: string[];
steps?: string[][];
format: ColorFormat;
onChange(value: Record<string, unknown>): void;
minimal?: boolean;
Expand Down Expand Up @@ -37,52 +37,39 @@ export const toRGB = (source: AnyColor, sourceFormat: ColorFormat): string => {
}
}

const rgbToTargetFormat = (source: string, targetFormat: ColorFormat): Record<string, unknown> => {
switch (targetFormat) {
case "color_hs":
const [hue, saturation] = convertColors.hex.hsv(source);
return { hue, saturation };


case "color_xy":
const [X, Y, Z] = convertColors.hex.xyz(source);
const x = X / (X + Y + Z);
const y = Y / (X + Y + Z);
return { x, y };
const whitePallet = ['#FFFFFF', '#FDF4DC', '#F4FDFF'];
const pridePallet = ['#FF0018', '#FFA52C', '#FFFF41', '#008018', '#0000F9', '#86007D'];

default:
return { hex: source };
}

}
const pridePallet = ['#FF0018', '#FFA52C', '#FFFF41', '#008018', '#0000F9', '#86007D'];
const ColorEditor: FunctionComponent<ColorProps & Omit<InputHTMLAttributes<HTMLInputElement>, 'onChange' | 'value'>> = (props) => {

const { onChange, value = {} as AnyColor, format, steps = pridePallet, minimal, ...rest } = props;
const { onChange, value = {} as AnyColor, format, steps = [pridePallet, whitePallet], minimal, ...rest } = props;
const [currentColor, setCurrentColor] = useState<string>(toRGB(value, format));
useEffect(() => {
setCurrentColor(toRGB(value, format))
}, [value, format]);
return <>
{!minimal && <div className="btn-group me-2 float-start">
{!minimal && steps.map((pallet, idx) => <div key={idx} className="btn-group me-2 float-start border">
{
steps.map(step => <Button<string>
pallet.map(step => <Button<string>
className="btn"
style={{ backgroundColor: step }}
key={step}
item={step}
title={step}
onClick={(item) => onChange(rgbToTargetFormat(item, format))}>&nbsp;&nbsp;&nbsp;</Button>)
onClick={(item) => onChange({ hex: item })}>&nbsp;&nbsp;&nbsp;</Button>
)
}
</div>}
</div>)}

<input
type="color"
className="form-control form-control-color"
value={currentColor}
style={{ minWidth: 40 }}
onChange={e => {
if (e.target.value.toLowerCase() !== currentColor.toLowerCase()) {
onChange(rgbToTargetFormat(e.target.value, format))
onChange({ hex: e.target.value })
}
}}

Expand Down

0 comments on commit 8a7fa80

Please sign in to comment.