|
1 | | -import { useId } from "react"; |
2 | | -import PropTypes from "prop-types"; |
| 1 | +import { useId, useEffect, useRef, useState } from "react"; |
| 2 | +import Coloris from "@melloware/coloris"; |
| 3 | +import setter from "../setter"; |
3 | 4 | import * as Styled from "./styles"; |
4 | 5 |
|
5 | | -export default function ColorInput({ defaultValue, ...props }) { |
| 6 | +function ColorInput({ defaultValue, ...props }) { |
6 | 7 | const id = useId(); |
| 8 | + const inputRef = useRef(); |
| 9 | + const colorRef = useRef(props.value || defaultValue); |
7 | 10 |
|
8 | | - const renderValue = value => value ?? defaultValue; |
| 11 | + const inputId = `color-input-${id}`; |
| 12 | + |
| 13 | + useEffect(() => { |
| 14 | + Coloris.init(); |
| 15 | + |
| 16 | + document.addEventListener("coloris:pick", event => { |
| 17 | + const isTarget = event.detail.currentEl.id === inputId; |
| 18 | + if (isTarget) colorRef.current = event.detail.color; |
| 19 | + }); |
| 20 | + }, [inputId]); |
| 21 | + |
| 22 | + useEffect(() => { |
| 23 | + if (inputRef.current) { |
| 24 | + Coloris({ |
| 25 | + el: inputRef.current, |
| 26 | + format: "mixed", |
| 27 | + formatToggle: true, |
| 28 | + themeMode: "dark", |
| 29 | + clearButton: true, |
| 30 | + closeButton: true, |
| 31 | + defaultColor: defaultValue, |
| 32 | + margin: 5 |
| 33 | + }); |
| 34 | + |
| 35 | + inputRef.current.addEventListener("close", () => { |
| 36 | + props.onChange({ target: { value: colorRef.current } }); |
| 37 | + }); |
| 38 | + } |
| 39 | + }, [inputRef, defaultValue, colorRef, props.onChange]); |
| 40 | + |
| 41 | + console.log(props.placeholder); |
| 42 | + |
| 43 | + const renderValue = () => colorRef.current || defaultValue; |
9 | 44 | return ( |
10 | 45 | <Styled.ColorInput |
11 | | - inputType="color" |
12 | | - id={`color-input-${id}`} |
| 46 | + id={inputId} |
| 47 | + colorRef={inputRef} |
13 | 48 | idForError={`color-input-error-${id}`} |
14 | 49 | idForInstructions={`color-input-instructions-${id}`} |
15 | | - renderValue={renderValue} |
| 50 | + placeholder={defaultValue} |
| 51 | + // renderValue={renderValue} |
16 | 52 | {...props} |
| 53 | + $defaultColor={defaultValue} |
17 | 54 | /> |
18 | 55 | ); |
19 | 56 | } |
20 | 57 |
|
| 58 | +export default setter(ColorInput); |
| 59 | + |
21 | 60 | ColorInput.displayName = "Form.ColorInput"; |
0 commit comments