{"$schema":"https://ui.shadcn.com/schema/registry-item.json","name":"rich-text-editor","type":"registry:ui","title":"Rich Text Editor","description":"Formatted text with a toolbar, keyboard shortcuts and markdown as you type; its value is HTML for forms.","dependencies":["@tiptap/core","@tiptap/extensions","@tiptap/react","@tiptap/starter-kit","lucide-react","radix-ui"],"registryDependencies":["https://dashral.com/r/utils.json","https://dashral.com/r/lib-locale.json","https://dashral.com/r/button.json","https://dashral.com/r/dropdown-menu.json","https://dashral.com/r/field.json","https://dashral.com/r/input.json","https://dashral.com/r/kbd.json","https://dashral.com/r/popover.json","https://dashral.com/r/prose.json","https://dashral.com/r/scroll-shadow.json","https://dashral.com/r/toggle.json","https://dashral.com/r/tooltip.json"],"files":[{"path":"registry/dashral/rich-text-editor.tsx","type":"registry:file","target":"components/dashral/rich-text-editor.tsx","content":"\"use client\"\n\nimport * as React from \"react\"\nimport { Toolbar as ToolbarPrimitive } from \"radix-ui\"\nimport { EditorContent, useEditor, useEditorState, type Editor } from \"@tiptap/react\"\nimport type { AnyExtension, JSONContent } from \"@tiptap/core\"\nimport StarterKit from \"@tiptap/starter-kit\"\nimport { CharacterCount, Placeholder } from \"@tiptap/extensions\"\nimport {\n  BoldIcon,\n  ChevronDownIcon,\n  CodeIcon,\n  Heading1Icon,\n  Heading2Icon,\n  Heading3Icon,\n  Heading4Icon,\n  ItalicIcon,\n  LinkIcon,\n  ListIcon,\n  ListOrderedIcon,\n  QuoteIcon,\n  Redo2Icon,\n  StrikethroughIcon,\n  TypeIcon,\n  UnderlineIcon,\n  Undo2Icon,\n} from \"lucide-react\"\n\nimport { useLocale, type MessageKey } from \"./lib/locale\"\nimport { cn } from \"./lib/utils\"\nimport { Button } from \"./button\"\nimport { DropdownMenu } from \"./dropdown-menu\"\nimport { FieldWrapper, splitFieldProps, useFieldControl, type FieldClassNames, type FieldOwnProps } from \"./field\"\nimport { Input } from \"./input\"\nimport { describeKey, useAppleKeyboard } from \"./kbd\"\nimport { PopoverContent, PopoverRoot, PopoverTrigger } from \"./popover\"\nimport { proseClasses } from \"./prose\"\nimport { ScrollShadow } from \"./scroll-shadow\"\nimport { toggleVariants } from \"./toggle\"\nimport { Tooltip } from \"./tooltip\"\n\n/** A tool in the toolbar, in the order given; \"|\" draws a divider between groups. */\ntype RichTextTool =\n  | \"heading\"\n  | \"bold\"\n  | \"italic\"\n  | \"underline\"\n  | \"strike\"\n  | \"code\"\n  | \"bulletList\"\n  | \"orderedList\"\n  | \"blockquote\"\n  | \"link\"\n  | \"undo\"\n  | \"redo\"\n  | \"|\"\n\ntype HeadingLevel = 1 | 2 | 3 | 4\n\nconst defaultTools: RichTextTool[] = [\n  \"heading\",\n  \"|\",\n  \"bold\",\n  \"italic\",\n  \"underline\",\n  \"strike\",\n  \"code\",\n  \"|\",\n  \"bulletList\",\n  \"orderedList\",\n  \"blockquote\",\n  \"|\",\n  \"link\",\n  \"undo\",\n  \"redo\",\n]\n\ntype RichTextEditorClassNames = FieldClassNames & {\n  /** The box around the toolbar and the text. */\n  editor?: string\n  toolbar?: string\n  /** The area you write in, e.g. a min-h-* or max-h-* (it scrolls past a max height). */\n  content?: string\n}\n\ntype RichTextEditorProps = Omit<React.ComponentProps<\"div\">, \"defaultValue\" | \"onChange\" | \"children\"> &\n  FieldOwnProps & {\n    /** The content as HTML. With onValueChange, it controls the editor; \"\" is empty. */\n    value?: string\n    /** The starting content, as HTML or Tiptap JSON, when value isn't used. */\n    defaultValue?: string | JSONContent\n    /** Called as the content changes, with the HTML (\"\" when empty); the editor gives JSON (editor.getJSON()) or text. */\n    onValueChange?: (html: string, editor: Editor) => void\n    /** Sends the HTML with a form, in a hidden input of this name. */\n    name?: string\n    placeholder?: string\n    /** Stops typing and pasting past this many characters; the count shows near the end. */\n    maxLength?: number\n    /** Always shows the character count under the text (\"120/500\" with maxLength). */\n    showCount?: boolean\n    /** The tools, in order; false hides the toolbar (the markdown shortcuts still work). */\n    toolbar?: RichTextTool[] | false\n    /** The heading levels in the heading menu. */\n    headings?: HeadingLevel[]\n    /** Controls added at the end of the toolbar, e.g. an \"Insert template\" button. */\n    actions?: React.ReactNode\n    disabled?: boolean\n    /** Shows the content without letting it be changed; the toolbar hides. */\n    readOnly?: boolean\n    required?: boolean\n    autoFocus?: boolean\n    /** More Tiptap extensions, after the built-in ones (open-source Tiptap extensions work). */\n    extensions?: AnyExtension[]\n    /** The Tiptap editor, once it exists: for commands of your own (editor.chain().focus()…). */\n    editorRef?: React.Ref<Editor | null>\n    classNames?: RichTextEditorClassNames\n  }\n\n/**\n * A rich text field in one tag: headings, bold, italic, lists, quotes and links from a toolbar, the keyboard (⌘B) or\n * markdown as you type (## , - , > , **bold**). Its value is HTML, so it works in forms and with a label, hint and\n * error like any field. Built on Tiptap.\n */\nfunction RichTextEditor(props: RichTextEditorProps) {\n  const [field, control] = splitFieldProps(props)\n  return (\n    // As a group, the label names the editor through aria-labelledby: a <label for> can't name an editable div.\n    <FieldWrapper {...field} group classNames={{ ...field.classNames, root: cn(\"gap-2\", field.classNames?.root) }}>\n      <RichTextEditorControl {...control} />\n    </FieldWrapper>\n  )\n}\n\n/** \"\", or the editor's HTML: an empty editor is \"<p></p>\" to Tiptap, but empty to a form. */\nconst htmlOf = (editor: Editor) => (editor.isEmpty ? \"\" : editor.getHTML())\n\n/** A link as typed, made whole (\"example.com\" → \"https://example.com\"), or null when it isn't safe to follow. */\nfunction normalizeHref(input: string) {\n  const href = input.trim()\n  if (!href) return null\n  if (/^(#|\\/|\\.\\/|\\.\\.\\/)/.test(href)) return href\n  const scheme = /^([a-z][a-z0-9+.-]*):/i.exec(href)?.[1]?.toLowerCase()\n  if (scheme) return [\"http\", \"https\", \"mailto\", \"tel\"].includes(scheme) ? href : null\n  if (/^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(href)) return `mailto:${href}`\n  if (/\\s/.test(href) || !href.includes(\".\")) return null\n  return `https://${href}`\n}\n\nconst headingIcons = { 0: TypeIcon, 1: Heading1Icon, 2: Heading2Icon, 3: Heading3Icon, 4: Heading4Icon }\n\ntype MarkTool = Exclude<RichTextTool, \"heading\" | \"link\" | \"|\">\n\nconst marks: Record<MarkTool, { icon: React.ComponentType; label: MessageKey; keys: string[]; flip?: boolean }> = {\n  bold: { icon: BoldIcon, label: \"bold\", keys: [\"mod\", \"B\"] },\n  italic: { icon: ItalicIcon, label: \"italic\", keys: [\"mod\", \"I\"] },\n  underline: { icon: UnderlineIcon, label: \"underline\", keys: [\"mod\", \"U\"] },\n  strike: { icon: StrikethroughIcon, label: \"strikethrough\", keys: [\"mod\", \"shift\", \"S\"] },\n  code: { icon: CodeIcon, label: \"inlineCode\", keys: [\"mod\", \"E\"] },\n  bulletList: { icon: ListIcon, label: \"bulletList\", keys: [\"mod\", \"shift\", \"8\"] },\n  orderedList: { icon: ListOrderedIcon, label: \"numberedList\", keys: [\"mod\", \"shift\", \"7\"] },\n  blockquote: { icon: QuoteIcon, label: \"quote\", keys: [\"mod\", \"shift\", \"B\"] },\n  undo: { icon: Undo2Icon, label: \"undo\", keys: [\"mod\", \"Z\"], flip: true },\n  redo: { icon: Redo2Icon, label: \"redo\", keys: [\"mod\", \"shift\", \"Z\"], flip: true },\n}\n\nfunction run(editor: Editor, tool: MarkTool) {\n  const chain = editor.chain().focus()\n  const commands = {\n    bold: () => chain.toggleBold(),\n    italic: () => chain.toggleItalic(),\n    underline: () => chain.toggleUnderline(),\n    strike: () => chain.toggleStrike(),\n    code: () => chain.toggleCode(),\n    bulletList: () => chain.toggleBulletList(),\n    orderedList: () => chain.toggleOrderedList(),\n    blockquote: () => chain.toggleBlockquote(),\n    undo: () => chain.undo(),\n    redo: () => chain.redo(),\n  }\n  commands[tool]().run()\n}\n\n// The placeholder sits on the empty first paragraph, in the text's own place (start side, right to left included).\nconst placeholderClasses =\n  \"[&_.is-editor-empty:first-child]:before:pointer-events-none [&_.is-editor-empty:first-child]:before:float-start [&_.is-editor-empty:first-child]:before:h-0 [&_.is-editor-empty:first-child]:before:text-muted-foreground [&_.is-editor-empty:first-child]:before:content-[attr(data-placeholder)]\"\n\nfunction RichTextEditorControl({\n  value,\n  defaultValue,\n  onValueChange,\n  name,\n  placeholder,\n  maxLength,\n  showCount,\n  toolbar = defaultTools,\n  headings = [1, 2, 3],\n  actions,\n  disabled,\n  readOnly,\n  required,\n  autoFocus,\n  extensions: extraExtensions,\n  editorRef,\n  classNames,\n  className,\n  id,\n  \"aria-describedby\": ariaDescribedBy,\n  \"aria-labelledby\": ariaLabelledBy,\n  \"aria-invalid\": ariaInvalid,\n  \"aria-label\": ariaLabel,\n  ...props\n}: Omit<RichTextEditorProps, keyof FieldOwnProps>) {\n  const { t } = useLocale()\n  const field = useFieldControl({ id, disabled, required, \"aria-describedby\": ariaDescribedBy, \"aria-labelledby\": ariaLabelledBy, \"aria-invalid\": ariaInvalid })\n  const editable = !field.disabled && !readOnly\n  const [linkOpen, setLinkOpen] = React.useState(false)\n  const toolbarRef = React.useRef<HTMLDivElement>(null)\n  const tools = toolbar === false || readOnly ? [] : toolbar\n  const hasLink = tools.includes(\"link\")\n\n  // The latest of what the editor calls back into, read when it calls: the editor itself is made once.\n  const latest = React.useRef({ onValueChange, placeholder, hasLink })\n  React.useLayoutEffect(() => {\n    latest.current = { onValueChange, placeholder, hasLink }\n  })\n  const [html, setHtml] = React.useState(() => (typeof (value ?? defaultValue) === \"string\" ? ((value ?? defaultValue) as string) : \"\"))\n\n  const headingsKey = headings.join()\n  const extensions = React.useMemo(\n    () => [\n      StarterKit.configure({\n        heading: { levels: headingsKey.split(\",\").map(Number) as HeadingLevel[] },\n        link: { openOnClick: false, autolink: true, defaultProtocol: \"https\", HTMLAttributes: { rel: \"noopener noreferrer nofollow\", target: null } },\n        // The kit's look, not ProseMirror's blue drop line.\n        dropcursor: { color: \"var(--color-ring)\", width: 2 },\n        // No empty paragraph slipped in after a list or quote: it grew the box and made Undo live before any change.\n        trailingNode: false,\n      }),\n      Placeholder.configure({ placeholder: () => latest.current.placeholder ?? \"\" }),\n      CharacterCount.configure({ limit: maxLength ?? null }),\n      ...(extraExtensions ?? []),\n    ],\n    [headingsKey, maxLength, extraExtensions]\n  )\n\n  const attributes = {\n    ...(field.id && { id: field.id }),\n    role: \"textbox\",\n    \"aria-multiline\": \"true\",\n    ...(ariaLabel && { \"aria-label\": ariaLabel }),\n    ...(field[\"aria-labelledby\"] && { \"aria-labelledby\": field[\"aria-labelledby\"] }),\n    ...(field[\"aria-describedby\"] && { \"aria-describedby\": field[\"aria-describedby\"] }),\n    ...(field[\"aria-invalid\"] && { \"aria-invalid\": \"true\" }),\n    ...(field.required && { \"aria-required\": \"true\" }),\n    ...(!editable && { \"aria-readonly\": \"true\" }),\n    ...(field.disabled && { \"aria-disabled\": \"true\" }),\n    class: proseClasses(\n      \"sm\",\n      cn(\n        // 16px on phones, so iOS doesn't zoom in on focus.\n        \"min-h-32 px-3 py-2.5 outline-none max-md:text-base max-md:leading-7\",\n        placeholderClasses,\n        (showCount || maxLength !== undefined) && \"pb-7\",\n        classNames?.content\n      )\n    ),\n  }\n\n  const editor = useEditor(\n    {\n      extensions,\n      content: value ?? defaultValue ?? \"\",\n      editable,\n      autofocus: autoFocus ? \"end\" : false,\n      // Made in the browser after hydration: the server has no editor to draw.\n      immediatelyRender: false,\n      shouldRerenderOnTransaction: false,\n      editorProps: {\n        attributes,\n        handleKeyDown: (_view, event) => {\n          // ⌘K / Ctrl+K: the link panel. Alt+F10: to the toolbar, as in other editors.\n          if ((event.metaKey || event.ctrlKey) && !event.altKey && event.key.toLowerCase() === \"k\" && latest.current.hasLink) {\n            event.preventDefault()\n            setLinkOpen(true)\n            return true\n          }\n          if (event.altKey && event.key === \"F10\") {\n            const first = toolbarRef.current?.querySelector<HTMLElement>(\"button:not([disabled])\")\n            if (first) {\n              event.preventDefault()\n              first.focus()\n              return true\n            }\n          }\n          return false\n        },\n      },\n      onUpdate: ({ editor }) => {\n        const next = htmlOf(editor)\n        setHtml(next)\n        latest.current.onValueChange?.(next, editor)\n      },\n    },\n    [extensions]\n  )\n\n  // The aria attributes follow the field (an error that appears after a submit), and the classes their props.\n  const attributesKey = JSON.stringify(attributes)\n  React.useEffect(() => {\n    if (!editor || editor.isDestroyed) return\n    editor.setOptions({ editorProps: { ...editor.options.editorProps, attributes: JSON.parse(attributesKey) } })\n  }, [editor, attributesKey])\n\n  React.useEffect(() => {\n    if (editor && !editor.isDestroyed && editor.isEditable !== editable) editor.setEditable(editable, false)\n  }, [editor, editable])\n\n  // A controlled value that changed from outside (a reset, a loaded draft) replaces the content, without calling back.\n  React.useEffect(() => {\n    if (!editor || editor.isDestroyed || value === undefined || value === htmlOf(editor)) return\n    editor.commands.setContent(value || \"\", { emitUpdate: false })\n    setHtml(value)\n  }, [editor, value])\n\n  React.useImperativeHandle<Editor | null, Editor | null>(editorRef, () => editor, [editor])\n\n  // A click on the label writes in the editor, as it would in a text field.\n  const labelId = field[\"aria-labelledby\"]\n  React.useEffect(() => {\n    const label = labelId ? document.getElementById(labelId) : null\n    if (!label || !editor) return\n    const focus = () => editor.commands.focus()\n    label.addEventListener(\"click\", focus)\n    return () => label.removeEventListener(\"click\", focus)\n  }, [labelId, editor])\n\n  const state = useEditorState({\n    editor,\n    selector: ({ editor }) => {\n      if (!editor) return null\n      return {\n        heading: (headingsKey.split(\",\").map(Number).find((level) => editor.isActive(\"heading\", { level })) ?? 0) as 0 | HeadingLevel,\n        active: Object.fromEntries(([\"bold\", \"italic\", \"underline\", \"strike\", \"code\", \"bulletList\", \"orderedList\", \"blockquote\", \"link\"] as const).map((name) => [name, editor.isActive(name)])) as Record<string, boolean>,\n        canUndo: editor.can().undo(),\n        canRedo: editor.can().redo(),\n        characters: editor.storage.characterCount.characters() as number,\n      }\n    },\n  })\n\n  const characters = state?.characters ?? 0\n  const left = maxLength === undefined ? Infinity : maxLength - characters\n  // Quiet until the last tenth (at least 20 characters), like the prompt composer, unless asked to show always.\n  const countShown = showCount || (maxLength !== undefined && left <= Math.max(20, Math.round(maxLength / 10)))\n  const countText = maxLength === undefined ? String(characters) : showCount ? `${characters}/${maxLength}` : String(left)\n  const countLabel = maxLength === undefined ? t(\"characterCount\", { count: characters }) : t(\"charactersLeft\", { count: left })\n\n  // Undo and redo sit at the far end when they close the list.\n  const trailing = (() => {\n    let i = tools.length\n    while (i > 0 && (tools[i - 1] === \"undo\" || tools[i - 1] === \"redo\")) i--\n    return i\n  })()\n\n  const items = tools.map((tool, i) => {\n    if (tool === \"|\") {\n      if (tools[i + 1] === undefined || i + 1 === trailing) return null\n      return <ToolbarPrimitive.Separator key={i} className=\"mx-1 h-5 w-px shrink-0 bg-border\" />\n    }\n    const end = i === trailing && i > 0 ? \"ms-auto\" : undefined\n    if (tool === \"heading\") {\n      return (\n        <HeadingMenu key={i} editor={editor} level={state?.heading ?? 0} levels={headings} disabled={!editable} />\n      )\n    }\n    if (tool === \"link\") {\n      return (\n        <LinkTool key={i} editor={editor} open={linkOpen} onOpenChange={setLinkOpen} active={state?.active.link ?? false} disabled={!editable} />\n      )\n    }\n    const mark = marks[tool]\n    const pressable = tool !== \"undo\" && tool !== \"redo\"\n    const can = tool === \"undo\" ? state?.canUndo : tool === \"redo\" ? state?.canRedo : true\n    const on = pressable && Boolean(state?.active[tool])\n    return (\n      <ToolTip key={i} label={t(mark.label)} keys={mark.keys}>\n        <ToolbarPrimitive.Button\n          type=\"button\"\n          aria-label={t(mark.label)}\n          aria-pressed={pressable ? on : undefined}\n          data-state={pressable ? (on ? \"on\" : \"off\") : undefined}\n          disabled={!editable || !can}\n          onClick={() => editor && run(editor, tool)}\n          className={cn(toolClass, mark.flip && \"[&_svg]:rtl:-scale-x-100\", end)}\n        >\n          <mark.icon />\n        </ToolbarPrimitive.Button>\n      </ToolTip>\n    )\n  })\n\n  return (\n    <div\n      data-slot=\"rich-text-editor\"\n      data-disabled={field.disabled || undefined}\n      data-invalid={field[\"aria-invalid\"] ? true : undefined}\n      data-readonly={readOnly || undefined}\n      className={cn(\n        \"relative flex w-full min-w-0 flex-col rounded-lg border border-input bg-transparent shadow-xs transition-[color,box-shadow,border-color]\",\n        \"focus-within:border-ring focus-within:ring-2 focus-within:ring-ring/15\",\n        \"data-[invalid]:border-destructive data-[invalid]:ring-destructive/15\",\n        \"data-[disabled]:cursor-not-allowed data-[disabled]:opacity-50\",\n        \"data-[readonly]:bg-muted/50\",\n        className,\n        classNames?.editor\n      )}\n      {...props}\n    >\n      {(tools.length > 0 || actions) && (\n        <ScrollShadow orientation=\"horizontal\" size={24} className=\"shrink-0 border-b\">\n          <ToolbarPrimitive.Root\n            ref={toolbarRef}\n            aria-label={t(\"formatting\")}\n            aria-controls={field.id}\n            className={cn(\"flex w-max min-w-full items-center gap-0.5 p-1\", classNames?.toolbar)}\n          >\n            {items}\n            {actions && <div className={cn(\"flex shrink-0 items-center gap-0.5\", trailing === tools.length && \"ms-auto\")}>{actions}</div>}\n          </ToolbarPrimitive.Root>\n        </ScrollShadow>\n      )}\n      <div className=\"relative min-w-0 flex-1 overflow-y-auto\">\n        {editor ? (\n          <EditorContent editor={editor} />\n        ) : (\n          // Until the editor exists (one frame after hydration), the same box, so nothing moves when it arrives.\n          <div aria-hidden className={attributes.class}>\n            {placeholder && !html && <p className=\"text-muted-foreground\">{placeholder}</p>}\n          </div>\n        )}\n      </div>\n      {(showCount || maxLength !== undefined) && (\n        <span\n          className={cn(\n            \"pointer-events-none absolute end-3 bottom-2 text-xs tabular-nums transition-opacity duration-(--duration-fast)\",\n            countShown ? \"opacity-100\" : \"opacity-0\",\n            left <= 0 ? \"text-destructive-text\" : \"text-muted-foreground\"\n          )}\n        >\n          <span aria-hidden>{countText}</span>\n          <span className=\"sr-only\" aria-live=\"polite\">\n            {countShown ? countLabel : \"\"}\n          </span>\n        </span>\n      )}\n      {name && <input type=\"hidden\" name={name} value={html} disabled={field.disabled} />}\n    </div>\n  )\n}\n\nconst toolClass = toggleVariants({ size: \"sm\", color: \"neutral\", className: \"rounded-sm px-0\" })\n\n/** A tool's name and its keys, on hover and keyboard focus. */\nfunction ToolTip({ label, keys, children, ...props }: { label: string; keys?: string[]; children: React.ReactElement }) {\n  const apple = useAppleKeyboard()\n  return (\n    <Tooltip\n      {...props}\n      content={\n        <span className=\"flex items-center gap-2\">\n          {label}\n          {keys && (\n            <span aria-hidden className=\"opacity-60\">\n              {keys.map((key) => describeKey(key, apple).label).join(apple ? \"\" : \"+\")}\n            </span>\n          )}\n        </span>\n      }\n    >\n      {children}\n    </Tooltip>\n  )\n}\n\nfunction HeadingMenu({ editor, level, levels, disabled }: { editor: Editor | null; level: 0 | HeadingLevel; levels: HeadingLevel[]; disabled: boolean }) {\n  const { t } = useLocale()\n  const picked = React.useRef(false)\n  const Icon = headingIcons[level]\n  const name = (l: 0 | HeadingLevel) => (l === 0 ? t(\"paragraph\") : t(\"heading\", { level: l }))\n  return (\n    <DropdownMenu\n      align=\"start\"\n      // After a pick, back to writing; Escape goes back to the button.\n      onCloseAutoFocus={(event) => {\n        if (!picked.current) return\n        picked.current = false\n        event.preventDefault()\n        editor?.commands.focus()\n      }}\n      items={[\n        {\n          type: \"radio\",\n          value: String(level),\n          onValueChange: (next) => {\n            if (!editor) return\n            picked.current = true\n            const l = Number(next) as 0 | HeadingLevel\n            if (l === 0) editor.chain().focus().setParagraph().run()\n            else editor.chain().focus().setHeading({ level: l }).run()\n          },\n          options: ([0, ...levels] as (0 | HeadingLevel)[]).map((l) => {\n            const ItemIcon = headingIcons[l]\n            return { value: String(l), label: name(l), icon: <ItemIcon /> }\n          }),\n        },\n      ]}\n      trigger={\n        <ToolbarPrimitive.Button\n          type=\"button\"\n          aria-label={`${t(\"textStyle\")}: ${name(level)}`}\n          disabled={disabled}\n          className={cn(toolClass, \"gap-0.5 px-1.5 data-[state=open]:bg-accent data-[state=open]:text-foreground [&_svg:last-child]:size-3.5\")}\n        >\n          <Icon />\n          <ChevronDownIcon />\n        </ToolbarPrimitive.Button>\n      }\n    />\n  )\n}\n\nfunction LinkTool({\n  editor,\n  open,\n  onOpenChange,\n  active,\n  disabled,\n}: {\n  editor: Editor | null\n  open: boolean\n  onOpenChange: (open: boolean) => void\n  active: boolean\n  disabled: boolean\n}) {\n  const { t } = useLocale()\n  const [href, setHref] = React.useState(\"\")\n  const [invalid, setInvalid] = React.useState(false)\n\n  const openChange = (next: boolean) => {\n    if (next && editor) {\n      setHref((editor.getAttributes(\"link\").href as string | undefined) ?? \"\")\n      setInvalid(false)\n    }\n    onOpenChange(next)\n  }\n  // Opened from ⌘K: fill in the link under the cursor as the button would.\n  const wasOpen = React.useRef(open)\n  React.useEffect(() => {\n    if (open && !wasOpen.current && editor) {\n      setHref((editor.getAttributes(\"link\").href as string | undefined) ?? \"\")\n      setInvalid(false)\n    }\n    wasOpen.current = open\n  }, [open, editor])\n\n  const apply = (event: React.FormEvent) => {\n    event.preventDefault()\n    event.stopPropagation()\n    if (!editor) return\n    const url = normalizeHref(href)\n    if (!url) {\n      setInvalid(true)\n      return\n    }\n    const chain = editor.chain().focus()\n    if (editor.state.selection.empty && !editor.isActive(\"link\")) {\n      // Nothing selected: the link goes in as its own text.\n      chain.insertContent({ type: \"text\", text: href.trim(), marks: [{ type: \"link\", attrs: { href: url } }] }).run()\n    } else {\n      chain.extendMarkRange(\"link\").setLink({ href: url }).run()\n    }\n    onOpenChange(false)\n  }\n\n  const remove = () => {\n    editor?.chain().focus().extendMarkRange(\"link\").unsetLink().run()\n    onOpenChange(false)\n  }\n\n  const label = active ? t(\"editLink\") : t(\"addLink\")\n  return (\n    <PopoverRoot open={open} onOpenChange={openChange}>\n      <ToolTip label={t(\"link\")} keys={[\"mod\", \"K\"]}>\n        <PopoverTrigger asChild>\n          <ToolbarPrimitive.Button type=\"button\" aria-label={label} aria-pressed={active} data-state={active ? \"on\" : \"off\"} disabled={disabled} className={toolClass}>\n            <LinkIcon />\n          </ToolbarPrimitive.Button>\n        </PopoverTrigger>\n      </ToolTip>\n      <PopoverContent\n        align=\"start\"\n        className=\"w-80 max-w-[calc(100vw-1rem)] p-3\"\n        // Closing goes back to the text, where the link is.\n        onCloseAutoFocus={(event) => {\n          event.preventDefault()\n          editor?.commands.focus()\n        }}\n      >\n        <form onSubmit={apply} className=\"grid gap-3\">\n          <Input\n            label={label}\n            value={href}\n            onChange={(event) => {\n              setHref(event.target.value)\n              setInvalid(false)\n            }}\n            placeholder=\"https://\"\n            inputMode=\"url\"\n            autoComplete=\"off\"\n            autoCapitalize=\"off\"\n            spellCheck={false}\n            error={invalid ? t(\"invalidLink\") : undefined}\n          />\n          <div className=\"flex justify-end gap-2\">\n            {active && (\n              <Button type=\"button\" variant=\"ghost\" size=\"sm\" color=\"destructive\" onClick={remove}>\n                {t(\"removeLink\")}\n              </Button>\n            )}\n            <Button type=\"submit\" size=\"sm\">\n              {t(\"apply\")}\n            </Button>\n          </div>\n        </form>\n      </PopoverContent>\n    </PopoverRoot>\n  )\n}\n\nexport { RichTextEditor, type RichTextEditorProps, type RichTextTool, type RichTextEditorClassNames, type Editor }\n"}],"cssVars":{"theme":{"color-destructive-foreground":"var(--destructive-foreground)","color-destructive-text":"var(--destructive-text)","ease-standard":"var(--ease-standard)","ease-enter":"var(--ease-enter)","ease-exit":"var(--ease-exit)","ease-spring":"var(--ease-spring)"},"light":{"destructive-foreground":"oklch(0.985 0 0)","destructive-text":"#bd2800","duration-fast":"160ms","duration-standard":"240ms","duration-considered":"480ms","ease-standard":"cubic-bezier(0.2, 0, 0, 1)","ease-enter":"cubic-bezier(0, 0, 0, 1)","ease-exit":"cubic-bezier(0.3, 0, 1, 1)","ease-spring":"linear(0, 0.071 4%, 0.234 8%, 0.433 12%, 0.626 17%, 0.791 21%, 0.917 25%, 1.004 29%, 1.055 33%, 1.079 38%, 1.083 42%, 1.075 46%, 1.06 50%, 1.043 54%, 1.027 58%, 1.015 62%, 1.005 67%, 0.998 71%, 0.995 75%, 0.993 79%, 0.993 83%, 0.994 88%, 0.995 92%, 0.997 96%, 1)"},"dark":{"destructive-foreground":"oklch(0.2 0 0)","destructive-text":"#ff8a5c"}}}