"use client"; import { useLexicalComposerContext } from "@lexical/react/LexicalComposerContext"; import { LexicalTypeaheadMenuPlugin, MenuOption, type MenuTextMatch, } from "@lexical/react/LexicalTypeaheadMenuPlugin"; import { cn } from "@suphark/ui/lib/utils"; import { $insertNodes, type TextNode } from "lexical"; import { useCallback, useState } from "react"; import { createPortal } from "react-dom"; import { $createVariableNode } from "../nodes/variable-node"; import { useRichTextText } from "../rich-text-text"; import { fill } from "../rich-text-utils"; class VariableOption extends MenuOption { name: string; constructor(name: string) { super(name); this.name = name; } } /** * ตัวจับ `{{ชื่อ` (หรือ `{ชื่อ`) ท้ายข้อความ — `useBasicTypeaheadTriggerMatch("{{")` ของ lexical ใช้ trigger เป็น * character class (`[{{]` = ปีกกาตัวเดียว) และห้าม `{` ในชื่อ → พิมพ์ `{{` แล้วเมนูหายทุกครั้ง (บั๊กเดิมตั้งแต่ 0.93.0) */ const VARIABLE_TRIGGER = /(^|\s|\()(\{\{?([^{}\s.,!?;:'"()[\]]{0,75}))$/; export function matchVariableTrigger(text: string): MenuTextMatch | null { const match = VARIABLE_TRIGGER.exec(text); if (!match) return null; const leading = match[1] ?? ""; return { leadOffset: match.index + leading.length, matchingString: match[3] ?? "", replaceableString: match[2] ?? "", }; } /** พิมพ์ `{{ชื่อ` แล้วกด Enter = แทรกตัวแปร `{{ชื่อ}}` (เทมเพลตเอกสาร/อีเมล) */ export function VariableTypeaheadPlugin() { const [editor] = useLexicalComposerContext(); const t = useRichTextText(); const [queryString, setQueryString] = useState(null); const options = [new VariableOption(queryString || t.variableNew)]; const onSelectOption = useCallback( (_selectedOption: VariableOption, nodeToRemove: TextNode | null, closeMenu: () => void) => { editor.update(() => { nodeToRemove?.remove(); const variableName = queryString && queryString.trim().length > 0 ? queryString.trim() : "new_variable"; $insertNodes([$createVariableNode(variableName)]); }); closeMenu(); }, [editor, queryString], ); return ( onQueryChange={setQueryString} onSelectOption={onSelectOption} triggerFn={matchVariableTrigger} options={options} menuRenderFn={( anchorElementRef, { selectedIndex, selectOptionAndCleanUp, setHighlightedIndex }, ) => { if (anchorElementRef.current == null || options.length === 0) { return null; } return createPortal(
    {options.map((option, i) => (
  • setHighlightedIndex(i)} onClick={() => selectOptionAndCleanUp(option)} onKeyDown={() => {}} > {"{ }"} {fill(t.variableCreate, { name: queryString || "…" })}
  • ))}
, anchorElementRef.current, ); }} /> ); }