{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "code-editor",
  "title": "Code Editor",
  "description": "A composable code editor built on CodeMirror, with a controlled document, toolbar, status bar and extension declarations.",
  "dependencies": [
    "@codemirror/commands",
    "@codemirror/state",
    "@codemirror/view",
    "cn",
    "lucide-react"
  ],
  "registryDependencies": [
    "litingyes/blocove/code-editor-extension",
    "button",
    "toggle",
    "tooltip"
  ],
  "files": [
    {
      "path": "src/registry/blocove/ui/code-editor/editor.tsx",
      "content": "import type { Extension } from '@codemirror/state'\nimport type { ComponentProps, ReactNode, RefObject } from 'react'\nimport type {\n  CodeEditorExtensionConfig,\n  CodeEditorSurfaceConfig,\n  CodeEditorSurfaceInstance,\n} from '@/lib/blocove/code-editor-extension'\nimport {\n  defaultKeymap,\n  history,\n  historyKeymap,\n  indentWithTab,\n  redo,\n  redoDepth,\n  undo,\n  undoDepth,\n} from '@codemirror/commands'\nimport { Compartment, EditorState } from '@codemirror/state'\nimport {\n  drawSelection,\n  dropCursor,\n  EditorView,\n  keymap,\n  placeholder as placeholderExtension,\n} from '@codemirror/view'\nimport { cn } from 'cn'\nimport { CheckIcon, CopyIcon, Redo2Icon, Undo2Icon, WrapTextIcon } from 'lucide-react'\nimport {\n  createContext,\n  use,\n  useCallback,\n  useEffect,\n  useReducer,\n  useRef,\n  useState,\n} from 'react'\nimport { Button } from '@/components/ui/button'\nimport { Toggle } from '@/components/ui/toggle'\nimport {\n  Tooltip,\n  TooltipContent,\n  TooltipProvider,\n  TooltipTrigger,\n} from '@/components/ui/tooltip'\nimport {\n  codeEditorExtensionSignature,\n  collectCodeEditorChildren,\n  resolveCodeEditorExtensions,\n  resolveCodeEditorSurface,\n} from '@/lib/blocove/code-editor-extension'\n\nexport interface CodeEditorProps {\n  /** Controlled document. */\n  value?: string\n  /** Initial document when uncontrolled. */\n  defaultValue?: string\n  /** Called with the new document whenever it changes. */\n  onChange?: (value: string) => void\n  /** Language shared by the highlighting and language items. */\n  language?: string\n  /** Placeholder shown while the document is empty. */\n  placeholder?: string\n  /** Whether the document can be edited. */\n  editable?: boolean\n  /**\n   * Read-only mode: the document can be selected and copied, but not edited.\n   * Chunk controls from the diff item keep working, since they are widgets.\n   */\n  readOnly?: boolean\n  /** Focus the editor once it is ready. */\n  autoFocus?: boolean\n  /** Initial line wrapping state. */\n  lineWrapping?: boolean\n  /** Called when the line wrapping toggle changes. */\n  onLineWrappingChange?: (lineWrapping: boolean) => void\n  /** Additional CodeMirror extensions, appended after the declared ones. */\n  extensions?: Extension\n  /** Called once the editor view is created. */\n  onReady?: (view: EditorView) => void\n  className?: string\n  /** Editor UI and extension declarations. */\n  children?: ReactNode\n}\n\ninterface CodeEditorComponentConfig {\n  value?: string\n  defaultValue?: string\n  onChange?: (value: string) => void\n  onReady?: (view: EditorView) => void\n  autoFocus: boolean\n  placeholder: string\n  language?: string\n  /** Extension declarations collected from the children. */\n  declared: CodeEditorExtensionConfig[]\n  /**\n   * The declaration that replaces the single-editor surface, if any. Only the\n   * split diff uses it, so the shell keeps one view by default.\n   */\n  surface?: CodeEditorSurfaceConfig\n  /** Extra extensions passed through the `extensions` prop. */\n  extra?: Extension\n}\n\ninterface CodeEditorContextValue {\n  view: EditorView | null\n  setView: (view: EditorView | null) => void\n  subscribe: (listener: () => void) => () => void\n  notify: () => void\n  configRef: RefObject<CodeEditorComponentConfig>\n  signature: string\n  value?: string\n  editable: boolean\n  readOnly: boolean\n  lineWrapping: boolean\n  setLineWrapping: (lineWrapping: boolean) => void\n}\n\nconst CodeEditorContext = createContext<CodeEditorContextValue | null>(null)\n\nexport function useCodeEditor() {\n  const context = use(CodeEditorContext)\n\n  if (!context) {\n    throw new Error('useCodeEditor must be used inside <CodeEditor>.')\n  }\n\n  return context\n}\n\n/**\n * Re-renders the calling component whenever the editor state changes, so\n * chrome components can read the cursor position and the history depth.\n */\nexport function useCodeEditorState() {\n  const { subscribe } = useCodeEditor()\n  const [, forceUpdate] = useReducer((version: number) => version + 1, 0)\n\n  useEffect(() => subscribe(forceUpdate), [subscribe])\n}\n\nconst baseTheme = EditorView.theme({\n  '&': {\n    height: '100%',\n    fontSize: '13px',\n    backgroundColor: 'transparent',\n  },\n  '&.cm-focused': {\n    outline: 'none',\n  },\n  '.cm-scroller': {\n    fontFamily: 'var(--font-mono, ui-monospace, SFMono-Regular, Menlo, monospace)',\n    lineHeight: '1.7',\n  },\n  '.cm-content': {\n    padding: '0.75rem 0',\n    caretColor: 'currentColor',\n  },\n  '.cm-line': {\n    padding: '0 0.75rem',\n  },\n  '.cm-gutters': {\n    backgroundColor: 'transparent',\n    color: 'var(--muted-foreground)',\n    border: 'none',\n  },\n  '.cm-activeLine': {\n    backgroundColor: 'color-mix(in oklab, currentColor 5%, transparent)',\n  },\n  '.cm-activeLineGutter': {\n    backgroundColor: 'transparent',\n    color: 'var(--foreground)',\n  },\n  '.cm-cursor, .cm-dropCursor': {\n    borderLeftColor: 'currentColor',\n  },\n  '&.cm-focused .cm-selectionBackground, .cm-selectionBackground, .cm-content ::selection': {\n    backgroundColor: 'color-mix(in oklab, var(--ring) 35%, transparent)',\n  },\n  '.cm-placeholder': {\n    color: 'var(--muted-foreground)',\n  },\n  '.cm-panels': {\n    backgroundColor: 'var(--background)',\n    color: 'var(--foreground)',\n  },\n})\n\n/**\n * Code editor root. Registers the extensions declared by its children, owns the\n * controlled document and renders the editor UI.\n */\nexport function CodeEditor({\n  value,\n  defaultValue,\n  onChange,\n  language,\n  placeholder = 'Type some code…',\n  editable = true,\n  readOnly = false,\n  autoFocus = false,\n  lineWrapping,\n  onLineWrappingChange,\n  extensions,\n  onReady,\n  className,\n  children,\n}: CodeEditorProps) {\n  const { extensions: declared, surface, content } = collectCodeEditorChildren(children)\n  const signature = codeEditorExtensionSignature(declared)\n  const [view, setView] = useState<EditorView | null>(null)\n  const [internalLineWrapping, setInternalLineWrapping] = useState(lineWrapping ?? false)\n  const resolvedLineWrapping = lineWrapping ?? internalLineWrapping\n  const listenersRef = useRef(new Set<() => void>())\n  const configRef = useRef<CodeEditorComponentConfig>({\n    value,\n    defaultValue,\n    onChange,\n    onReady,\n    autoFocus,\n    placeholder,\n    language,\n    declared,\n    surface,\n    extra: extensions,\n  })\n\n  configRef.current = {\n    value,\n    defaultValue,\n    onChange,\n    onReady,\n    autoFocus,\n    placeholder,\n    language,\n    declared,\n    surface,\n    extra: extensions,\n  }\n\n  const subscribe = useCallback((listener: () => void) => {\n    listenersRef.current.add(listener)\n\n    return () => {\n      listenersRef.current.delete(listener)\n    }\n  }, [])\n\n  const notify = useCallback(() => {\n    for (const listener of listenersRef.current) {\n      listener()\n    }\n  }, [])\n\n  const setLineWrapping = useCallback((next: boolean) => {\n    setInternalLineWrapping(next)\n    onLineWrappingChange?.(next)\n  }, [onLineWrappingChange])\n\n  return (\n    <CodeEditorContext\n      value={{\n        view,\n        setView,\n        subscribe,\n        notify,\n        configRef,\n        signature,\n        value,\n        editable,\n        readOnly,\n        lineWrapping: resolvedLineWrapping,\n        setLineWrapping,\n      }}\n    >\n      <div\n        data-slot=\"code-editor\"\n        className={cn(\n          'flex w-full flex-col overflow-hidden rounded-lg border border-input bg-transparent text-foreground transition-colors focus-within:border-ring focus-within:ring-3 focus-within:ring-ring/50 dark:bg-input/30',\n          className,\n        )}\n      >\n        {content}\n      </div>\n    </CodeEditorContext>\n  )\n}\n\nexport type CodeEditorContentProps = ComponentProps<'div'>\n\n/**\n * The editable surface. Creates the CodeMirror view once the container is\n * mounted and keeps it in sync with the controlled document. When a declaration\n * asks for its own surface — the split diff owns two editors — that surface\n * builds the views instead and the single editor is skipped.\n */\nexport function CodeEditorContent({\n  className,\n  ...props\n}: CodeEditorContentProps) {\n  const {\n    configRef,\n    signature,\n    view,\n    setView,\n    notify,\n    editable,\n    readOnly,\n    value,\n    lineWrapping,\n  } = useCodeEditor()\n  const hostRef = useRef<HTMLDivElement>(null)\n  const editableCompartmentRef = useRef(new Compartment())\n  const lineWrappingCompartmentRef = useRef(new Compartment())\n  const editableRef = useRef(editable)\n  const readOnlyRef = useRef(readOnly)\n  const lineWrappingRef = useRef(lineWrapping)\n  const notifyRef = useRef(notify)\n  const lastEmittedRef = useRef<string | null>(null)\n  const surfaceRef = useRef<CodeEditorSurfaceInstance | null>(null)\n\n  editableRef.current = editable\n  readOnlyRef.current = readOnly\n  lineWrappingRef.current = lineWrapping\n  notifyRef.current = notify\n\n  useEffect(() => {\n    const host = hostRef.current\n\n    if (!host) {\n      return\n    }\n\n    const config = configRef.current\n    const doc = config.value ?? config.defaultValue ?? ''\n\n    lastEmittedRef.current = doc\n\n    const head: Extension[] = [\n      history(),\n      drawSelection(),\n      dropCursor(),\n      EditorState.allowMultipleSelections.of(true),\n      keymap.of([\n        ...defaultKeymap,\n        ...historyKeymap,\n        indentWithTab,\n      ]),\n      placeholderExtension(config.placeholder),\n      baseTheme,\n    ]\n    const tail: Extension[] = [\n      ...resolveCodeEditorExtensions(config.declared, {\n        language: config.language,\n      }),\n      ...(config.extra\n        ? [config.extra]\n        : []),\n    ]\n    // Only the primary side reports the document: a comparison side recreates\n    // text too, and that must not look like an edit.\n    const contentListener = EditorView.updateListener.of((update) => {\n      if (update.docChanged) {\n        const next = update.state.doc.toString()\n\n        if (next !== lastEmittedRef.current) {\n          lastEmittedRef.current = next\n          configRef.current.onChange?.(next)\n        }\n      }\n\n      notifyRef.current()\n    })\n    const chromeListener = EditorView.updateListener.of(() => {\n      notifyRef.current()\n    })\n\n    const mount = resolveCodeEditorSurface(config.surface, {\n      language: config.language,\n    })\n    const surfaceInstance = mount\n      ? mount({\n          host,\n          doc,\n          primaryExtensions: [\n            ...head,\n            ...tail,\n            contentListener,\n          ],\n          secondaryExtensions: [\n            ...head,\n            ...tail,\n            chromeListener,\n          ],\n          options: {\n            editable: editableRef.current,\n            readOnly: readOnlyRef.current,\n            lineWrapping: lineWrappingRef.current,\n            autoFocus: config.autoFocus,\n          },\n        })\n      : null\n\n    if (surfaceInstance) {\n      surfaceRef.current = surfaceInstance\n      setView(surfaceInstance.view)\n      config.onReady?.(surfaceInstance.view)\n\n      return () => {\n        surfaceRef.current = null\n        setView(null)\n        surfaceInstance.destroy()\n      }\n    }\n\n    const state = EditorState.create({\n      doc,\n      extensions: [\n        ...head,\n        editableCompartmentRef.current.of([\n          EditorView.editable.of(editableRef.current && !readOnlyRef.current),\n          EditorState.readOnly.of(readOnlyRef.current),\n        ]),\n        lineWrappingCompartmentRef.current.of(\n          lineWrappingRef.current\n            ? EditorView.lineWrapping\n            : [],\n        ),\n        ...tail,\n        contentListener,\n      ],\n    })\n\n    const instance = new EditorView({ state, parent: host })\n\n    setView(instance)\n    config.onReady?.(instance)\n\n    if (config.autoFocus) {\n      instance.focus()\n    }\n\n    return () => {\n      setView(null)\n      instance.destroy()\n    }\n    // The extension signature is the identity of the editor configuration: a\n    // different set of declarations recreates the view.\n  }, [\n    configRef,\n    setView,\n    signature,\n  ])\n\n  useEffect(() => {\n    const surface = surfaceRef.current\n\n    if (surface) {\n      surface.update({\n        editable: editableRef.current,\n        readOnly: readOnlyRef.current,\n        lineWrapping: lineWrappingRef.current,\n        autoFocus: false,\n      })\n      return\n    }\n\n    if (!view) {\n      return\n    }\n\n    view.dispatch({\n      effects: editableCompartmentRef.current.reconfigure([\n        EditorView.editable.of(editable && !readOnly),\n        EditorState.readOnly.of(readOnly),\n      ]),\n    })\n  }, [editable, readOnly, view])\n\n  useEffect(() => {\n    const surface = surfaceRef.current\n\n    if (surface) {\n      surface.update({\n        editable: editableRef.current,\n        readOnly: readOnlyRef.current,\n        lineWrapping: lineWrappingRef.current,\n        autoFocus: false,\n      })\n      return\n    }\n\n    if (!view) {\n      return\n    }\n\n    view.dispatch({\n      effects: lineWrappingCompartmentRef.current.reconfigure(\n        lineWrapping\n          ? EditorView.lineWrapping\n          : [],\n      ),\n    })\n  }, [lineWrapping, view])\n\n  useEffect(() => {\n    if (!view || value === undefined) {\n      return\n    }\n\n    const current = view.state.doc.toString()\n\n    if (current === value) {\n      return\n    }\n\n    lastEmittedRef.current = value\n    view.dispatch({\n      changes: { from: 0, to: current.length, insert: value },\n    })\n  }, [value, view])\n\n  return (\n    <div\n      data-slot=\"code-editor-content\"\n      className={cn('relative min-h-0 flex-1', className)}\n      {...props}\n    >\n      <div ref={hostRef} className=\"h-full w-full\" />\n    </div>\n  )\n}\n\nexport type CodeEditorToolbarProps = ComponentProps<'div'>\n\n/**\n * Editor toolbar with the history controls, the line wrapping toggle and a\n * copy action. Extension items can add their own controls as children.\n */\nexport function CodeEditorToolbar({\n  className,\n  children,\n  ...props\n}: CodeEditorToolbarProps) {\n  const { view } = useCodeEditor()\n\n  useCodeEditorState()\n\n  return (\n    <TooltipProvider>\n      <div\n        data-slot=\"code-editor-toolbar\"\n        role=\"toolbar\"\n        aria-label=\"Code editor\"\n        className={cn(\n          'flex flex-wrap items-center gap-1 border-b p-1.5',\n          className,\n        )}\n        {...props}\n      >\n        <CodeEditorToolbarButton\n          label=\"Undo\"\n          shortcut=\"Mod Z\"\n          disabled={!view || undoDepth(view.state) === 0}\n          onClick={() => view && undo(view)}\n        >\n          <Undo2Icon />\n        </CodeEditorToolbarButton>\n        <CodeEditorToolbarButton\n          label=\"Redo\"\n          shortcut=\"Shift Mod Z\"\n          disabled={!view || redoDepth(view.state) === 0}\n          onClick={() => view && redo(view)}\n        >\n          <Redo2Icon />\n        </CodeEditorToolbarButton>\n        <CodeEditorCopyButton />\n        <CodeEditorWrappingButton />\n        {children}\n      </div>\n    </TooltipProvider>\n  )\n}\n\nfunction CodeEditorWrappingButton() {\n  const { lineWrapping, setLineWrapping } = useCodeEditor()\n\n  return (\n    <CodeEditorToolbarButton\n      label=\"Soft wrap\"\n      pressed={lineWrapping}\n      onPressedChange={setLineWrapping}\n    >\n      <WrapTextIcon />\n    </CodeEditorToolbarButton>\n  )\n}\n\nfunction CodeEditorCopyButton() {\n  const { view } = useCodeEditor()\n  const [copied, setCopied] = useState(false)\n\n  useEffect(() => {\n    if (!copied) {\n      return\n    }\n\n    const timeout = window.setTimeout(setCopied, 1500, false)\n\n    return () => window.clearTimeout(timeout)\n  }, [copied])\n\n  return (\n    <CodeEditorToolbarButton\n      label={copied ? 'Copied' : 'Copy code'}\n      onClick={() => {\n        if (!view) {\n          return\n        }\n\n        void navigator.clipboard.writeText(view.state.doc.toString())\n        setCopied(true)\n      }}\n    >\n      {copied\n        ? <CheckIcon />\n        : <CopyIcon />}\n    </CodeEditorToolbarButton>\n  )\n}\n\nexport interface CodeEditorToolbarButtonProps {\n  label: string\n  shortcut?: string\n  /** Omit to render a plain action button instead of a toggle. */\n  pressed?: boolean\n  onPressedChange?: (pressed: boolean) => void\n  onClick?: () => void\n  disabled?: boolean\n  className?: string\n  children?: ReactNode\n}\n\n/**\n * A single toolbar control with a tooltip and an optional keyboard shortcut.\n * Used by the built-in controls and by extension items.\n */\nexport function CodeEditorToolbarButton({\n  label,\n  shortcut,\n  pressed,\n  onPressedChange,\n  onClick,\n  disabled,\n  className,\n  children,\n}: CodeEditorToolbarButtonProps) {\n  const control = pressed === undefined\n    ? (\n        <Button\n          type=\"button\"\n          variant=\"ghost\"\n          size=\"icon-sm\"\n          aria-label={label}\n          disabled={disabled}\n          onClick={onClick}\n          className={className}\n        >\n          {children}\n        </Button>\n      )\n    : (\n        <Toggle\n          type=\"button\"\n          aria-label={label}\n          size=\"sm\"\n          pressed={pressed}\n          onPressedChange={onPressedChange}\n          disabled={disabled}\n          className={cn('h-7 min-w-7 px-0', className)}\n        >\n          {children}\n        </Toggle>\n      )\n\n  return (\n    <Tooltip>\n      <TooltipTrigger render={control} />\n      <TooltipContent side=\"bottom\" className=\"flex items-center gap-1.5\">\n        <span>{label}</span>\n        {shortcut\n          ? <span className=\"text-muted-foreground\">{shortcut}</span>\n          : null}\n      </TooltipContent>\n    </Tooltip>\n  )\n}\n\nexport type CodeEditorStatusBarProps = ComponentProps<'div'>\n\n/**\n * Status bar with the cursor position, the selection length and the language\n * shared by the highlighting and language items.\n */\nexport function CodeEditorStatusBar({\n  className,\n  ...props\n}: CodeEditorStatusBarProps) {\n  const { view, configRef, readOnly } = useCodeEditor()\n\n  useCodeEditorState()\n\n  const state = view?.state\n  const head = state ? state.selection.main.head : 0\n  const line = state\n    ? state.doc.lineAt(head)\n    : null\n  const column = line\n    ? head - line.from + 1\n    : 1\n  const selected = state\n    ? state.selection.ranges.reduce(\n        (total, range) => total + (range.to - range.from),\n        0,\n      )\n    : 0\n\n  return (\n    <div\n      data-slot=\"code-editor-status\"\n      className={cn(\n        'flex items-center justify-between gap-2 border-t px-3 py-1.5 text-xs text-muted-foreground',\n        className,\n      )}\n      {...props}\n    >\n      <span className=\"tabular-nums\">\n        {line\n          ? `Ln ${line.number}, Col ${column}`\n          : 'Ln 1, Col 1'}\n      </span>\n      <span className=\"flex items-center gap-3\">\n        {readOnly\n          ? <span>Read only</span>\n          : null}\n        {selected > 0\n          ? (\n              <span>\n                {selected}\n                {' '}\n                selected\n              </span>\n            )\n          : null}\n        {configRef.current.language\n          ? (\n              <span className=\"font-mono uppercase\">\n                {configRef.current.language}\n              </span>\n            )\n          : null}\n      </span>\n    </div>\n  )\n}\n",
      "type": "registry:ui",
      "target": "components/blocove/code-editor/editor.tsx"
    }
  ],
  "categories": [
    "code-editor"
  ],
  "type": "registry:ui"
}