Skip to content

Commit 37c81fd

Browse files
committed
feat: validate the color input field
1 parent d4394c2 commit 37c81fd

File tree

4 files changed

+17
-2
lines changed

4 files changed

+17
-2
lines changed

packages/keybr-theme-designer/lib/design/input/color/ColorInput.tsx

+7-2
Original file line numberDiff line numberDiff line change
@@ -5,16 +5,18 @@ import type { ColorEditorProps } from "./types.ts";
55

66
export function ColorInput({ color, onChange }: ColorEditorProps) {
77
const focus = useRef(false);
8+
const [error, setError] = useState("");
89
const [value, setValue] = useState("");
910
useEffect(() => {
1011
if (!focus.current) {
11-
setValue(String(color.toRgb()));
12+
setValue(color.toRgb().formatHex());
1213
}
1314
}, [color]);
1415
return (
1516
<TextField
1617
size="full"
17-
placeholder="hex, rgb, hsl, etc..."
18+
placeholder="hex, rgb(...), hsl(...), etc"
19+
error={error}
1820
value={value}
1921
onChange={setValue}
2022
onFocus={() => {
@@ -24,7 +26,10 @@ export function ColorInput({ color, onChange }: ColorEditorProps) {
2426
focus.current = false;
2527
const color = tryParseColor(value);
2628
if (color != null) {
29+
setError("");
2730
onChange(color);
31+
} else {
32+
setError("Invalid color. We accept hex, rgb(...), hsl(...), etc.");
2833
}
2934
}}
3035
/>

packages/keybr-widget/lib/components/textfield/TextField.module.less

+4
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,10 @@
1717
outline: none;
1818
}
1919

20+
.root:invalid {
21+
color: var(--error);
22+
}
23+
2024
input.root {
2125
display: inline-block;
2226
min-block-size: @field-height;

packages/keybr-widget/lib/components/textfield/TextField.tsx

+5
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import {
44
forwardRef,
55
type ReactNode,
66
type RefObject,
7+
useEffect,
78
useImperativeHandle,
89
useRef,
910
} from "react";
@@ -14,6 +15,7 @@ import { type TextFieldProps, type TextFieldRef } from "./TextField.types.ts";
1415
export const TextField = forwardRef(function TextField(
1516
{
1617
disabled,
18+
error,
1719
maxLength,
1820
name,
1921
placeholder,
@@ -42,6 +44,9 @@ export const TextField = forwardRef(function TextField(
4244
element.current?.select();
4345
},
4446
}));
47+
useEffect(() => {
48+
element.current?.setCustomValidity(error ?? "");
49+
}, [error]);
4550
if (type === "textarea") {
4651
return (
4752
<textarea

packages/keybr-widget/lib/components/textfield/TextField.types.ts

+1
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import {
1010
export type TextFieldType = "text" | "textarea" | "email" | "url" | "password";
1111

1212
export type TextFieldProps = {
13+
readonly error?: string | null;
1314
readonly maxLength?: number;
1415
readonly name?: string;
1516
readonly placeholder?: string;

0 commit comments

Comments
 (0)