Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 6 additions & 4 deletions src/components/ActivityButtons.tsx
Original file line number Diff line number Diff line change
@@ -1,22 +1,24 @@
import {
Button,
ButtonGroup,
ColorPicker,
Flex,
Group,
HStack,
Heading,
Input,
Portal,
Select,
Stack,
Text,
createListCollection,
parseColor,
ColorPicker,
Select,
Portal,
} from "@chakra-ui/react";
import type { ComponentPropsWithoutRef, FormEvent } from "react";
import { useContext, useLayoutEffect, useState } from "react";

import { ColorPickerInput } from "./ui/colorpicker-input";

import { LuCheck as CheckIcon, LuX as CloseIcon } from "react-icons/lu";
import { Checkbox } from "./ui/checkbox";
import { Field } from "./ui/field";
Expand Down Expand Up @@ -213,7 +215,7 @@ function ActivityColor(props: { activity: Activity; onHide: () => void }) {
>
<ColorPicker.HiddenInput />
<ColorPicker.Control>
<ColorPicker.Input autoFocus />
<ColorPickerInput autoFocus />
<ColorPicker.Trigger />
</ColorPicker.Control>
<Portal>
Expand Down
53 changes: 53 additions & 0 deletions src/components/ui/colorpicker-input.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import {
ColorPicker,
parseColor,
useColorPickerContext,
} from "@chakra-ui/react";
import { forwardRef } from "react";

export const ColorPickerInput = forwardRef<
HTMLInputElement,
Omit<ColorPicker.ChannelInputProps, "channel">
>(function ColorHexInput(props, ref) {
const { setValue } = useColorPickerContext();

return (
<ColorPicker.ChannelInput
onChange={(e) => {
const input = e.target.value;
if (
input.length === 6 ||
(input.length === 7 && input.startsWith("#"))
) {
// parseColor will throw if the value is not a valid hex color
try {
let caretPositionBefore = e.target.selectionStart;
let colorToParse = input;
if (!colorToParse.startsWith("#")) {
colorToParse = `#${colorToParse}`;
caretPositionBefore = caretPositionBefore
? caretPositionBefore + 1
: caretPositionBefore;
}
setValue(parseColor(colorToParse));
setTimeout(() => {
try {
e.target.setSelectionRange(
caretPositionBefore,
caretPositionBefore,
);
} catch (error) {
console.error("Error setting selection range:", error);
}
}, 0);
} catch {
return;
}
}
}}
channel="hex"
ref={ref}
{...props}
/>
);
});