Skip to content

Commit f846d01

Browse files
authored
changed hex input for color picker to not require pressing enter to change (#239)
#227
1 parent e9a822b commit f846d01

File tree

2 files changed

+59
-4
lines changed

2 files changed

+59
-4
lines changed

src/components/ActivityButtons.tsx

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,24 @@
11
import {
22
Button,
33
ButtonGroup,
4+
ColorPicker,
45
Flex,
56
Group,
67
HStack,
78
Heading,
89
Input,
10+
Portal,
11+
Select,
912
Stack,
1013
Text,
1114
createListCollection,
1215
parseColor,
13-
ColorPicker,
14-
Select,
15-
Portal,
1616
} from "@chakra-ui/react";
1717
import type { ComponentPropsWithoutRef, FormEvent } from "react";
1818
import { useContext, useLayoutEffect, useState } from "react";
1919

20+
import { ColorPickerInput } from "./ui/colorpicker-input";
21+
2022
import { LuCheck as CheckIcon, LuX as CloseIcon } from "react-icons/lu";
2123
import { Checkbox } from "./ui/checkbox";
2224
import { Field } from "./ui/field";
@@ -213,7 +215,7 @@ function ActivityColor(props: { activity: Activity; onHide: () => void }) {
213215
>
214216
<ColorPicker.HiddenInput />
215217
<ColorPicker.Control>
216-
<ColorPicker.Input autoFocus />
218+
<ColorPickerInput autoFocus />
217219
<ColorPicker.Trigger />
218220
</ColorPicker.Control>
219221
<Portal>
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
import {
2+
ColorPicker,
3+
parseColor,
4+
useColorPickerContext,
5+
} from "@chakra-ui/react";
6+
import { forwardRef } from "react";
7+
8+
export const ColorPickerInput = forwardRef<
9+
HTMLInputElement,
10+
Omit<ColorPicker.ChannelInputProps, "channel">
11+
>(function ColorHexInput(props, ref) {
12+
const { setValue } = useColorPickerContext();
13+
14+
return (
15+
<ColorPicker.ChannelInput
16+
onChange={(e) => {
17+
const input = e.target.value;
18+
if (
19+
input.length === 6 ||
20+
(input.length === 7 && input.startsWith("#"))
21+
) {
22+
// parseColor will throw if the value is not a valid hex color
23+
try {
24+
let caretPositionBefore = e.target.selectionStart;
25+
let colorToParse = input;
26+
if (!colorToParse.startsWith("#")) {
27+
colorToParse = `#${colorToParse}`;
28+
caretPositionBefore = caretPositionBefore
29+
? caretPositionBefore + 1
30+
: caretPositionBefore;
31+
}
32+
setValue(parseColor(colorToParse));
33+
setTimeout(() => {
34+
try {
35+
e.target.setSelectionRange(
36+
caretPositionBefore,
37+
caretPositionBefore,
38+
);
39+
} catch (error) {
40+
console.error("Error setting selection range:", error);
41+
}
42+
}, 0);
43+
} catch {
44+
return;
45+
}
46+
}
47+
}}
48+
channel="hex"
49+
ref={ref}
50+
{...props}
51+
/>
52+
);
53+
});

0 commit comments

Comments
 (0)