# Code Editor

A client-loaded Monaco code editor whose toolbar features are plugins.

Page: https://sui.draco.dev/docs/components/code-editor

### Example: code-editor-demo

```tsx
"use client";
import {
  CodeEditor,
  codeEditorLabelsZhCN,
  defaultPlugins,
  languageSelect,
  preview,
} from "@workspace/ui/components/code-editor";
import { HtmlViewer } from "@workspace/ui/viewers/html-viewer";
import { MarkdownViewer } from "@workspace/ui/viewers/markdown-viewer";
import { useMemo, useState } from "react";
import type { ExampleProps } from "../types";

const languages = [
  { value: "markdown", label: "Markdown" },
  { value: "html", label: "HTML" },
  { value: "typescript", label: "TypeScript" },
  { value: "tsx", label: "TSX" },
  { value: "json", label: "JSON" },
];

export default function Example({ locale }: ExampleProps) {
  const chinese = locale === "zh-CN";
  const [language, setLanguage] = useState("markdown");
  const [value, setValue] = useState(
    chinese
      ? "# 项目说明\n\n编辑这里的 **Markdown**，然后切换预览。\n\n- [x] 双语文档\n- [ ] 下一次发布"
      : "# Project notes\n\nEdit this **Markdown**, then switch to preview.\n\n- [x] Bilingual docs\n- [ ] Next release",
  );
  // Memoize plugins so Monaco options are not rebuilt on every keystroke.
  const plugins = useMemo(() => {
    const list = [languageSelect({ onChange: setLanguage, languages })];
    if (language === "markdown")
      list.push(
        preview({
          defaultMode: "edit",
          render: (content) => (
            <MarkdownViewer className="p-4" content={content} />
          ),
        }),
      );
    if (language === "html")
      list.push(
        preview({
          defaultMode: "edit",
          render: (content) => <HtmlViewer content={content} />,
        }),
      );
    return [...list, ...defaultPlugins()];
  }, [language]);
  return (
    <CodeEditor
      value={value}
      onChange={setValue}
      language={language}
      height={320}
      title={chinese ? "项目说明" : "Project notes"}
      labels={chinese ? codeEditorLabelsZhCN : undefined}
      plugins={plugins}
    />
  );
}
```

## Installation

```bash
npx shadcn@latest add @sui/code-editor
```

With pnpm, Yarn or Bun, use `pnpm dlx`, `yarn dlx` or `bunx --bun` in place of `npx`, and `pnpm add`, `yarn add` or `bun add` in place of `npm install`.

