import { useAjax } from "@/Hook/useAjax" import { txtLength } from "@/utils/utils"; import { Button, Input, InputRef, List, Popover } from "antd"; import React, { useEffect, useRef } from "react" import { useState } from "react"; import './index.less' import { getTextApi } from "@/services/adqV3/global"; import { SmileOutlined } from "@ant-design/icons"; import { emojiList } from "./const"; interface Props { value?: any, onChange?: (value: any) => void; style?: React.CSSProperties; placeholder?: string; maxTextLength?: number; isShowAjax?: boolean isSelectEmoji?: boolean } /** * 文案助手输入框 * @param props * @returns */ const TextAideInput: React.FC = (props) => { /************************/ const { value, onChange, style, placeholder, maxTextLength = 10, isShowAjax = true, isSelectEmoji = true } = props const [text, setText] = useState(value) const [descriptionShow, setDescriptionshow] = useState(false) const [cursorPosition, setCursorPosition] = useState(null); const inputRef = useRef(null); // 获取 input DOM 元素 const [emojiOpen, setEmojiOpen] = useState(false) const getTextLsit = useAjax((params) => getTextApi(params)) /************************/ useEffect(() => { setText(value) }, [value]) // 文案助手 const textList = (keyword?: any) => { getTextLsit.run({ keyword, maxTextLength }) } const insertTextAtCursor = (emoji: string) => { const inputElement = inputRef.current; if (inputElement) { if (cursorPosition !== null) { const newValue = text.slice(0, cursorPosition) + emoji + text.slice(cursorPosition); setText(newValue); onChange?.(newValue) } else { const newValue = text + emoji setText(newValue); onChange?.(newValue) } const newCursorPosition = (cursorPosition || text.length) + emoji.length; setCursorPosition(newCursorPosition); // 等待状态更新后再设置光标位置 setTimeout(() => { inputElement.setSelectionRange(newCursorPosition, newCursorPosition); inputElement.focus(); }, 0); } }; return
{ setText(item.text) onChange && onChange(item.text) setTimeout(() => { setDescriptionshow(false) }, 50) }}>{item.text}{item.tag && {'CTR 高'}}} />} > { if (isShowAjax) { setDescriptionshow(true) textList(value) } }} onBlur={(e) => { setCursorPosition(e.target.selectionStart) if (!emojiOpen) { setTimeout(() => { setDescriptionshow(false) }, 0) } }} onChange={(e) => { let value = e.target.value setText(value) if (isShowAjax) { textList(value) } onChange && onChange(value) }} allowClear /> {isSelectEmoji &&
    {emojiList.map(item =>
  • insertTextAtCursor(item.text)}>{item.text}
  • )}
} trigger="click" onOpenChange={(e) => { setEmojiOpen(e) }} > } {`${txtLength(text)}/${maxTextLength}`} } export default React.memo(TextAideInput)