"use client" /** * Type `@` in an email editor to insert a merge field. * * Opens a list at the caret as soon as `@` is typed (at the start of a line or after a * space). Keep typing to filter; ↑ ↓ move, Enter or Tab inserts, Esc closes. The same field * is also on the toolbar's "Insert field" menu for people who would rather click. */ import * as React from "react" import { createPortal } from "react-dom" import type { Editor } from "@tiptap/react" import { cn } from "../../lib/utils" import { mergeTagChipClass, type MergeField } from "./merge-tag" interface Open { query: string from: number to: number left: number top: number } // "@" opens the list at the start, after a space, or straight after a merge-field badge. const TRIGGER = /(?:^|[\s\u00a0\ufffc])@([\w ]{0,30})$/ export function useMergeTagSuggest(fields: MergeField[] | undefined) { const [open, setOpen] = React.useState(null) const [active, setActive] = React.useState(0) const editorRef = React.useRef(null) const listId = React.useId() const matches = React.useMemo(() => { if (!open || !fields) return [] const q = open.query.trim().toLowerCase() return fields.filter(f => !q || f.label.toLowerCase().includes(q) || f.key.toLowerCase().includes(q)) }, [open, fields]) // Stable handlers read the latest state through refs, so editor options never go stale. const live = React.useRef({ open, matches, active }) React.useLayoutEffect(() => { live.current = { open, matches, active } }) const attach = React.useCallback((editor: Editor | null) => { editorRef.current = editor }, []) const close = React.useCallback(() => setOpen(null), []) const update = React.useCallback( (editor: Editor) => { if (!fields || fields.length === 0 || !editor.isEditable) return setOpen(null) const { selection } = editor.state if (!selection.empty) return setOpen(null) const { $from } = selection const before = $from.parent.textBetween(0, $from.parentOffset, undefined, "") const match = TRIGGER.exec(before) if (!match) return setOpen(null) const caret = editor.view.coordsAtPos(selection.from) // Pure updater: the "new query" check reads the last committed state, not the setter. if (live.current.open?.query !== match[1]) setActive(0) setOpen({ query: match[1], from: selection.from - match[1].length - 1, to: selection.from, left: Math.min(caret.left, window.innerWidth - 296), top: caret.bottom + 6, }) }, [fields], ) const pick = React.useCallback((field: MergeField) => { const editor = editorRef.current const current = live.current.open if (!editor || !current) return editor .chain() .focus() .insertContentAt({ from: current.from, to: current.to }, [ { type: "mergeTag", attrs: { key: field.key } }, { type: "text", text: " " }, ]) .run() setOpen(null) }, []) /** Returns true when the key belonged to the list. */ const onKeyDown = React.useCallback( (event: KeyboardEvent) => { const { open: current, matches: list, active: index } = live.current if (!current || list.length === 0) return false if (event.key === "ArrowDown") { setActive((index + 1) % list.length) } else if (event.key === "ArrowUp") { setActive((index - 1 + list.length) % list.length) } else if (event.key === "Enter" || event.key === "Tab") { pick(list[index]) } else if (event.key === "Escape") { setOpen(null) } else { return false } event.preventDefault() return true }, [pick], ) // Esc belongs to the list while it is showing. Listen on window, in the capture phase, so the // rail or dialog behind it never sees the key and closes. const showing = Boolean(open) && matches.length > 0 React.useEffect(() => { if (!showing) return const onEscape = (event: KeyboardEvent) => { if (event.key !== "Escape") return event.stopPropagation() event.preventDefault() setOpen(null) } window.addEventListener("keydown", onEscape, true) return () => window.removeEventListener("keydown", onEscape, true) }, [showing]) const popup = open && matches.length > 0 && typeof document !== "undefined" ? createPortal(

Merge fields · filled in for each person

    {matches.map((field, index) => (
  • event.preventDefault()} onMouseEnter={() => setActive(index)} onClick={() => pick(field)} className={cn( "flex cursor-pointer flex-col gap-0.5 rounded-md px-2 py-1.5", index === active ? "bg-accent text-accent-foreground" : "hover:bg-interactive-hover", )} > @{field.label} {field.description ? ( {field.description} ) : null}
  • ))}
{matches.length} merge {matches.length === 1 ? "field" : "fields"} available. Use arrow keys and Enter.
, document.body, ) : null return { attach, update, close, onKeyDown, popup, listId, activeId: open && matches.length ? `${listId}-${active}` : undefined } }