Install with the shadcn CLI or use the shared `@workspace/ui` package. Follow the [installation guide](/docs/installation) to configure the registry, load styles, and choose import aliases.

  CodeEditor installs as `components/ui/code-editor/index.tsx`. If you installed it
  from SUI 5.4 or earlier, delete the old `components/ui/code-editor.tsx` after
  updating: a file beside the folder wins over its index, so imports would
  keep the old version. See [Update installed
  source](/docs/registry#updating-source).

## Usage

```tsx
import { CodeEditor } from "@workspace/ui/components/code-editor";
import { useState } from "react";

export function ConfigEditor() {
  const [value, setValue] = useState('{ "name": "sui" }');
  return <CodeEditor value={value} onChange={setValue} language="json" height={320} />;
}
```

`CodeEditor` keeps a fixed set of props. Everything beyond editing (copy, fullscreen, language selection, preview and formatting) is a plugin passed through `plugins`, which defaults to `defaultPlugins()` (copy and fullscreen). Toolbar items appear in plugin order. Memoize the plugin list, or define it outside the component, so Monaco options are not rebuilt on every render.

```tsx
<CodeEditor
  value={value}
  onChange={setValue}
  language={language}
  plugins={[languageSelect({ onChange: setLanguage }), format(), ...defaultPlugins()]}
/>
```

## Editing and value state

Use `value` and `onChange` for controlled editing. For internal state, omit `value` and supply `defaultValue`; `onChange` still reports edits. `disabled` makes the editor read-only. The editor loads on the client, with a loading placeholder during SSR and hydration. Changing `language` recreates the editor bridge and releases its previous model while keeping the document. Language services and workers load as needed, are shared between mounted editors, and stop after the last editor and its models are released. Editing never runs the code. `options` passes Monaco settings, merged over the defaults.

## Plugins

| Plugin | Adds |
| --- | --- |
| `copy()` | A copy button with copied and failed feedback. |
| `fullscreen({ mode, value, defaultValue, onChange })` | A fullscreen toggle. `mode` is `"fixed"` (viewport overlay, default) or `"screen"` (browser Fullscreen API). |
| `languageSelect({ onChange, languages })` | A language picker. The caller owns `language` and updates it in `onChange`. |
| `preview({ render, mode, defaultMode, onModeChange, toggles })` | A preview pane with preview and split toggles. |
| `format()` | A button that runs Monaco's formatter for the current language. |
| `defaultPlugins()` | `copy()` and `fullscreen()`. |

A custom plugin is an object with a `name` and any of `toolbar(editor)`, `setup(editor)` (runs as a hook), `options` (Monaco options), `preview` or `fullscreen`.

### Language selection

`languageSelect` lists common languages by default; pass `languages` to change them. The current language stays visible even when it is missing from the list, and `disabled` disables the picker. Language IDs are trimmed and lowercased; `ts`, `js`, `md` and `text` normalize to `typescript`, `javascript`, `markdown` and `plaintext`. The first example switches between Markdown, HTML, TypeScript, TSX and JSON, and only adds a preview for Markdown and HTML.

## Preview

CodeEditor has no built-in renderers and does not depend on any viewer. `preview({ render })` receives the current value and renders anything, such as [Markdown Viewer](/docs/viewers/markdown-viewer) or [Html Viewer](/docs/viewers/html-viewer):

```tsx
preview({ render: (value) => <MarkdownViewer className="p-4" content={value} /> })
```

The toolbar switches between `edit`, `preview` and `split`. The default mode is `split`; use `defaultMode`, or `mode` with `onModeChange` for controlled selection.

### Scroll synchronization

In split mode, scrolling either pane moves the other to the same relative position. When the preview pane itself scrolls, this needs no wiring. A renderer that scrolls elsewhere, such as an iframe document, passes that element to the context `render` receives:

```tsx
function HtmlPreview({ content, context }: { content: string; context: CodeEditorPreviewContext }) {
  const frame = useRef<HTMLIFrameElement>(null);
  const [doc, setDoc] = useState<Document | null>(null);
  useEffect(() => {
    const element = doc?.scrollingElement as HTMLElement | null | undefined;
    if (!doc || !element) return;
    context.setScrollElement(element);
    const scroll = () => context.syncFromPreview(element);
    doc.addEventListener("scroll", scroll, { passive: true, capture: true });
    return () => {
      context.setScrollElement(null);
      doc.removeEventListener("scroll", scroll, true);
    };
  }, [context, doc]);
  return (
    <HtmlViewer
      ref={frame}
      content={content}
      sandbox="allow-same-origin"
      onLoad={() => setDoc(frame.current?.contentDocument ?? null)}
    />
  );
}

preview({ render: (value, context) => <HtmlPreview content={value} context={context} /> })
```

`allow-same-origin` lets the editor read the iframe document while scripts stay disabled.

The example uses a long document, controlled preview mode and browser fullscreen.

### Example: code-editor-preview

```tsx
"use client";

import {
  CodeEditor,
  type CodeEditorViewMode,
  codeEditorLabelsZhCN,
  copy,
  fullscreen,
  preview,
} from "@workspace/ui/components/code-editor";
import { MarkdownViewer } from "@workspace/ui/viewers/markdown-viewer";
import { useMemo, useState } from "react";
import type { ExampleProps } from "../types";

const sections = Array.from({ length: 24 }, (_, index) => index + 1);

export default function Example({ locale }: ExampleProps) {
  const chinese = locale === "zh-CN";
  const [mode, setMode] = useState<CodeEditorViewMode>("split");
  const [value, setValue] = useState(() =>
    sections
      .map((section) =>
        chinese
          ? `## 第 ${section} 节\n\n在编辑区和预览区分别滚动，另一区域按可滚动距离的比例跟随。\n\n这一段用于产生真实的长内容。\n`
          : `## Section ${section}\n\nScroll either pane to synchronize its relative position with the other pane.\n\nThis paragraph creates real long-form content.\n`,
      )
      .join("\n"),
  );
  const plugins = useMemo(
    () => [
      // The preview pane scrolls, so sync needs no extra wiring.
      preview({
        mode,
        onModeChange: setMode,
        render: (content) => (
          <MarkdownViewer
            className="p-4"
            content={content}
            labels={chinese ? { empty: "没有预览内容" } : undefined}
          />
        ),
      }),
      copy(),
      fullscreen({ mode: "screen" }),
    ],
    [mode, chinese],
  );
  return (
    <div className="grid w-full gap-3">
      <CodeEditor
        value={value}
        onChange={setValue}
        language="markdown"
        height={360}
        title={chinese ? "滚动同步预览" : "Synchronized preview"}
        labels={chinese ? codeEditorLabelsZhCN : undefined}
        plugins={plugins}
      />
      <output className="text-muted-foreground text-sm" aria-live="polite">
        {chinese ? "受控模式" : "Controlled mode"}: {mode}
      </output>
    </div>
  );
}
```

## Toolbar and read-only editing

`title` replaces the toolbar heading, which defaults to the language name. `toolbar` adds actions before the plugins' items, and `toolbar={false}` hides the toolbar. The example adds a format plugin and a reset button, and switches between editable and read-only.

### Example: code-editor-toolbar

```tsx
"use client";
import { Button } from "@workspace/ui/components/button";
import {
  CodeEditor,
  codeEditorLabelsZhCN,
  copy,
  format,
  fullscreen,
} from "@workspace/ui/components/code-editor";
import { useState } from "react";
import type { ExampleProps } from "../types";

