{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "rich-text-editor",
  "title": "Rich Text Editor",
  "author": "ilinxa",
  "description": "Plate-powered WYSIWYG editor and read-only viewer for long-form articles — code blocks, captioned images, floating toolbar, HTML export.",
  "dependencies": [
    "platejs@^53.0.3",
    "@platejs/basic-nodes@^53.0.0",
    "@platejs/basic-styles@^53.0.0",
    "@platejs/caption@^53.0.0",
    "@platejs/code-block@^53.0.0",
    "@platejs/indent@^53.0.0",
    "@platejs/link@^53.0.3",
    "@platejs/list@^53.0.2",
    "@platejs/media@^53.0.1",
    "@platejs/resizable@^53.0.0",
    "@platejs/table@^53.0.0",
    "@floating-ui/react@^0.27.19",
    "lowlight@^3.3.0",
    "highlight.js@^11.11.1",
    "lucide-react@^1.11.0"
  ],
  "registryDependencies": [
    "button"
  ],
  "files": [
    {
      "path": "src/registry/components/data/rich-text-editor/rich-text-editor.tsx",
      "content": "\"use client\";\n\nimport { useCallback, useEffect, useRef } from \"react\";\nimport { Plate, PlateContent, usePlateEditor } from \"platejs/react\";\nimport { cn } from \"@/lib/utils\";\nimport { setEmbedPolicy } from \"./lib/safe-embed\";\nimport { richTextPlugins } from \"./plugins/editor-kit\";\nimport { EditorToolbar } from \"./parts/editor-toolbar\";\nimport { FloatingToolbar } from \"./parts/floating-toolbar\";\nimport {\n  RICH_TEXT_DEFAULT_PLACEHOLDER,\n  RICH_TEXT_EMPTY_VALUE,\n  type RichTextEditorProps,\n  type RichTextValue,\n} from \"./types\";\n\nconst SAVE_KEY_DESCRIPTOR =\n  typeof navigator !== \"undefined\" && /Mac/i.test(navigator.platform)\n    ? \"Cmd+S\"\n    : \"Ctrl+S\";\n\nexport function RichTextEditor(props: RichTextEditorProps) {\n  const {\n    value: controlledValue,\n    defaultValue,\n    onChange,\n    onSave,\n    readOnly = false,\n    placeholder = RICH_TEXT_DEFAULT_PLACEHOLDER,\n    onImageUpload,\n    className,\n    toolbarClassName,\n    contentClassName,\n    containerClassName,\n    hideToolbar = false,\n    autoFocus = false,\n    embedAllowList,\n    isEmbedAllowed,\n  } = props;\n\n  const initialValue =\n    controlledValue ?? defaultValue ?? RICH_TEXT_EMPTY_VALUE;\n\n  const editor = usePlateEditor({\n    plugins: richTextPlugins,\n    value: initialValue,\n    autoSelect: autoFocus ? \"end\" : undefined,\n  });\n\n  // Idempotent per-editor policy for the embed renderer (see lib/safe-embed.ts).\n  setEmbedPolicy(editor, { embedAllowList, isEmbedAllowed });\n\n  // v0.2.2 — echo-guarded sync, now content-keyed. When `controlledValue`\n  // prop changes by REFERENCE only (e.g., RHF-controlled forms emit a fresh\n  // reference on every state change even when content is identical), the\n  // previous ref-equality check would fire `editor.tf.setValue` on every\n  // render. That re-applies the editor's current content as a \"new\" value,\n  // which resets Slate's selection — the user's cursor disappears\n  // immediately after every click, and typing can't land because each\n  // keystroke is followed by a setValue that wipes selection. Worse, on\n  // RHF + React 19, the rapid setValue → onChange → setState cascade\n  // tripped React error #185 (Maximum update depth exceeded). The fix is\n  // to gate the sync on the content key (cheap stringify of the Plate\n  // tree) — fire setValue only when the content actually differs from\n  // what the editor last emitted or accepted, regardless of how many fresh\n  // references the consumer pipes through `value`.\n  const lastSyncedKeyRef = useRef<string>(serializeValueKey(initialValue));\n  useEffect(() => {\n    if (!controlledValue) return;\n    const nextKey = serializeValueKey(controlledValue);\n    if (nextKey === lastSyncedKeyRef.current) return;\n    editor.tf.setValue(controlledValue);\n    lastSyncedKeyRef.current = nextKey;\n  }, [controlledValue, editor]);\n\n  const handleChange = useCallback(\n    ({ value }: { value: RichTextValue }) => {\n      lastSyncedKeyRef.current = serializeValueKey(value);\n      onChange?.(value);\n    },\n    [onChange]\n  );\n\n  const handleKeyDown = useCallback(\n    (e: React.KeyboardEvent) => {\n      if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === \"s\" && onSave) {\n        e.preventDefault();\n        const current = editor.children as RichTextValue;\n        Promise.resolve(onSave(current)).catch((err) => {\n          console.error(\"onSave failed\", err);\n        });\n      }\n    },\n    [editor, onSave]\n  );\n\n  return (\n    <div\n      className={cn(\n        \"rounded-lg border border-border bg-card overflow-hidden\",\n        className\n      )}\n    >\n      <Plate editor={editor} onChange={handleChange} readOnly={readOnly}>\n        {!hideToolbar && !readOnly ? (\n          <EditorToolbar\n            className={toolbarClassName}\n            onImageUpload={onImageUpload}\n          />\n        ) : null}\n\n        <div\n          className={cn(\n            \"max-h-150 overflow-y-auto px-6 py-4\",\n            containerClassName\n          )}\n        >\n          <PlateContent\n            placeholder={placeholder}\n            className={cn(\n              \"min-h-50 focus:outline-none\",\n              \"prose prose-sm dark:prose-invert max-w-none\",\n              \"[&_:where(p,h1,h2,h3,h4)]:my-0\",\n              contentClassName\n            )}\n            onKeyDown={handleKeyDown}\n            spellCheck\n          />\n        </div>\n\n        {!readOnly ? <FloatingToolbar /> : null}\n\n        {!readOnly && onSave ? (\n          <div className=\"border-t border-border bg-muted/30 px-4 py-1.5 text-xs text-muted-foreground\">\n            Press{\" \"}\n            <kbd className=\"rounded border border-border bg-muted px-1.5 py-0.5 font-mono text-[0.85em]\">\n              {SAVE_KEY_DESCRIPTOR}\n            </kbd>{\" \"}\n            to save\n          </div>\n        ) : null}\n      </Plate>\n    </div>\n  );\n}\n\n/**\n * v0.2.2 — content key for the echo-guarded controlled-value sync.\n * Stringify is adequate for Plate JSON (no functions, no cycles) and\n * cheap relative to a keystroke's frame budget for documents that fit on\n * one screen. Returns a random hash on circular-ref edge cases so the\n * effect still fires (defensive — we'd rather over-sync than skip a real\n * external update). */\nfunction serializeValueKey(value: RichTextValue): string {\n  try {\n    return JSON.stringify(value);\n  } catch {\n    return String(Math.random());\n  }\n}\n\n// Re-exports for cross-procomp consumers (e.g. json-form's `richtext` field\n// renderer). Imports targeting `./types` from another procomp's shipped\n// source get rewritten by shadcn 4.6.0 to `./types` of the CURRENT slug\n// (F-S1 cross-procomp `/types` bug), so cross-procomp imports must come from\n// this component file instead — its path the rewriter handles correctly.\nexport {\n  RICH_TEXT_EMPTY_VALUE,\n  type RichTextValue,\n  type ImageUploader,\n} from \"./types\";\n",
      "type": "registry:component",
      "target": "components/rich-text-editor/rich-text-editor.tsx"
    },
    {
      "path": "src/registry/components/data/rich-text-editor/rich-text-viewer.tsx",
      "content": "import { createStaticEditor, PlateStatic } from \"platejs/static\";\nimport { cn } from \"@/lib/utils\";\nimport { setEmbedPolicy } from \"./lib/safe-embed\";\nimport { richTextViewerPlugins } from \"./plugins/viewer-kit\";\nimport {\n  RICH_TEXT_EMPTY_VALUE,\n  type RichTextValue,\n  type RichTextViewerProps,\n} from \"./types\";\n\nconst VIEWER_PROSE_CLASSES =\n  \"prose prose-sm dark:prose-invert max-w-none [&_:where(p,h1,h2,h3,h4)]:my-0\";\n\nexport function RichTextViewer({\n  value,\n  className,\n  fallback,\n  embedAllowList,\n  isEmbedAllowed,\n}: RichTextViewerProps) {\n  if (!value || value.length === 0) {\n    if (fallback !== undefined) return <>{fallback}</>;\n    return (\n      <div className={cn(VIEWER_PROSE_CLASSES, className)}>\n        <p className=\"text-muted-foreground\">No content.</p>\n      </div>\n    );\n  }\n\n  const editor = createStaticEditor({\n    plugins: richTextViewerPlugins,\n    value: value as RichTextValue,\n  });\n\n  setEmbedPolicy(editor, { embedAllowList, isEmbedAllowed });\n\n  return (\n    <div className={cn(VIEWER_PROSE_CLASSES, className)}>\n      <PlateStatic editor={editor} value={value as RichTextValue} />\n    </div>\n  );\n}\n\n// Re-export for ergonomic destructuring + the empty-value sentinel.\nexport { RICH_TEXT_EMPTY_VALUE };\n",
      "type": "registry:component",
      "target": "components/rich-text-editor/rich-text-viewer.tsx"
    },
    {
      "path": "src/registry/components/data/rich-text-editor/index.ts",
      "content": "export { RichTextEditor } from \"./rich-text-editor\";\nexport { RichTextViewer } from \"./rich-text-viewer\";\nexport {\n  RICH_TEXT_DEFAULT_PLACEHOLDER,\n  RICH_TEXT_EMPTY_VALUE,\n  type RichTextEditorProps,\n  type RichTextEmbedPolicyProps,\n  type RichTextValue,\n  type RichTextViewerProps,\n  type ImageUploadResult,\n  type ImageUploader,\n} from \"./types\";\nexport {\n  serializeRichTextToHtml,\n  type SerializeHtmlOptions,\n} from \"./lib/serialize-html\";\nexport {\n  EMBED_DEFAULT_ALLOW_LIST,\n  safeHref,\n  type EmbedPolicy,\n} from \"./lib/safe-embed\";\n\n// @ilinxa/rich-text-editor 0.4.1\n",
      "type": "registry:component",
      "target": "components/rich-text-editor/index.ts"
    },
    {
      "path": "src/registry/components/data/rich-text-editor/types.ts",
      "content": "import type { ReactNode } from \"react\";\nimport type { Value } from \"platejs\";\n\nexport type RichTextValue = Value;\n\nexport interface ImageUploadResult {\n  src: string;\n  alt?: string;\n  width?: number;\n  height?: number;\n}\n\nexport type ImageUploader = (file: File) => Promise<ImageUploadResult>;\n\n/** Embed hardening options shared by the editor, viewer and serializer. */\nexport interface RichTextEmbedPolicyProps {\n  /**\n   * Hostnames allowed to render as an iframe. `*.example.com` matches any\n   * subdomain. REPLACES the default list (YouTube, youtube-nocookie, Vimeo\n   * player). Embeds on other hosts render as a plain link.\n   */\n  embedAllowList?: string[];\n  /** Custom predicate; wins over `embedAllowList`. Receives the parsed https URL. */\n  isEmbedAllowed?: (url: URL) => boolean;\n}\n\nexport interface RichTextEditorProps extends RichTextEmbedPolicyProps {\n  value?: RichTextValue;\n  defaultValue?: RichTextValue;\n  onChange?: (value: RichTextValue) => void;\n  onSave?: (value: RichTextValue) => void | Promise<void>;\n  readOnly?: boolean;\n  placeholder?: string;\n  onImageUpload?: ImageUploader;\n  className?: string;\n  toolbarClassName?: string;\n  contentClassName?: string;\n  containerClassName?: string;\n  hideToolbar?: boolean;\n  autoFocus?: boolean;\n}\n\nexport interface RichTextViewerProps extends RichTextEmbedPolicyProps {\n  value: RichTextValue;\n  className?: string;\n  fallback?: ReactNode;\n}\n\nexport const RICH_TEXT_EMPTY_VALUE: RichTextValue = [\n  { type: \"p\", children: [{ text: \"\" }] },\n];\n\nexport const RICH_TEXT_DEFAULT_PLACEHOLDER = \"Write your article here…\";\n",
      "type": "registry:component",
      "target": "components/rich-text-editor/types.ts"
    },
    {
      "path": "src/registry/components/data/rich-text-editor/plugins/editor-kit.ts",
      "content": "\"use client\";\n\nimport {\n  BlockquotePlugin,\n  BoldPlugin,\n  CodePlugin,\n  H1Plugin,\n  H2Plugin,\n  H3Plugin,\n  H4Plugin,\n  HighlightPlugin,\n  HorizontalRulePlugin,\n  ItalicPlugin,\n  KbdPlugin,\n  StrikethroughPlugin,\n  SubscriptPlugin,\n  SuperscriptPlugin,\n  UnderlinePlugin,\n} from \"@platejs/basic-nodes/react\";\nimport {\n  FontBackgroundColorPlugin,\n  FontColorPlugin,\n  FontFamilyPlugin,\n  FontSizePlugin,\n} from \"@platejs/basic-styles/react\";\nimport { CaptionPlugin } from \"@platejs/caption/react\";\nimport { CodeBlockPlugin, CodeLinePlugin, CodeSyntaxPlugin } from \"@platejs/code-block/react\";\nimport { IndentPlugin } from \"@platejs/indent/react\";\nimport { LinkPlugin } from \"@platejs/link/react\";\nimport { ListPlugin } from \"@platejs/list/react\";\nimport { ImagePlugin, MediaEmbedPlugin } from \"@platejs/media/react\";\nimport { KEYS } from \"platejs\";\n\nimport { lowlight } from \"../lib/lowlight-instance\";\nimport {\n  TableCellHeaderPlugin,\n  TableCellPlugin,\n  TablePlugin,\n  TableRowPlugin,\n} from \"@platejs/table/react\";\nimport { ParagraphPlugin } from \"platejs/react\";\n\nimport {\n  BlockquoteElement,\n  CodeBlockElement,\n  CodeLineElement,\n  H1Element,\n  H2Element,\n  H3Element,\n  H4Element,\n  HrElement,\n  ImageElement,\n  LinkElement,\n  ListElement,\n  MediaEmbedElement,\n  ParagraphElement,\n  TableCellElement,\n  TableCellHeaderElement,\n  TableElement,\n  TableRowElement,\n} from \"../parts/element-renderers\";\nimport {\n  CodeLeaf,\n  HighlightLeaf,\n  KbdLeaf,\n} from \"../parts/leaf-renderers\";\n\n/**\n * The plugin set for the editor side.\n * The viewer reuses these plugin definitions via createSlateEditor + components map\n * (see rich-text-viewer.tsx) so element/leaf rendering stays consistent.\n */\nexport const richTextPlugins = [\n  // Blocks\n  ParagraphPlugin.withComponent(ParagraphElement),\n  H1Plugin.withComponent(H1Element),\n  H2Plugin.withComponent(H2Element),\n  H3Plugin.withComponent(H3Element),\n  H4Plugin.withComponent(H4Element),\n  BlockquotePlugin.withComponent(BlockquoteElement),\n  HorizontalRulePlugin.withComponent(HrElement),\n\n  // Lists\n  ListPlugin.withComponent(ListElement),\n\n  // Code blocks (with lowlight syntax highlighting)\n  CodeBlockPlugin.configure({\n    options: { lowlight },\n    node: { component: CodeBlockElement },\n  }),\n  CodeLinePlugin.withComponent(CodeLineElement),\n  CodeSyntaxPlugin,\n\n  // Tables\n  TablePlugin.withComponent(TableElement),\n  TableRowPlugin.withComponent(TableRowElement),\n  TableCellPlugin.withComponent(TableCellElement),\n  TableCellHeaderPlugin.withComponent(TableCellHeaderElement),\n\n  // Media + captions (caption applies to image/video/audio/file/embed)\n  ImagePlugin.withComponent(ImageElement),\n  MediaEmbedPlugin.withComponent(MediaEmbedElement),\n  CaptionPlugin.configure({\n    options: {\n      query: {\n        allow: [KEYS.img, KEYS.video, KEYS.audio, KEYS.file, KEYS.mediaEmbed],\n      },\n    },\n  }),\n\n  // Inline\n  LinkPlugin.configure({\n    options: { allowedSchemes: [\"http\", \"https\", \"mailto\", \"tel\"] },\n    node: { component: LinkElement },\n  }),\n\n  // Marks\n  BoldPlugin,\n  ItalicPlugin,\n  UnderlinePlugin,\n  StrikethroughPlugin,\n  CodePlugin.withComponent(CodeLeaf),\n  HighlightPlugin.withComponent(HighlightLeaf),\n  SubscriptPlugin,\n  SuperscriptPlugin,\n  KbdPlugin.withComponent(KbdLeaf),\n\n  // Styles (text-level attributes — no element component)\n  FontFamilyPlugin,\n  FontSizePlugin,\n  FontColorPlugin,\n  FontBackgroundColorPlugin,\n\n  // Layout\n  IndentPlugin.configure({\n    inject: {\n      targetPlugins: [\n        ParagraphPlugin.key,\n        H1Plugin.key,\n        H2Plugin.key,\n        H3Plugin.key,\n        H4Plugin.key,\n        BlockquotePlugin.key,\n        CodeBlockPlugin.key,\n      ],\n    },\n  }),\n];\n",
      "type": "registry:component",
      "target": "components/rich-text-editor/plugins/editor-kit.ts"
    },
    {
      "path": "src/registry/components/data/rich-text-editor/plugins/viewer-kit.ts",
      "content": "import {\n  BlockquotePlugin,\n  BoldPlugin,\n  CodePlugin,\n  H1Plugin,\n  H2Plugin,\n  H3Plugin,\n  H4Plugin,\n  HighlightPlugin,\n  HorizontalRulePlugin,\n  ItalicPlugin,\n  KbdPlugin,\n  StrikethroughPlugin,\n  SubscriptPlugin,\n  SuperscriptPlugin,\n  UnderlinePlugin,\n} from \"@platejs/basic-nodes/react\";\nimport {\n  FontBackgroundColorPlugin,\n  FontColorPlugin,\n  FontFamilyPlugin,\n  FontSizePlugin,\n} from \"@platejs/basic-styles/react\";\nimport { CodeBlockPlugin, CodeLinePlugin, CodeSyntaxPlugin } from \"@platejs/code-block/react\";\nimport { LinkPlugin } from \"@platejs/link/react\";\nimport { ListPlugin } from \"@platejs/list/react\";\nimport { ImagePlugin, MediaEmbedPlugin } from \"@platejs/media/react\";\n\nimport { lowlight } from \"../lib/lowlight-instance\";\nimport {\n  TableCellHeaderPlugin,\n  TableCellPlugin,\n  TablePlugin,\n  TableRowPlugin,\n} from \"@platejs/table/react\";\nimport { ParagraphPlugin } from \"platejs/react\";\n\nimport {\n  StaticBlockquote,\n  StaticCodeBlock,\n  StaticCodeLeaf,\n  StaticCodeLine,\n  StaticH1,\n  StaticH2,\n  StaticH3,\n  StaticH4,\n  StaticHighlightLeaf,\n  StaticHr,\n  StaticImage,\n  StaticKbdLeaf,\n  StaticLink,\n  StaticList,\n  StaticMediaEmbed,\n  StaticParagraph,\n  StaticTable,\n  StaticTableCell,\n  StaticTableCellHeader,\n  StaticTableRow,\n} from \"../static-elements/static-element-renderers\";\n\n/**\n * Plugin set for the static (RSC) viewer side.\n * Mirrors editor-kit.ts but binds Slate{Element,Leaf}-based renderers\n * — those don't use client-only hooks, so the viewer is server-renderable.\n */\nexport const richTextViewerPlugins = [\n  // Blocks\n  ParagraphPlugin.withComponent(StaticParagraph),\n  H1Plugin.withComponent(StaticH1),\n  H2Plugin.withComponent(StaticH2),\n  H3Plugin.withComponent(StaticH3),\n  H4Plugin.withComponent(StaticH4),\n  BlockquotePlugin.withComponent(StaticBlockquote),\n  HorizontalRulePlugin.withComponent(StaticHr),\n\n  // Lists\n  ListPlugin.withComponent(StaticList),\n\n  // Code blocks (with lowlight syntax highlighting)\n  CodeBlockPlugin.configure({\n    options: { lowlight },\n    node: { component: StaticCodeBlock },\n  }),\n  CodeLinePlugin.withComponent(StaticCodeLine),\n  CodeSyntaxPlugin,\n\n  // Tables\n  TablePlugin.withComponent(StaticTable),\n  TableRowPlugin.withComponent(StaticTableRow),\n  TableCellPlugin.withComponent(StaticTableCell),\n  TableCellHeaderPlugin.withComponent(StaticTableCellHeader),\n\n  // Media\n  ImagePlugin.withComponent(StaticImage),\n  MediaEmbedPlugin.withComponent(StaticMediaEmbed),\n\n  // Inline\n  LinkPlugin.configure({\n    options: { allowedSchemes: [\"http\", \"https\", \"mailto\", \"tel\"] },\n    node: { component: StaticLink },\n  }),\n\n  // Marks\n  BoldPlugin,\n  ItalicPlugin,\n  UnderlinePlugin,\n  StrikethroughPlugin,\n  CodePlugin.withComponent(StaticCodeLeaf),\n  HighlightPlugin.withComponent(StaticHighlightLeaf),\n  SubscriptPlugin,\n  SuperscriptPlugin,\n  KbdPlugin.withComponent(StaticKbdLeaf),\n\n  // Styles\n  FontFamilyPlugin,\n  FontSizePlugin,\n  FontColorPlugin,\n  FontBackgroundColorPlugin,\n];\n",
      "type": "registry:component",
      "target": "components/rich-text-editor/plugins/viewer-kit.ts"
    },
    {
      "path": "src/registry/components/data/rich-text-editor/parts/editor-toolbar.tsx",
      "content": "\"use client\";\n\nimport {\n  Bold,\n  Code,\n  Heading1,\n  Heading2,\n  Heading3,\n  Highlighter,\n  Image as ImageIcon,\n  Italic,\n  Link as LinkIcon,\n  List,\n  ListOrdered,\n  Minus,\n  Quote,\n  Strikethrough,\n  Subscript as SubIcon,\n  Superscript as SupIcon,\n  Table as TableIcon,\n  TerminalSquare,\n  Underline as UnderlineIcon,\n} from \"lucide-react\";\nimport {\n  BoldPlugin,\n  CodePlugin,\n  H1Plugin,\n  H2Plugin,\n  H3Plugin,\n  HighlightPlugin,\n  HorizontalRulePlugin,\n  ItalicPlugin,\n  StrikethroughPlugin,\n  SubscriptPlugin,\n  SuperscriptPlugin,\n  UnderlinePlugin,\n} from \"@platejs/basic-nodes/react\";\nimport { type ComponentType, type ReactNode, useCallback } from \"react\";\nimport { CodeBlockPlugin } from \"@platejs/code-block/react\";\nimport { LinkPlugin } from \"@platejs/link/react\";\nimport { ListPlugin } from \"@platejs/list/react\";\nimport { ImagePlugin } from \"@platejs/media/react\";\nimport { TablePlugin } from \"@platejs/table/react\";\nimport { ParagraphPlugin, useEditorRef } from \"platejs/react\";\nimport { cn } from \"@/lib/utils\";\nimport { isHttpUrl, safeHref } from \"../lib/safe-embed\";\nimport type { ImageUploader } from \"../types\";\nimport { BlockButton, MarkButton, useBlockToggle } from \"./toolbar-buttons\";\n\nfunction HeadingButton({\n  blockType,\n  icon,\n  label,\n}: {\n  blockType: string;\n  icon: ComponentType<{ className?: string }>;\n  label: string;\n}) {\n  const { isActive, toggle } = useBlockToggle(blockType);\n  return <BlockButton isActive={isActive} onActivate={toggle} icon={icon} label={label} />;\n}\n\nfunction InsertHrButton() {\n  const editor = useEditorRef();\n  const handleClick = useCallback(() => {\n    editor.tf.insertNodes({\n      type: HorizontalRulePlugin.key,\n      children: [{ text: \"\" }],\n    });\n    editor.tf.focus();\n  }, [editor]);\n  return (\n    <BlockButton\n      isActive={false}\n      onActivate={handleClick}\n      icon={Minus}\n      label=\"Insert horizontal rule\"\n    />\n  );\n}\n\nfunction InsertListButton({ ordered }: { ordered: boolean }) {\n  const editor = useEditorRef();\n  const handleClick = useCallback(() => {\n    editor.tf.insertNodes({\n      type: ListPlugin.key,\n      listStyleType: ordered ? \"decimal\" : \"disc\",\n      indent: 1,\n      children: [{ text: \"\" }],\n    });\n    editor.tf.focus();\n  }, [editor, ordered]);\n  return (\n    <BlockButton\n      isActive={false}\n      onActivate={handleClick}\n      icon={ordered ? ListOrdered : List}\n      label={ordered ? \"Insert ordered list\" : \"Insert bullet list\"}\n    />\n  );\n}\n\nfunction InsertTableButton() {\n  const editor = useEditorRef();\n  const handleClick = useCallback(() => {\n    const cell = (text = \"\") => ({\n      type: \"td\",\n      children: [{ type: ParagraphPlugin.key, children: [{ text }] }],\n    });\n    const headerCell = (text = \"\") => ({\n      type: \"th\",\n      children: [{ type: ParagraphPlugin.key, children: [{ text }] }],\n    });\n    editor.tf.insertNodes({\n      type: TablePlugin.key,\n      children: [\n        { type: \"tr\", children: [headerCell(\"Column 1\"), headerCell(\"Column 2\"), headerCell(\"Column 3\")] },\n        { type: \"tr\", children: [cell(), cell(), cell()] },\n        { type: \"tr\", children: [cell(), cell(), cell()] },\n      ],\n    });\n    editor.tf.focus();\n  }, [editor]);\n  return (\n    <BlockButton\n      isActive={false}\n      onActivate={handleClick}\n      icon={TableIcon}\n      label=\"Insert table\"\n    />\n  );\n}\n\nfunction InsertImageButton({ onImageUpload }: { onImageUpload?: ImageUploader }) {\n  const editor = useEditorRef();\n\n  const handleClick = useCallback(async () => {\n    if (onImageUpload) {\n      const input = document.createElement(\"input\");\n      input.type = \"file\";\n      input.accept = \"image/*\";\n      input.onchange = async () => {\n        const file = input.files?.[0];\n        if (!file) return;\n        try {\n          const result = await onImageUpload(file);\n          editor.tf.insertNodes({\n            type: ImagePlugin.key,\n            url: result.src,\n            alt: result.alt ?? file.name,\n            width: result.width,\n            height: result.height,\n            children: [{ text: \"\" }],\n          });\n          editor.tf.focus();\n        } catch (err) {\n          console.error(\"Image upload failed\", err);\n        }\n      };\n      input.click();\n      return;\n    }\n\n    const url = window.prompt(\"Image URL\");\n    if (!url || !isHttpUrl(url)) return;\n    editor.tf.insertNodes({\n      type: ImagePlugin.key,\n      url,\n      children: [{ text: \"\" }],\n    });\n    editor.tf.focus();\n  }, [editor, onImageUpload]);\n\n  return (\n    <BlockButton\n      isActive={false}\n      onActivate={handleClick}\n      icon={ImageIcon}\n      label=\"Insert image\"\n    />\n  );\n}\n\nfunction InsertLinkButton() {\n  const editor = useEditorRef();\n  const handleClick = useCallback(() => {\n    const raw = window.prompt(\"Link URL\");\n    const url = safeHref(raw);\n    if (!url) return;\n    const text = window.getSelection()?.toString() || url;\n    editor.tf.insertNodes({\n      type: LinkPlugin.key,\n      url,\n      children: [{ text }],\n    });\n    editor.tf.focus();\n  }, [editor]);\n  return (\n    <BlockButton\n      isActive={false}\n      onActivate={handleClick}\n      icon={LinkIcon}\n      label=\"Insert link\"\n    />\n  );\n}\n\nfunction FontFamilySelect() {\n  const editor = useEditorRef();\n  const handleChange = useCallback(\n    (e: React.ChangeEvent<HTMLSelectElement>) => {\n      const value = e.target.value;\n      if (value === \"default\") {\n        editor.tf.removeMark(\"fontFamily\");\n      } else {\n        editor.tf.addMark(\"fontFamily\", value);\n      }\n      editor.tf.focus();\n    },\n    [editor]\n  );\n  return (\n    <select\n      onMouseDown={(e) => e.preventDefault()}\n      onChange={handleChange}\n      className=\"h-8 rounded-md border border-input bg-background px-2 text-xs\"\n      title=\"Font family\"\n      aria-label=\"Font family\"\n      defaultValue=\"default\"\n    >\n      <option value=\"default\">Default font</option>\n      <option value=\"var(--font-serif)\">Serif</option>\n      <option value=\"var(--font-sans)\">Sans</option>\n      <option value=\"var(--font-mono)\">Mono</option>\n    </select>\n  );\n}\n\nfunction FontSizeSelect() {\n  const editor = useEditorRef();\n  const handleChange = useCallback(\n    (e: React.ChangeEvent<HTMLSelectElement>) => {\n      const value = e.target.value;\n      if (value === \"default\") {\n        editor.tf.removeMark(\"fontSize\");\n      } else {\n        editor.tf.addMark(\"fontSize\", value);\n      }\n      editor.tf.focus();\n    },\n    [editor]\n  );\n  return (\n    <select\n      onMouseDown={(e) => e.preventDefault()}\n      onChange={handleChange}\n      className=\"h-8 rounded-md border border-input bg-background px-2 text-xs\"\n      title=\"Font size\"\n      aria-label=\"Font size\"\n      defaultValue=\"default\"\n    >\n      <option value=\"default\">Size</option>\n      <option value=\"12px\">12</option>\n      <option value=\"14px\">14</option>\n      <option value=\"16px\">16</option>\n      <option value=\"18px\">18</option>\n      <option value=\"20px\">20</option>\n      <option value=\"24px\">24</option>\n      <option value=\"32px\">32</option>\n    </select>\n  );\n}\n\nfunction FontColorInput() {\n  const editor = useEditorRef();\n  const handleChange = useCallback(\n    (e: React.ChangeEvent<HTMLInputElement>) => {\n      editor.tf.addMark(\"color\", e.target.value);\n      editor.tf.focus();\n    },\n    [editor]\n  );\n  return (\n    <input\n      type=\"color\"\n      onMouseDown={(e) => e.preventDefault()}\n      onChange={handleChange}\n      className=\"h-8 w-8 cursor-pointer rounded-md border border-input bg-background\"\n      title=\"Text color\"\n      aria-label=\"Text color\"\n      defaultValue=\"#000000\"\n    />\n  );\n}\n\nfunction ToolbarSeparator() {\n  return <span className=\"mx-1 h-6 w-px bg-border\" aria-hidden=\"true\" />;\n}\n\nfunction ToolbarGroup({ children }: { children: ReactNode }) {\n  return <div className=\"flex items-center gap-0.5\">{children}</div>;\n}\n\ninterface EditorToolbarProps {\n  className?: string;\n  onImageUpload?: ImageUploader;\n}\n\nexport function EditorToolbar({ className, onImageUpload }: EditorToolbarProps) {\n  return (\n    <div\n      role=\"toolbar\"\n      aria-label=\"Rich text editor toolbar\"\n      className={cn(\n        \"flex flex-wrap items-center gap-1 border-b border-border bg-card px-2 py-1.5\",\n        className\n      )}\n    >\n      <ToolbarGroup>\n        <MarkButton nodeType={BoldPlugin.key} icon={Bold} label=\"Bold\" />\n        <MarkButton nodeType={ItalicPlugin.key} icon={Italic} label=\"Italic\" />\n        <MarkButton nodeType={UnderlinePlugin.key} icon={UnderlineIcon} label=\"Underline\" />\n        <MarkButton nodeType={StrikethroughPlugin.key} icon={Strikethrough} label=\"Strikethrough\" />\n        <MarkButton nodeType={CodePlugin.key} icon={Code} label=\"Inline code\" />\n        <MarkButton nodeType={HighlightPlugin.key} icon={Highlighter} label=\"Highlight\" />\n        <MarkButton nodeType={SubscriptPlugin.key} icon={SubIcon} label=\"Subscript\" />\n        <MarkButton nodeType={SuperscriptPlugin.key} icon={SupIcon} label=\"Superscript\" />\n      </ToolbarGroup>\n\n      <ToolbarSeparator />\n\n      <ToolbarGroup>\n        <HeadingButton blockType={H1Plugin.key} icon={Heading1} label=\"Heading 1\" />\n        <HeadingButton blockType={H2Plugin.key} icon={Heading2} label=\"Heading 2\" />\n        <HeadingButton blockType={H3Plugin.key} icon={Heading3} label=\"Heading 3\" />\n      </ToolbarGroup>\n\n      <ToolbarSeparator />\n\n      <ToolbarGroup>\n        <HeadingButton blockType=\"blockquote\" icon={Quote} label=\"Blockquote\" />\n        <HeadingButton blockType={CodeBlockPlugin.key} icon={TerminalSquare} label=\"Code block\" />\n        <InsertHrButton />\n      </ToolbarGroup>\n\n      <ToolbarSeparator />\n\n      <ToolbarGroup>\n        <InsertListButton ordered={false} />\n        <InsertListButton ordered />\n      </ToolbarGroup>\n\n      <ToolbarSeparator />\n\n      <ToolbarGroup>\n        <InsertLinkButton />\n        <InsertImageButton onImageUpload={onImageUpload} />\n        <InsertTableButton />\n      </ToolbarGroup>\n\n      <ToolbarSeparator />\n\n      <ToolbarGroup>\n        <FontFamilySelect />\n        <FontSizeSelect />\n        <FontColorInput />\n      </ToolbarGroup>\n    </div>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/rich-text-editor/parts/editor-toolbar.tsx"
    },
    {
      "path": "src/registry/components/data/rich-text-editor/parts/floating-toolbar.tsx",
      "content": "\"use client\";\n\nimport {\n  Bold,\n  Code,\n  Highlighter,\n  Italic,\n  Link as LinkIcon,\n  Strikethrough,\n  Underline as UnderlineIcon,\n} from \"lucide-react\";\nimport {\n  BoldPlugin,\n  CodePlugin,\n  HighlightPlugin,\n  ItalicPlugin,\n  StrikethroughPlugin,\n  UnderlinePlugin,\n} from \"@platejs/basic-nodes/react\";\nimport { LinkPlugin } from \"@platejs/link/react\";\nimport {\n  autoUpdate,\n  flip,\n  offset,\n  shift,\n  useFloating,\n} from \"@floating-ui/react\";\nimport { useEditorRef, useEditorSelection } from \"platejs/react\";\nimport { useCallback, useEffect, useMemo, useState } from \"react\";\nimport { Button } from \"@/components/ui/button\";\nimport { safeHref } from \"../lib/safe-embed\";\nimport { MarkButton } from \"./toolbar-buttons\";\n\nfunction getSelectionRect(): DOMRect | null {\n  if (typeof window === \"undefined\") return null;\n  const sel = window.getSelection();\n  if (!sel || sel.rangeCount === 0 || sel.isCollapsed) return null;\n  const rect = sel.getRangeAt(0).getBoundingClientRect();\n  // Selection-near-empty case (collapsed-but-not-collapsed): width 0\n  if (rect.width === 0 && rect.height === 0) return null;\n  return rect;\n}\n\nexport function FloatingToolbar() {\n  const editor = useEditorRef();\n  const selection = useEditorSelection();\n  const [visible, setVisible] = useState(false);\n\n  const isCollapsed = useMemo(() => {\n    if (!selection) return true;\n    const a = selection.anchor;\n    const f = selection.focus;\n    if (a.offset !== f.offset) return false;\n    if (JSON.stringify(a.path) !== JSON.stringify(f.path)) return false;\n    return true;\n  }, [selection]);\n\n  const { refs, floatingStyles } = useFloating({\n    placement: \"top\",\n    middleware: [offset(8), flip(), shift({ padding: 8 })],\n    whileElementsMounted: autoUpdate,\n  });\n\n  // Sync the floating-UI reference with the live window selection.\n  // setVisible() inside an effect is unavoidable here: the source of truth is\n  // a DOM-level Selection that React doesn't track. The rule is meant for\n  // derived-state sync; this is genuine external-system subscription.\n  useEffect(() => {\n    if (isCollapsed) {\n      // eslint-disable-next-line react-hooks/set-state-in-effect\n      setVisible(false);\n      return;\n    }\n    const update = () => {\n      const rect = getSelectionRect();\n      if (!rect) {\n        setVisible(false);\n        return;\n      }\n      refs.setReference({\n        getBoundingClientRect: () => rect,\n        contextElement: undefined,\n      });\n      setVisible(true);\n    };\n    update();\n\n    // Re-poll on scroll / resize so the toolbar stays attached to selection.\n    document.addEventListener(\"scroll\", update, true);\n    window.addEventListener(\"resize\", update);\n    return () => {\n      document.removeEventListener(\"scroll\", update, true);\n      window.removeEventListener(\"resize\", update);\n    };\n  }, [isCollapsed, refs, selection]);\n\n  const handleAddLink = useCallback(() => {\n    const url = safeHref(window.prompt(\"Link URL\"));\n    if (!url) return;\n    editor.tf.insertNodes({\n      type: LinkPlugin.key,\n      url,\n      children: [{ text: window.getSelection()?.toString() || url }],\n    });\n    editor.tf.focus();\n  }, [editor]);\n\n  if (!visible || isCollapsed) return null;\n\n  return (\n    <div\n      // floating-ui's setFloating is a stable ref-callback, not a `.current`\n      // access. Lint can't tell the difference.\n      // eslint-disable-next-line react-hooks/refs\n      ref={refs.setFloating}\n      style={floatingStyles}\n      className=\"z-50 flex items-center gap-0.5 rounded-md border border-border bg-card px-1 py-0.5 shadow-lg\"\n      role=\"toolbar\"\n      aria-label=\"Selection actions\"\n      onMouseDown={(e) => e.preventDefault()}\n    >\n      <MarkButton nodeType={BoldPlugin.key} icon={Bold} label=\"Bold\" size=\"sm\" />\n      <MarkButton nodeType={ItalicPlugin.key} icon={Italic} label=\"Italic\" size=\"sm\" />\n      <MarkButton nodeType={UnderlinePlugin.key} icon={UnderlineIcon} label=\"Underline\" size=\"sm\" />\n      <MarkButton nodeType={StrikethroughPlugin.key} icon={Strikethrough} label=\"Strikethrough\" size=\"sm\" />\n      <MarkButton nodeType={CodePlugin.key} icon={Code} label=\"Inline code\" size=\"sm\" />\n      <MarkButton nodeType={HighlightPlugin.key} icon={Highlighter} label=\"Highlight\" size=\"sm\" />\n      <span className=\"mx-0.5 h-5 w-px bg-border\" aria-hidden=\"true\" />\n      <Button\n        type=\"button\"\n        variant=\"ghost\"\n        size=\"icon\"\n        className=\"h-7 w-7\"\n        title=\"Insert link\"\n        aria-label=\"Insert link\"\n        onMouseDown={(e) => e.preventDefault()}\n        onClick={handleAddLink}\n      >\n        <LinkIcon className=\"h-4 w-4\" />\n      </Button>\n    </div>\n  );\n}\n\n",
      "type": "registry:component",
      "target": "components/rich-text-editor/parts/floating-toolbar.tsx"
    },
    {
      "path": "src/registry/components/data/rich-text-editor/parts/toolbar-buttons.tsx",
      "content": "\"use client\";\n\nimport {\n  type ComponentType,\n  type MouseEvent,\n  useCallback,\n} from \"react\";\nimport {\n  useEditorRef,\n  useEditorSelector,\n  useMarkToolbarButton,\n  useMarkToolbarButtonState,\n} from \"platejs/react\";\nimport { Button } from \"@/components/ui/button\";\nimport { cn } from \"@/lib/utils\";\n\ninterface MarkButtonProps {\n  nodeType: string;\n  icon: ComponentType<{ className?: string }>;\n  label: string;\n  size?: \"sm\" | \"md\";\n}\n\nexport function MarkButton({\n  nodeType,\n  icon: Icon,\n  label,\n  size = \"md\",\n}: MarkButtonProps) {\n  const state = useMarkToolbarButtonState({ nodeType });\n  const { props } = useMarkToolbarButton(state);\n  return (\n    <Button\n      type=\"button\"\n      variant=\"ghost\"\n      size=\"icon\"\n      className={cn(\n        size === \"sm\" ? \"h-7 w-7\" : \"h-8 w-8\",\n        state.pressed && \"bg-muted text-foreground\"\n      )}\n      title={label}\n      aria-label={label}\n      aria-pressed={state.pressed}\n      onMouseDown={props.onMouseDown}\n      onClick={props.onClick}\n    >\n      <Icon className=\"h-4 w-4\" />\n    </Button>\n  );\n}\n\ninterface BlockButtonProps {\n  isActive: boolean;\n  onActivate: () => void;\n  icon: ComponentType<{ className?: string }>;\n  label: string;\n  size?: \"sm\" | \"md\";\n}\n\nexport function BlockButton({\n  isActive,\n  onActivate,\n  icon: Icon,\n  label,\n  size = \"md\",\n}: BlockButtonProps) {\n  const handleMouseDown = useCallback(\n    (e: MouseEvent<HTMLButtonElement>) => {\n      e.preventDefault();\n    },\n    []\n  );\n\n  return (\n    <Button\n      type=\"button\"\n      variant=\"ghost\"\n      size=\"icon\"\n      className={cn(\n        size === \"sm\" ? \"h-7 w-7\" : \"h-8 w-8\",\n        isActive && \"bg-muted text-foreground\"\n      )}\n      title={label}\n      aria-label={label}\n      aria-pressed={isActive}\n      onMouseDown={handleMouseDown}\n      onClick={onActivate}\n    >\n      <Icon className=\"h-4 w-4\" />\n    </Button>\n  );\n}\n\nexport function useBlockToggle(blockType: string) {\n  const editor = useEditorRef();\n  const isActive = useEditorSelector(\n    (e) => {\n      const entry = e.api.block();\n      return entry?.[0]?.type === blockType;\n    },\n    [blockType]\n  );\n  const toggle = useCallback(() => {\n    editor.tf.toggleBlock(blockType);\n    editor.tf.focus();\n  }, [editor, blockType]);\n  return { isActive, toggle };\n}\n",
      "type": "registry:component",
      "target": "components/rich-text-editor/parts/toolbar-buttons.tsx"
    },
    {
      "path": "src/registry/components/data/rich-text-editor/parts/element-renderers.tsx",
      "content": "\"use client\";\n\nimport type { ComponentProps, ReactNode } from \"react\";\nimport { PlateElement, type PlateElementProps } from \"platejs/react\";\nimport { cn } from \"@/lib/utils\";\nimport { getEmbedPolicy, safeHref } from \"../lib/safe-embed\";\nimport { SafeEmbedView } from \"./safe-embed-view\";\n\ntype ElementProps = ComponentProps<typeof PlateElement>;\n\n// Plate's `<PlateElement as=\"X\">` discriminates the type of `attributes` per\n// HTML element kind. When we forward `props.attributes` (typed for a wider\n// element kind), TS rejects the narrower target. The runtime is just data-slate-*\n// attributes — fine on any HTML element. Cast via this helper.\n//\n// Without this we'd pepper `attributes={props.attributes as never}` on every\n// element. One central cast keeps the noise local.\nfunction withAs<As extends string>(props: ElementProps, as: As): ElementProps & { as: As } {\n  // The cast is intentional: we know `props.attributes` is the same data-slate-*\n  // shape regardless of `as`. TS's discriminated-union narrowing doesn't help here.\n  return { ...props, as, attributes: props.attributes as never } as ElementProps & {\n    as: As;\n  };\n}\n\nfunction Wrapped(props: ElementProps & { as?: string; className?: string; children: ReactNode }) {\n  return <PlateElement {...(props as ElementProps)}>{props.children}</PlateElement>;\n}\n\nexport function ParagraphElement(props: ElementProps) {\n  return (\n    <Wrapped {...withAs(props, \"p\")} className={cn(\"my-4 leading-relaxed\", props.className)}>\n      {props.children}\n    </Wrapped>\n  );\n}\n\nexport function H1Element(props: ElementProps) {\n  return (\n    <Wrapped {...withAs(props, \"h1\")} className={cn(\"mt-10 mb-4 text-4xl font-serif font-bold tracking-tight\", props.className)}>\n      {props.children}\n    </Wrapped>\n  );\n}\n\nexport function H2Element(props: ElementProps) {\n  return (\n    <Wrapped {...withAs(props, \"h2\")} className={cn(\"mt-8 mb-3 text-3xl font-serif font-bold tracking-tight\", props.className)}>\n      {props.children}\n    </Wrapped>\n  );\n}\n\nexport function H3Element(props: ElementProps) {\n  return (\n    <Wrapped {...withAs(props, \"h3\")} className={cn(\"mt-6 mb-2 text-2xl font-serif font-bold\", props.className)}>\n      {props.children}\n    </Wrapped>\n  );\n}\n\nexport function H4Element(props: ElementProps) {\n  return (\n    <Wrapped {...withAs(props, \"h4\")} className={cn(\"mt-4 mb-2 text-xl font-serif font-semibold\", props.className)}>\n      {props.children}\n    </Wrapped>\n  );\n}\n\nexport function BlockquoteElement(props: ElementProps) {\n  return (\n    <Wrapped\n      {...withAs(props, \"blockquote\")}\n      className={cn(\n        \"my-6 border-s-4 border-primary ps-6 py-2 italic text-muted-foreground bg-muted/30 rounded-e-md\",\n        props.className\n      )}\n    >\n      {props.children}\n    </Wrapped>\n  );\n}\n\nexport function HrElement(props: ElementProps) {\n  return (\n    <PlateElement\n      {...props}\n      className={cn(\"my-8\", props.className)}\n      attributes={{ ...(props.attributes as Record<string, unknown>), contentEditable: false } as never}\n    >\n      <div>\n        <hr className=\"border-border\" />\n      </div>\n      {props.children}\n    </PlateElement>\n  );\n}\n\nexport function ListElement(props: ElementProps) {\n  const { element } = props as PlateElementProps;\n  const listStyleType = (element as { listStyleType?: string }).listStyleType ?? \"disc\";\n  const indent = ((element as { indent?: number }).indent ?? 1) - 1;\n  const tag = (listStyleType === \"decimal\" ? \"ol\" : \"ul\") as \"ol\" | \"ul\";\n\n  return (\n    <Wrapped\n      {...withAs(props, tag)}\n      className={cn(\n        \"my-4 ms-6\",\n        listStyleType === \"decimal\" ? \"list-decimal\" : \"list-disc\",\n        props.className\n      )}\n      style={{\n        ...(props.style ?? {}),\n        marginLeft: indent > 0 ? `${indent * 1.5}rem` : undefined,\n      }}\n    >\n      <li>{props.children}</li>\n    </Wrapped>\n  );\n}\n\nexport function CodeBlockElement(props: ElementProps) {\n  return (\n    <Wrapped\n      {...withAs(props, \"pre\")}\n      className={cn(\n        \"my-6 overflow-x-auto rounded-md border border-border bg-muted p-4 font-mono text-sm\",\n        props.className\n      )}\n    >\n      <code>{props.children}</code>\n    </Wrapped>\n  );\n}\n\nexport function CodeLineElement(props: ElementProps) {\n  return (\n    <Wrapped {...withAs(props, \"div\")} className={cn(\"font-mono\", props.className)}>\n      {props.children}\n    </Wrapped>\n  );\n}\n\nexport function TableElement(props: ElementProps) {\n  return (\n    <PlateElement {...props} className={cn(\"my-6 overflow-x-auto\", props.className)}>\n      <table className=\"w-full border-collapse text-sm\">\n        <tbody>{props.children}</tbody>\n      </table>\n    </PlateElement>\n  );\n}\n\nexport function TableRowElement(props: ElementProps) {\n  return (\n    <Wrapped {...withAs(props, \"tr\")} className={cn(props.className)}>\n      {props.children}\n    </Wrapped>\n  );\n}\n\nexport function TableCellElement(props: ElementProps) {\n  return (\n    <Wrapped\n      {...withAs(props, \"td\")}\n      className={cn(\"border border-border px-3 py-2 align-top\", props.className)}\n    >\n      {props.children}\n    </Wrapped>\n  );\n}\n\nexport function TableCellHeaderElement(props: ElementProps) {\n  return (\n    <Wrapped\n      {...withAs(props, \"th\")}\n      className={cn(\n        \"border border-border bg-muted/40 px-3 py-2 text-start font-semibold align-top\",\n        props.className\n      )}\n    >\n      {props.children}\n    </Wrapped>\n  );\n}\n\n// ImageElement is sealed in its own file (parts/image-element.tsx) — handles\n// resize handle + caption editing. Re-exported here for downstream barrel-import\n// continuity (editor-kit.ts imports it from this module).\nexport { ImageElement } from \"./image-element\";\n\nexport function MediaEmbedElement(props: ElementProps) {\n  const { element, editor } = props as PlateElementProps;\n  const url = (element as { url?: string }).url;\n  return (\n    <PlateElement\n      {...props}\n      className={cn(\"my-6\", props.className)}\n      attributes={{ ...(props.attributes as Record<string, unknown>), contentEditable: false } as never}\n    >\n      <div className=\"aspect-video overflow-hidden rounded-md border border-border bg-muted/30\">\n        {url ? (\n          <SafeEmbedView url={url} policy={getEmbedPolicy(editor)} />\n        ) : (\n          <div className=\"flex h-full items-center justify-center text-sm text-muted-foreground\">\n            (embed)\n          </div>\n        )}\n      </div>\n      {props.children}\n    </PlateElement>\n  );\n}\n\nexport function LinkElement(props: ElementProps) {\n  const { element } = props as PlateElementProps;\n  const href = safeHref((element as { url?: string }).url);\n  return (\n    <Wrapped\n      {...withAs(props, \"a\")}\n      attributes={{\n        ...(props.attributes as Record<string, unknown>),\n        // Unsafe scheme (javascript:, data:, ...) => no href; children kept.\n        ...(href ? { href, target: \"_blank\" } : {}),\n        rel: \"noopener noreferrer\",\n      } as never}\n      className={cn(\"text-primary underline underline-offset-2 hover:text-primary/80\", props.className)}\n    >\n      {props.children}\n    </Wrapped>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/rich-text-editor/parts/element-renderers.tsx"
    },
    {
      "path": "src/registry/components/data/rich-text-editor/parts/image-element.tsx",
      "content": "\"use client\";\n\nimport {\n  type ChangeEvent,\n  type ComponentProps,\n  type CSSProperties,\n  type MouseEvent as ReactMouseEvent,\n  useCallback,\n  useEffect,\n  useRef,\n  useState,\n} from \"react\";\nimport {\n  PlateElement,\n  type PlateElementProps,\n  useEditorRef,\n  useNodePath,\n  useReadOnly,\n} from \"platejs/react\";\nimport { cn } from \"@/lib/utils\";\n\ntype ElementProps = ComponentProps<typeof PlateElement>;\n\ninterface ImageNode {\n  url?: string;\n  alt?: string;\n  caption?: string;\n  width?: string | number;\n  height?: string | number;\n}\n\nconst MIN_WIDTH_PCT = 20;\nconst MAX_WIDTH_PCT = 100;\n\nfunction parseWidthPercent(width: string | number | undefined): number {\n  if (typeof width === \"number\") return width;\n  if (!width) return MAX_WIDTH_PCT;\n  const match = /^(\\d+(?:\\.\\d+)?)\\s*%$/.exec(width);\n  return match ? Number(match[1]) : MAX_WIDTH_PCT;\n}\n\nexport function ImageElement(props: ElementProps) {\n  const { element } = props as PlateElementProps;\n  const node = element as ImageNode & { type: string };\n  const url = node.url;\n  const alt = node.alt ?? \"\";\n  const caption = node.caption ?? \"\";\n\n  const editor = useEditorRef();\n  const path = useNodePath(element);\n  const readOnly = useReadOnly();\n\n  const widthPct = parseWidthPercent(node.width);\n  const [draftWidthPct, setDraftWidthPct] = useState<number | null>(null);\n  const wrapperRef = useRef<HTMLDivElement>(null);\n  const isDraggingRef = useRef(false);\n\n  const commitWidth = useCallback(\n    (next: number) => {\n      const clamped = Math.max(MIN_WIDTH_PCT, Math.min(MAX_WIDTH_PCT, next));\n      editor.tf.setNodes({ width: `${clamped.toFixed(0)}%` }, { at: path });\n    },\n    [editor, path]\n  );\n\n  const handleResizeStart = useCallback(\n    (e: ReactMouseEvent<HTMLButtonElement>) => {\n      e.preventDefault();\n      e.stopPropagation();\n      const wrapper = wrapperRef.current;\n      if (!wrapper) return;\n      const parent = wrapper.parentElement;\n      if (!parent) return;\n\n      const parentWidth = parent.getBoundingClientRect().width;\n      const startX = e.clientX;\n      const startPct = parseWidthPercent(node.width);\n      isDraggingRef.current = true;\n\n      const onMove = (ev: MouseEvent) => {\n        const deltaPx = ev.clientX - startX;\n        const deltaPct = (deltaPx / parentWidth) * 100;\n        const next = Math.max(\n          MIN_WIDTH_PCT,\n          Math.min(MAX_WIDTH_PCT, startPct + deltaPct)\n        );\n        setDraftWidthPct(next);\n      };\n\n      const onUp = (ev: MouseEvent) => {\n        const deltaPx = ev.clientX - startX;\n        const deltaPct = (deltaPx / parentWidth) * 100;\n        commitWidth(startPct + deltaPct);\n        setDraftWidthPct(null);\n        isDraggingRef.current = false;\n        document.removeEventListener(\"mousemove\", onMove);\n        document.removeEventListener(\"mouseup\", onUp);\n      };\n\n      document.addEventListener(\"mousemove\", onMove);\n      document.addEventListener(\"mouseup\", onUp);\n    },\n    [commitWidth, node.width]\n  );\n\n  // Cleanup if component unmounts mid-drag.\n  useEffect(() => {\n    return () => {\n      isDraggingRef.current = false;\n    };\n  }, []);\n\n  const handleCaptionChange = useCallback(\n    (e: ChangeEvent<HTMLInputElement>) => {\n      editor.tf.setNodes({ caption: e.target.value }, { at: path });\n    },\n    [editor, path]\n  );\n\n  const effectivePct = draftWidthPct ?? widthPct;\n  const wrapperStyle: CSSProperties = { width: `${effectivePct.toFixed(0)}%` };\n\n  return (\n    <PlateElement\n      {...props}\n      className={cn(\"my-6\", props.className)}\n      attributes={\n        {\n          ...(props.attributes as Record<string, unknown>),\n          contentEditable: false,\n        } as never\n      }\n    >\n      <figure className=\"group/img flex flex-col items-center\">\n        <div ref={wrapperRef} className=\"relative\" style={wrapperStyle}>\n          {url ? (\n            <img\n              src={url}\n              alt={alt}\n              loading=\"lazy\"\n              className=\"w-full rounded-md border border-border\"\n              draggable={false}\n            />\n          ) : (\n            <div className=\"flex aspect-video items-center justify-center rounded-md border border-dashed border-border bg-muted/30 text-sm text-muted-foreground\">\n              (image)\n            </div>\n          )}\n          {!readOnly ? (\n            <button\n              type=\"button\"\n              aria-label=\"Resize image\"\n              onMouseDown={handleResizeStart}\n              className={cn(\n                // dir-ok: resize handle sits on the edge that handleResizeStart drags by physical clientX delta (width grows rightward)\n                \"absolute right-0 top-1/2 -translate-y-1/2 translate-x-1/2\",\n                \"h-12 w-1.5 cursor-ew-resize rounded-full bg-primary/40\",\n                \"opacity-0 transition-opacity hover:opacity-100 group-hover/img:opacity-100\",\n                \"ring-1 ring-primary/20 hover:bg-primary/70\"\n              )}\n              tabIndex={-1}\n            />\n          ) : null}\n        </div>\n\n        {(caption || !readOnly) ? (\n          readOnly ? (\n            caption ? (\n              <figcaption className=\"mt-2 max-w-[80%] text-center text-xs text-muted-foreground\">\n                {caption}\n              </figcaption>\n            ) : null\n          ) : (\n            <input\n              type=\"text\"\n              value={caption}\n              onChange={handleCaptionChange}\n              placeholder=\"Caption (optional)\"\n              aria-label=\"Image caption\"\n              className={cn(\n                \"mt-2 w-3/4 max-w-prose bg-transparent text-center text-xs\",\n                \"text-muted-foreground placeholder:text-muted-foreground/60\",\n                \"focus:outline-none focus:ring-1 focus:ring-ring focus:rounded-sm\"\n              )}\n            />\n          )\n        ) : null}\n      </figure>\n      {props.children}\n    </PlateElement>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/rich-text-editor/parts/image-element.tsx"
    },
    {
      "path": "src/registry/components/data/rich-text-editor/parts/leaf-renderers.tsx",
      "content": "\"use client\";\n\nimport type { ComponentProps } from \"react\";\nimport { PlateLeaf } from \"platejs/react\";\nimport { cn } from \"@/lib/utils\";\n\ntype LeafProps = ComponentProps<typeof PlateLeaf>;\n\nexport function CodeLeaf(props: LeafProps) {\n  return (\n    <PlateLeaf\n      {...props}\n      as=\"code\"\n      className={cn(\n        \"rounded bg-muted px-1.5 py-0.5 font-mono text-[0.9em]\",\n        props.className\n      )}\n    >\n      {props.children}\n    </PlateLeaf>\n  );\n}\n\nexport function HighlightLeaf(props: LeafProps) {\n  return (\n    <PlateLeaf\n      {...props}\n      as=\"mark\"\n      className={cn(\n        \"rounded bg-primary/20 px-0.5 text-foreground\",\n        props.className\n      )}\n    >\n      {props.children}\n    </PlateLeaf>\n  );\n}\n\nexport function KbdLeaf(props: LeafProps) {\n  return (\n    <PlateLeaf\n      {...props}\n      as=\"kbd\"\n      className={cn(\n        \"rounded border border-border bg-muted px-1.5 py-0.5 font-mono text-[0.85em] shadow-sm\",\n        props.className\n      )}\n    >\n      {props.children}\n    </PlateLeaf>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/rich-text-editor/parts/leaf-renderers.tsx"
    },
    {
      "path": "src/registry/components/data/rich-text-editor/static-elements/static-element-renderers.tsx",
      "content": "import type { CSSProperties, HTMLAttributes, ReactNode } from \"react\";\nimport { cn } from \"@/lib/utils\";\nimport { getEmbedPolicy, safeHref } from \"../lib/safe-embed\";\nimport { SafeEmbedView } from \"../parts/safe-embed-view\";\n\ninterface StaticElementProps {\n  attributes?: Record<string, unknown>;\n  children?: ReactNode;\n  element: { type: string; [key: string]: unknown };\n  /** Passed by Plate's static pipeline; carries the per-instance embed policy. */\n  editor?: unknown;\n  className?: string;\n  style?: CSSProperties;\n}\n\ninterface StaticLeafProps {\n  attributes?: Record<string, unknown>;\n  children?: ReactNode;\n  leaf: { [key: string]: unknown };\n  className?: string;\n  style?: CSSProperties;\n}\n\n// Plate's `attributes` carry data-slate-* metadata + a ref typed for various\n// element kinds. We render bare HTML, so we cast to a permissive shape here.\n// Strip `ref` — it's typed for a specific HTML element and TS can't reconcile\n// across our union of output tags. The viewer is read-only; refs aren't load-bearing.\ntype Attrs = Omit<HTMLAttributes<HTMLElement>, \"color\" | \"ref\">;\n\nfunction spreadAttrs(attributes: Record<string, unknown> | undefined): Attrs {\n  if (!attributes) return {};\n  // eslint-disable-next-line @typescript-eslint/no-unused-vars\n  const { ref: _ref, ...rest } = attributes as { ref?: unknown };\n  return rest as Attrs;\n}\n\nexport function StaticParagraph(props: StaticElementProps) {\n  return (\n    <p {...spreadAttrs(props.attributes)} className={cn(\"my-4 leading-relaxed\", props.className)}>\n      {props.children}\n    </p>\n  );\n}\n\nexport function StaticH1(props: StaticElementProps) {\n  return (\n    <h1 {...spreadAttrs(props.attributes)} className={cn(\"mt-10 mb-4 text-4xl font-serif font-bold tracking-tight\", props.className)}>\n      {props.children}\n    </h1>\n  );\n}\n\nexport function StaticH2(props: StaticElementProps) {\n  return (\n    <h2 {...spreadAttrs(props.attributes)} className={cn(\"mt-8 mb-3 text-3xl font-serif font-bold tracking-tight\", props.className)}>\n      {props.children}\n    </h2>\n  );\n}\n\nexport function StaticH3(props: StaticElementProps) {\n  return (\n    <h3 {...spreadAttrs(props.attributes)} className={cn(\"mt-6 mb-2 text-2xl font-serif font-bold\", props.className)}>\n      {props.children}\n    </h3>\n  );\n}\n\nexport function StaticH4(props: StaticElementProps) {\n  return (\n    <h4 {...spreadAttrs(props.attributes)} className={cn(\"mt-4 mb-2 text-xl font-serif font-semibold\", props.className)}>\n      {props.children}\n    </h4>\n  );\n}\n\nexport function StaticBlockquote(props: StaticElementProps) {\n  return (\n    <blockquote\n      {...spreadAttrs(props.attributes)}\n      className={cn(\n        \"my-6 border-s-4 border-primary ps-6 py-2 italic text-muted-foreground bg-muted/30 rounded-e-md\",\n        props.className\n      )}\n    >\n      {props.children}\n    </blockquote>\n  );\n}\n\nexport function StaticHr(props: StaticElementProps) {\n  return (\n    <div {...spreadAttrs(props.attributes)} className={cn(\"my-8\", props.className)}>\n      <hr className=\"border-border\" />\n      {props.children}\n    </div>\n  );\n}\n\nexport function StaticList(props: StaticElementProps) {\n  const element = props.element as { listStyleType?: string; indent?: number };\n  const listStyleType = element.listStyleType ?? \"disc\";\n  const indent = (element.indent ?? 1) - 1;\n  const ordered = listStyleType === \"decimal\";\n  const className = cn(\n    \"my-4 ms-6\",\n    ordered ? \"list-decimal\" : \"list-disc\",\n    props.className\n  );\n  const style = {\n    ...(props.style ?? {}),\n    marginLeft: indent > 0 ? `${indent * 1.5}rem` : undefined,\n  };\n  const attrs = spreadAttrs(props.attributes);\n\n  if (ordered) {\n    return (\n      <ol {...attrs} className={className} style={style}>\n        <li>{props.children}</li>\n      </ol>\n    );\n  }\n  return (\n    <ul {...attrs} className={className} style={style}>\n      <li>{props.children}</li>\n    </ul>\n  );\n}\n\nexport function StaticCodeBlock(props: StaticElementProps) {\n  return (\n    <pre\n      {...spreadAttrs(props.attributes)}\n      className={cn(\n        \"my-6 overflow-x-auto rounded-md border border-border bg-muted p-4 font-mono text-sm\",\n        props.className\n      )}\n    >\n      <code>{props.children}</code>\n    </pre>\n  );\n}\n\nexport function StaticCodeLine(props: StaticElementProps) {\n  return (\n    <div {...spreadAttrs(props.attributes)} className={cn(\"font-mono\", props.className)}>\n      {props.children}\n    </div>\n  );\n}\n\nexport function StaticTable(props: StaticElementProps) {\n  return (\n    <div {...spreadAttrs(props.attributes)} className={cn(\"my-6 overflow-x-auto\", props.className)}>\n      <table className=\"w-full border-collapse text-sm\">\n        <tbody>{props.children}</tbody>\n      </table>\n    </div>\n  );\n}\n\nexport function StaticTableRow(props: StaticElementProps) {\n  return <tr {...spreadAttrs(props.attributes)} className={cn(props.className)}>{props.children}</tr>;\n}\n\nexport function StaticTableCell(props: StaticElementProps) {\n  return (\n    <td\n      {...spreadAttrs(props.attributes)}\n      className={cn(\"border border-border px-3 py-2 align-top\", props.className)}\n    >\n      {props.children}\n    </td>\n  );\n}\n\nexport function StaticTableCellHeader(props: StaticElementProps) {\n  return (\n    <th\n      {...spreadAttrs(props.attributes)}\n      className={cn(\n        \"border border-border bg-muted/40 px-3 py-2 text-start font-semibold align-top\",\n        props.className\n      )}\n    >\n      {props.children}\n    </th>\n  );\n}\n\nexport function StaticImage(props: StaticElementProps) {\n  const element = props.element as {\n    url?: string;\n    alt?: string;\n    caption?: string;\n    width?: string | number;\n  };\n  // Width comes through as a percentage string (e.g. \"75%\") set by the editor.\n  // Numbers are interpreted as pixels for backward compatibility.\n  const widthStyle =\n    element.width !== undefined\n      ? typeof element.width === \"number\"\n        ? `${element.width}px`\n        : element.width\n      : undefined;\n\n  return (\n    <div {...spreadAttrs(props.attributes)} className={cn(\"my-6\", props.className)}>\n      <figure className=\"flex flex-col items-center\">\n        {element.url ? (\n          <img\n            src={element.url}\n            alt={element.alt ?? \"\"}\n            loading=\"lazy\"\n            className=\"rounded-md border border-border\"\n            style={widthStyle ? { width: widthStyle } : undefined}\n          />\n        ) : null}\n        {element.caption ? (\n          <figcaption className=\"mt-2 max-w-[80%] text-center text-xs text-muted-foreground\">\n            {element.caption}\n          </figcaption>\n        ) : null}\n      </figure>\n      {props.children}\n    </div>\n  );\n}\n\nexport function StaticMediaEmbed(props: StaticElementProps) {\n  const element = props.element as { url?: string };\n  return (\n    <div {...spreadAttrs(props.attributes)} className={cn(\"my-6\", props.className)}>\n      {element.url ? (\n        <div className=\"aspect-video overflow-hidden rounded-md border border-border bg-muted/30\">\n          <SafeEmbedView url={element.url} policy={getEmbedPolicy(props.editor)} />\n        </div>\n      ) : null}\n      {props.children}\n    </div>\n  );\n}\n\nexport function StaticLink(props: StaticElementProps) {\n  const element = props.element as { url?: string };\n  const href = safeHref(element.url);\n  return (\n    <a\n      {...spreadAttrs(props.attributes)}\n      // Unsafe scheme (javascript:, data:, ...) => no href; children kept.\n      href={href}\n      target={href ? \"_blank\" : undefined}\n      rel=\"noopener noreferrer\"\n      className={cn(\n        \"text-primary underline underline-offset-2 hover:text-primary/80\",\n        props.className\n      )}\n    >\n      {props.children}\n    </a>\n  );\n}\n\nexport function StaticCodeLeaf(props: StaticLeafProps) {\n  return (\n    <code\n      {...(spreadAttrs(props.attributes) as HTMLAttributes<HTMLElement>)}\n      className={cn(\"rounded bg-muted px-1.5 py-0.5 font-mono text-[0.9em]\", props.className)}\n    >\n      {props.children}\n    </code>\n  );\n}\n\nexport function StaticHighlightLeaf(props: StaticLeafProps) {\n  return (\n    <mark\n      {...(spreadAttrs(props.attributes) as HTMLAttributes<HTMLElement>)}\n      className={cn(\"rounded bg-primary/20 px-0.5 text-foreground\", props.className)}\n    >\n      {props.children}\n    </mark>\n  );\n}\n\nexport function StaticKbdLeaf(props: StaticLeafProps) {\n  return (\n    <kbd\n      {...(spreadAttrs(props.attributes) as HTMLAttributes<HTMLElement>)}\n      className={cn(\n        \"rounded border border-border bg-muted px-1.5 py-0.5 font-mono text-[0.85em] shadow-sm\",\n        props.className\n      )}\n    >\n      {props.children}\n    </kbd>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/rich-text-editor/static-elements/static-element-renderers.tsx"
    },
    {
      "path": "src/registry/components/data/rich-text-editor/lib/lowlight-instance.ts",
      "content": "import { createLowlight } from \"lowlight\";\n\nimport bash from \"highlight.js/lib/languages/bash\";\nimport css from \"highlight.js/lib/languages/css\";\nimport diff from \"highlight.js/lib/languages/diff\";\nimport go from \"highlight.js/lib/languages/go\";\nimport java from \"highlight.js/lib/languages/java\";\nimport javascript from \"highlight.js/lib/languages/javascript\";\nimport json from \"highlight.js/lib/languages/json\";\nimport markdown from \"highlight.js/lib/languages/markdown\";\nimport python from \"highlight.js/lib/languages/python\";\nimport rust from \"highlight.js/lib/languages/rust\";\nimport shell from \"highlight.js/lib/languages/shell\";\nimport sql from \"highlight.js/lib/languages/sql\";\nimport typescript from \"highlight.js/lib/languages/typescript\";\nimport xml from \"highlight.js/lib/languages/xml\";\nimport yaml from \"highlight.js/lib/languages/yaml\";\n\n// 15 languages cover ~95% of realistic rich-text code blocks.\n// Selective registration keeps the bundle small (~30KB gzip vs ~250KB\n// for `lowlight/all`). Add more via `lowlight.register(...)` if needed.\nexport const lowlight = createLowlight();\n\nlowlight.register(\"bash\", bash);\nlowlight.register(\"sh\", shell);\nlowlight.register(\"shell\", shell);\nlowlight.register(\"css\", css);\nlowlight.register(\"diff\", diff);\nlowlight.register(\"go\", go);\nlowlight.register(\"html\", xml);\nlowlight.register(\"xml\", xml);\nlowlight.register(\"java\", java);\nlowlight.register(\"javascript\", javascript);\nlowlight.register(\"js\", javascript);\nlowlight.register(\"json\", json);\nlowlight.register(\"markdown\", markdown);\nlowlight.register(\"md\", markdown);\nlowlight.register(\"python\", python);\nlowlight.register(\"py\", python);\nlowlight.register(\"rust\", rust);\nlowlight.register(\"rs\", rust);\nlowlight.register(\"sql\", sql);\nlowlight.register(\"typescript\", typescript);\nlowlight.register(\"ts\", typescript);\nlowlight.register(\"yaml\", yaml);\nlowlight.register(\"yml\", yaml);\n",
      "type": "registry:component",
      "target": "components/rich-text-editor/lib/lowlight-instance.ts"
    },
    {
      "path": "src/registry/components/data/rich-text-editor/lib/serialize-html.ts",
      "content": "import { createStaticEditor, serializeHtml } from \"platejs/static\";\n\nimport { setEmbedPolicy, type EmbedPolicy } from \"./safe-embed\";\nimport { richTextViewerPlugins } from \"../plugins/viewer-kit\";\nimport type { RichTextValue } from \"../types\";\n\nexport interface SerializeHtmlOptions extends EmbedPolicy {\n  /** Drop className attributes from the output. Default: false. */\n  stripClassNames?: boolean;\n  /**\n   * Class names to keep when `stripClassNames` is true. Useful when you\n   * want to preserve specific design-system classes but drop the rest.\n   */\n  preserveClassNames?: string[];\n  /**\n   * Drop data-slate-* attributes from the output. Default: true —\n   * exported HTML usually shouldn't carry editor metadata.\n   */\n  stripDataAttributes?: boolean;\n}\n\n/**\n * Serialize an RichTextValue to a static HTML string.\n *\n * Useful at export boundaries — RSS feeds, email digests, OG tag previews,\n * static-site rendering. Don't round-trip through HTML for storage; keep\n * JSON canonical and call this when you need the HTML form.\n *\n * Async because Plate uses `react-dom/server` under the hood. Server-only;\n * don't call from client components.\n */\nexport async function serializeRichTextToHtml(\n  value: RichTextValue,\n  options: SerializeHtmlOptions = {}\n): Promise<string> {\n  const {\n    stripClassNames = false,\n    preserveClassNames,\n    stripDataAttributes = true,\n    embedAllowList,\n    isEmbedAllowed,\n  } = options;\n\n  const editor = createStaticEditor({\n    plugins: richTextViewerPlugins,\n    value,\n  });\n\n  setEmbedPolicy(editor, { embedAllowList, isEmbedAllowed });\n\n  return serializeHtml(editor, {\n    stripClassNames,\n    preserveClassNames,\n    stripDataAttributes,\n  });\n}\n",
      "type": "registry:component",
      "target": "components/rich-text-editor/lib/serialize-html.ts"
    },
    {
      "path": "src/registry/components/data/rich-text-editor/lib/safe-embed.ts",
      "content": "/**\n * Safe embeds + safe hrefs (v0.4.0).\n *\n * Pure logic — no React, no DOM — so it is shared by the client editor, the\n * server-renderable viewer and the HTML serializer, and is unit-testable in\n * the node project.\n *\n * Threat model: a stored value (or HTML pasted into the editor) can carry\n * `{ type: \"media_embed\", url }` and `{ type: \"a\", url }` nodes with an\n * arbitrary `url`. Rendering those verbatim gives an attacker an arbitrary\n * iframe (clickjacking, drive-by content, same-origin script) or a\n * `javascript:` link.\n */\n\n/** Hosts allowed to render as an iframe unless the host passes its own list. */\nexport const EMBED_DEFAULT_ALLOW_LIST: readonly string[] = [\n  \"www.youtube.com\",\n  \"youtube.com\",\n  \"www.youtube-nocookie.com\",\n  \"player.vimeo.com\",\n];\n\n/**\n * Sandbox applied to every embed iframe. `allow-same-origin` is required for\n * the major video players to work; it is only safe because the frame is a\n * DIFFERENT origin. Never add `allow-top-navigation*`.\n */\nexport const EMBED_SANDBOX =\n  \"allow-scripts allow-same-origin allow-presentation allow-popups allow-popups-to-escape-sandbox\";\n\nexport const EMBED_REFERRER_POLICY = \"strict-origin-when-cross-origin\" as const;\nexport const EMBED_ALLOW = \"fullscreen; picture-in-picture; encrypted-media\";\n\n/** Overridable default strings (kept in one place so a labels prop can land later). */\nexport const EMBED_DEFAULT_LABELS = {\n  iframeTitle: \"Embedded content\",\n} as const;\n\nexport interface EmbedPolicy {\n  /**\n   * Allowed embed hostnames. `*.example.com` matches any subdomain (not the\n   * apex). REPLACES the default list.\n   */\n  embedAllowList?: string[];\n  /** Custom predicate. When provided it wins over `embedAllowList`. */\n  isEmbedAllowed?: (url: URL) => boolean;\n}\n\nexport type EmbedResolution =\n  | { kind: \"iframe\"; src: string }\n  | { kind: \"link\"; href: string | undefined; text: string };\n\nfunction hostMatches(host: string, pattern: string): boolean {\n  const h = host.toLowerCase();\n  const p = pattern.trim().toLowerCase();\n  if (!p) return false;\n  if (p.startsWith(\"*.\")) {\n    const suffix = p.slice(1); // \".example.com\"\n    return h.length > suffix.length && h.endsWith(suffix);\n  }\n  return h === p;\n}\n\n/**\n * Decide how to render an embed URL. Always requires an absolute `https:` URL;\n * then `isEmbedAllowed` (if given) or the host list decides.\n */\nexport function resolveEmbed(\n  rawUrl: string,\n  policy: EmbedPolicy = {}\n): EmbedResolution {\n  const fallback: EmbedResolution = {\n    kind: \"link\",\n    href: safeHref(rawUrl),\n    text: rawUrl,\n  };\n  let parsed: URL;\n  try {\n    parsed = new URL(rawUrl.trim());\n  } catch {\n    return fallback;\n  }\n  if (parsed.protocol !== \"https:\") return fallback;\n  // Credentials in an embed URL serve no player and only obscure the real host.\n  if (parsed.username || parsed.password) return fallback;\n\n  let allowed: boolean;\n  if (policy.isEmbedAllowed) {\n    try {\n      allowed = policy.isEmbedAllowed(parsed) === true;\n    } catch {\n      allowed = false;\n    }\n  } else {\n    const list = policy.embedAllowList ?? EMBED_DEFAULT_ALLOW_LIST;\n    allowed = list.some((p) => hostMatches(parsed.hostname, p));\n  }\n  return allowed ? { kind: \"iframe\", src: parsed.href } : fallback;\n}\n\nconst SAFE_SCHEMES = new Set([\"http\", \"https\", \"mailto\", \"tel\"]);\n// ASCII control chars, DEL and whitespace. Browsers strip tab/CR/LF inside a\n// URL before parsing the scheme, so `java\\tscript:` is a live javascript: URL.\nconst STRIP = /[\\u0000- \\u007f]/g;\n\n/**\n * Return `url` (trimmed) when it is safe to put in an `href`, else\n * `undefined`. Allows http, https, mailto, tel and scheme-less relative URLs\n * (`/x`, `#x`, `?x`, `./x`, `../x`, `x/y`).\n */\nexport function safeHref(url: unknown): string | undefined {\n  if (typeof url !== \"string\") return undefined;\n  const trimmed = url.trim();\n  if (!trimmed) return undefined;\n  const cleaned = trimmed.replace(STRIP, \"\");\n  const match = /^([a-zA-Z][a-zA-Z0-9+.-]*):/.exec(cleaned);\n  if (match) {\n    return SAFE_SCHEMES.has(match[1].toLowerCase()) ? trimmed : undefined;\n  }\n  return trimmed;\n}\n\n/** True for an absolute http(s) URL (used for the toolbar image-URL prompt). */\nexport function isHttpUrl(url: unknown): url is string {\n  if (typeof url !== \"string\") return false;\n  try {\n    const p = new URL(url.trim());\n    return p.protocol === \"https:\" || p.protocol === \"http:\";\n  } catch {\n    return false;\n  }\n}\n\n// ── Per-editor policy ────────────────────────────────────────────────────\n// Element renderers are plugin components built from module-level arrays, so\n// per-instance props reach them through the editor object (both the Plate\n// editor and the static editor are passed to renderers as `props.editor`).\n// A WeakMap is SSR-safe, needs no React context (the viewer is a server\n// component), and works identically for `serializeHtml`.\n\nconst policies = new WeakMap<object, EmbedPolicy>();\n\nexport function setEmbedPolicy(editor: object, policy: EmbedPolicy): void {\n  policies.set(editor, policy);\n}\n\nexport function getEmbedPolicy(editor: unknown): EmbedPolicy {\n  if (editor && typeof editor === \"object\") {\n    return policies.get(editor) ?? {};\n  }\n  return {};\n}\n",
      "type": "registry:component",
      "target": "components/rich-text-editor/lib/safe-embed.ts"
    },
    {
      "path": "src/registry/components/data/rich-text-editor/parts/safe-embed-view.tsx",
      "content": "import {\n  EMBED_ALLOW,\n  EMBED_DEFAULT_LABELS,\n  EMBED_REFERRER_POLICY,\n  EMBED_SANDBOX,\n  resolveEmbed,\n  type EmbedPolicy,\n} from \"../lib/safe-embed\";\n\n/**\n * The box contents shared by the editor's `MediaEmbedElement` and the static\n * viewer's `StaticMediaEmbed`: a sandboxed iframe for allowed https hosts, a\n * plain link card otherwise. No directive on purpose — no hooks, so it renders\n * in both server and client trees.\n */\nexport function SafeEmbedView({\n  url,\n  policy,\n}: {\n  url: string;\n  policy: EmbedPolicy;\n}) {\n  const result = resolveEmbed(url, policy);\n  if (result.kind === \"iframe\") {\n    return (\n      <iframe\n        src={result.src}\n        title={EMBED_DEFAULT_LABELS.iframeTitle}\n        className=\"h-full w-full\"\n        sandbox={EMBED_SANDBOX}\n        referrerPolicy={EMBED_REFERRER_POLICY}\n        loading=\"lazy\"\n        allow={EMBED_ALLOW}\n        allowFullScreen\n      />\n    );\n  }\n  return (\n    <div className=\"flex h-full items-center justify-center p-4 text-sm\">\n      {result.href ? (\n        <a\n          href={result.href}\n          target=\"_blank\"\n          rel=\"noopener noreferrer nofollow\"\n          className=\"break-all text-primary underline underline-offset-2 hover:text-primary/80\"\n        >\n          {result.text}\n        </a>\n      ) : (\n        <span className=\"break-all text-muted-foreground\">{result.text}</span>\n      )}\n    </div>\n  );\n}\n",
      "type": "registry:component",
      "target": "components/rich-text-editor/parts/safe-embed-view.tsx"
    }
  ],
  "meta": {
    "version": "0.4.1",
    "status": "alpha"
  },
  "categories": [
    "data",
    "richtext"
  ],
  "type": "registry:block"
}