|
| 1 | +import { ChangeEvent, FocusEvent, useEffect, useRef, useState } from "react"; |
| 2 | + |
| 3 | +import { useCreateTheme } from "@/components/atoms/createTheme.atom"; |
| 4 | +import { useCreateHint } from "@/components/atoms/createHint.atom"; |
| 5 | + |
| 6 | +import { ThemeInfoTextAreaType } from "./TextAreaType"; |
| 7 | + |
| 8 | +const useTextArea = ({ |
| 9 | + id, |
| 10 | + content, |
| 11 | + checkErrorText, |
| 12 | +}: ThemeInfoTextAreaType) => { |
| 13 | + const [textAreaValue, setTextAreaValue] = useState<string>(content || ""); |
| 14 | + const [isFocus, setIsFocus] = useState<boolean>(false); |
| 15 | + const [errorText, setErrorText] = useState<string>(""); |
| 16 | + const textAreaRef = useRef<HTMLTextAreaElement>(null); |
| 17 | + const [, setCreateHint] = useCreateHint(); |
| 18 | + const [, setCreateTheme] = useCreateTheme(); |
| 19 | + |
| 20 | + useEffect(() => { |
| 21 | + if (errorText) return; |
| 22 | + setCreateTheme((prev) => ({ |
| 23 | + ...prev, |
| 24 | + [id]: textAreaValue, |
| 25 | + })); |
| 26 | + setCreateHint((prev) => ({ |
| 27 | + ...prev, |
| 28 | + [id]: textAreaValue, |
| 29 | + })); |
| 30 | + }, [textAreaValue, id, setCreateTheme, setCreateHint, errorText]); |
| 31 | + |
| 32 | + useEffect(() => { |
| 33 | + if (!isFocus || !textAreaRef.current) { |
| 34 | + setErrorText(""); |
| 35 | + return; |
| 36 | + } |
| 37 | + textAreaRef.current.focus(); |
| 38 | + }, [isFocus]); |
| 39 | + |
| 40 | + const handleTextAreaChange = (e: ChangeEvent<HTMLTextAreaElement>) => { |
| 41 | + const cur = e.target.value; |
| 42 | + const error = checkErrorText ? checkErrorText(cur) : ""; |
| 43 | + if (error) { |
| 44 | + setErrorText(error); |
| 45 | + setTextAreaValue(textAreaValue); |
| 46 | + return; |
| 47 | + } |
| 48 | + setErrorText(""); |
| 49 | + setTextAreaValue(cur); |
| 50 | + }; |
| 51 | + |
| 52 | + const handleTextAreaBlur = (e: FocusEvent<HTMLTextAreaElement>) => { |
| 53 | + if ( |
| 54 | + !e.relatedTarget || |
| 55 | + (e.relatedTarget.className !== "theme-info focus" && |
| 56 | + e.relatedTarget.className !== "theme-info error") |
| 57 | + ) { |
| 58 | + setIsFocus(false); |
| 59 | + return; |
| 60 | + } |
| 61 | + textAreaRef.current?.focus(); |
| 62 | + setIsFocus(true); |
| 63 | + }; |
| 64 | + |
| 65 | + return { |
| 66 | + textAreaValue, |
| 67 | + isFocus, |
| 68 | + setIsFocus, |
| 69 | + errorText, |
| 70 | + textAreaRef, |
| 71 | + handleTextAreaChange, |
| 72 | + handleTextAreaBlur, |
| 73 | + }; |
| 74 | +}; |
| 75 | + |
| 76 | +export default useTextArea; |
0 commit comments