const initialValue = 'export const theme = { name: "bamboo", enabled: true };';
const plugins = [format(), copy(), fullscreen({ mode: "fixed" })];

export default function Example({ locale }: ExampleProps) {
  const chinese = locale === "zh-CN";
  const [value, setValue] = useState(initialValue);
  const [disabled, setDisabled] = useState(false);
  let toggleLabel = chinese ? "设为只读" : "Make read-only";
  if (disabled) toggleLabel = chinese ? "允许编辑" : "Enable editing";
  return (
    <div className="grid w-full gap-4">
      <Button
        variant="outline"
        className="justify-self-start"
        type="button"
        onClick={() => setDisabled((current) => !current)}
      >
        {toggleLabel}
      </Button>
      <CodeEditor
        value={value}
        onChange={setValue}
        disabled={disabled}
        language="typescript"
        height={260}
        title="theme.ts"
        labels={chinese ? codeEditorLabelsZhCN : undefined}
        plugins={plugins}
        toolbar={
          <Button
            type="button"
            size="sm"
            variant="ghost"
            disabled={disabled}
            onClick={() => setValue(initialValue)}
          >
            {chinese ? "恢复示例" : "Reset example"}
          </Button>
        }
      />
    </div>
  );
}
```

## Composition

For a custom layout, call `useCodeEditor` with the same options and assemble the parts. `CodeEditorRoot` provides the editor to `CodeEditorToolbar`, `CodeEditorTitle`, `CodeEditorActions`, `CodeEditorToolbarButton` and `CodeEditorContent`, and `useCodeEditorContext()` reads it inside your own parts. The instance exposes `value`, `mode`, `fullscreen`, the Monaco `editor`, and `setValue`, `setMode`, `setFullscreen` and `format`.

### Example: code-editor-compose

```tsx
"use client";
import { Badge } from "@workspace/ui/components/badge";
import {
  CodeEditorActions,
  CodeEditorContent,
  CodeEditorRoot,
  CodeEditorTitle,
  CodeEditorToolbar,
  CodeEditorToolbarButton,
  codeEditorLabelsZhCN,
  copy,
  useCodeEditor,
} from "@workspace/ui/components/code-editor";
import { Undo2 } from "lucide-react";
import { useState } from "react";
import type { ExampleProps } from "../types";

const initialValue = '{\n  "name": "sui",\n  "private": true\n}';
const plugins = [copy()];

export default function Example({ locale }: ExampleProps) {
  const chinese = locale === "zh-CN";
  const [value, setValue] = useState(initialValue);
  const editor = useCodeEditor({
    value,
    onChange: setValue,
    language: "json",
    height: 200,
    labels: chinese ? codeEditorLabelsZhCN : undefined,
    plugins,
  });
  const dirty = value !== initialValue;
  return (
    <CodeEditorRoot editor={editor}>
      <CodeEditorToolbar>
        <CodeEditorTitle>package.json</CodeEditorTitle>
        {dirty && (
          <Badge variant="secondary">{chinese ? "未保存" : "Unsaved"}</Badge>
        )}
        <CodeEditorActions>
          <CodeEditorToolbarButton
            tooltip={chinese ? "撤销全部" : "Revert"}
            disabled={!dirty}
            onClick={() => setValue(initialValue)}
          >
            <Undo2 />
          </CodeEditorToolbarButton>
        </CodeEditorActions>
      </CodeEditorToolbar>
      <CodeEditorContent />
    </CodeEditorRoot>
  );
}
```

## Fullscreen and localization

The fixed overlay supports Escape, keeps keyboard focus inside and restores focus on exit. Browser fullscreen needs API support and permission; a failed request stays out of fullscreen. Pass `codeEditorLabelsZhCN`, or your own `labels`, to translate actions, loading and failure messages. Monaco themes are shared within a page, so keep editors on one page in a consistent theme.

## API reference

| Prop | Type | Default / behavior |
| --- | --- | --- |
| `value` / `defaultValue` | `string` | Controlled / initial internal content. |
| `onChange` | `(value: string) => void` | Reports content changes. |
| `language` | `string` | `"plaintext"`. |
| `disabled` | `boolean` | `false`; read-only editing. |
| `height` | `string \| number` | Editing area height; numbers are pixels. Without it the editor fills its parent. |
| `plugins` | `readonly CodeEditorPlugin[]` | `defaultPlugins()`. |
| `options` | Monaco options | Merged over the defaults and plugin options. |
| `title` | `ReactNode` | The language name. |
| `toolbar` | `false \| ReactNode` | Extra actions, or `false` to hide the toolbar. |
| `size` | Button size | `"icon-sm"` for toolbar actions. |
| `labels` | `Partial<CodeEditorLabels>` | English action names and messages. |

The module exports `CodeEditorProps`, `CodeEditorPlugin`, `CodeEditorInstance`, `CodeEditorPreviewContext`, `CodeEditorViewMode` and `CodeEditorLabels`. The editor uses Monaco; see the [Monaco API](https://microsoft.github.io/monaco-editor/docs.html).
