# Code editor

Edit short code or configuration with logical line context and linked diagnostics.

Access: pro. Category: Forms. Kind: composite.

## When to use

- Use it when a page needs edit short code or configuration with logical line context and linked diagnostics.
- Choose it when the host application can supply the required state and keep business logic outside the presentation component.

## Alternatives

- Choose form-field instead when a labeled email field with validation and help text is the actual interface need, rather than code editor.

## Setup for agents

Use React 19 and TypeScript. Initialize shadcn for your framework, then merge this exact entry into components.json:

```json
{
  "registries": {
    "@tidal-pro": {
      "url": "https://tidalui.com/r/pro/{name}.json",
      "headers": {
        "Authorization": "Bearer ${TIDALUI_TOKEN}"
      }
    }
  }
}
```

The namespace must be named **@tidal-pro** because transitive Pro dependencies use that namespace. Obtain an agent key from your active Pro account at https://tidalui.com/account. Keep TIDALUI_TOKEN in your local environment, never in components.json, client code, Git or logs.

```sh
export TIDALUI_TOKEN='your-private-agent-key'
npx shadcn@latest add @tidal-pro/waitlist-form
npx shadcn@latest add https://tidalui.com/r/tidal-button.json
```

Free command: `npx shadcn@latest add https://tidalui.com/r/<name>.json`.
Pro command: `npx shadcn@latest add @tidal-pro/<name>`.

Import the base stylesheet and every stylesheet listed on the installed item's metadata. For example:

```tsx
import "./components/ui/tidal.css";
import "./components/ui/hero-section.css";
// Place installed components inside this wrapper:
<div className="tidal-scope" data-theme="dark">...</div>
```

Omit data-theme for the default light theme. Put the attribute on the same tidal-scope element for dark mode. Every component installs the shared free tidal-base dependency. After upgrading, run `npx shadcn@latest add https://tidalui.com/r/tidal-base.json --overwrite` to receive current tokens. Review local modifications before overwriting.

Vite: Use React + TypeScript. Map @/* to ./src/* in paths and Vite resolve.alias. Import tidal.css and each component stylesheet in your application entry.

Next.js 15 App Router: Next.js App Router: import tidal.css and component CSS in app/layout.tsx. Interactive examples belong in a client component with "use client". Map @/* to ./* or ./src/* to match your project.

TypeScript 6: use paths without baseUrl:

```json
{
  "compilerOptions": {
    "paths": {
      "@/*": [
        "./src/*"
      ]
    }
  }
}
```

Pro registry requests are server/CLI-only. Use the same-origin account interface in a browser; cross-origin Authorization preflights are intentionally unsupported.


## Install Code editor

```sh
npx shadcn@latest add @tidal-pro/code-editor
```

Stylesheets: `components/ui/tidal.css`, `components/ui/code-editor.css`.

## Minimal example

```tsx
import"./components/ui/tidal.css";
import"./components/ui/code-editor.css";
import{TidalCodeEditor}from"./components/ui/code-editor";
export default()=><div className="tidal-scope"><TidalCodeEditor label={"Demo"} onValueChange={() => {}} value={"value"}/></div>;
```

## Structured props

- `TidalCodeEditor.label: string`: Required label value accepted by this exported component.
- `TidalCodeEditor.onValueChange: (value: string, event: ChangeEvent<HTMLTextAreaElement> | KeyboardEvent<HTMLTextAreaElement>) => void`: Callback invoked when the value change interaction is proposed.
- `TidalCodeEditor.value: string`: Required value value accepted by this exported component.
- `TidalCodeEditor.actions?: ReactNode`: Optional actions value accepted by this exported component.
- `TidalCodeEditor.description?: ReactNode`: Optional description value accepted by this exported component.
- `TidalCodeEditor.diagnostics?: ReadonlyArray<TidalCodeEditorDiagnostic> | undefined` (default []): Optional diagnostics value accepted by this exported component.
- `TidalCodeEditor.disabled?: boolean | undefined` (default false): Optional disabled value accepted by this exported component.
- `TidalCodeEditor.filename?: string | undefined`: Optional filename value accepted by this exported component.
- `TidalCodeEditor.indentation?: string | undefined` (default "  "): Optional indentation value accepted by this exported component.
- `TidalCodeEditor.labels?: TidalCodeEditorLabels | undefined` (default {}): Optional labels value accepted by this exported component.
- `TidalCodeEditor.language?: string | undefined`: Optional language value accepted by this exported component.
- `TidalCodeEditor.maxHeight?: number | undefined` (default 420): Optional max height value accepted by this exported component.
- `TidalCodeEditor.readOnly?: boolean | undefined` (default false): Optional read only value accepted by this exported component.
- `TidalCodeEditor.showLineNumbers?: boolean | undefined` (default true): Optional show line numbers value accepted by this exported component.
- `TidalCodeEditor.tabBehavior?: TidalCodeEditorTabBehavior | undefined` (default "focus"): Optional tab behavior value accepted by this exported component.
- `TidalCodeEditor.textareaProps?: CodeTextareaProps | undefined` (default {}): Optional textarea props value accepted by this exported component.
- `TidalCodeEditor.textareaRef?: Ref<HTMLTextAreaElement> | undefined`: Optional textarea ref value accepted by this exported component.
- `TidalCodeEditor.wrap?: boolean | undefined` (default false): Optional wrap value accepted by this exported component.

## Complete usage example

[Source](https://tidalui.com/examples/code-editor.tsx) | [Manifest](https://tidalui.com/examples/code-editor.json). Install the listed additional dependencies. Consumer fixture: TypeScript pass; Vite pass. This fixture check is distinct from the actual shadcn install receipt.

```tsx
import "./components/ui/tidal.css";

import { useId, useMemo, useRef, useState } from "react";

import "./components/ui/code-editor.css";

import { TidalCodeEditor, type TidalCodeEditorDiagnostic } from "./components/ui/code-editor";



const tidalExampleStyles = ".tidal-scope .tidal-code-editor-demo {\n  display: grid;\n  width: min(100%, 720px);\n  min-width: 0;\n  margin: 0 auto;\n  gap: 14px;\n}\n\n.tidal-scope .tidal-code-editor-demo button {\n  min-height: 44px;\n  max-width: 100%;\n  padding: 0 14px;\n  border: 1px solid var(--t-border);\n  border-radius: var(--t-radius-control);\n  color: var(--t-ink);\n  background: var(--t-surface);\n  font: inherit;\n  font-size: 12px;\n  font-weight: 650;\n  overflow-wrap: anywhere;\n  cursor: pointer;\n  transition:\n    color 140ms,\n    background 140ms,\n    border-color 140ms,\n    transform 140ms;\n}\n\n.tidal-scope .tidal-code-editor-demo-footer {\n  display: grid;\n  grid-template-columns: max-content minmax(0, 1fr);\n  align-items: center;\n  gap: 10px 14px;\n  min-width: 0;\n}\n\n.tidal-scope .tidal-code-editor-demo-footer > button {\n  color: var(--t-surface);\n  background: var(--t-ink);\n  border-color: var(--t-ink);\n}\n\n.tidal-scope .tidal-code-editor-demo output,\n.tidal-scope .tidal-code-editor-demo-note {\n  min-width: 0;\n  margin: 0;\n  color: var(--t-muted);\n  font-size: 11px;\n  line-height: 1.6;\n  overflow-wrap: anywhere;\n}\n\n@media (hover: hover) and (pointer: fine) {\n  .tidal-scope .tidal-code-editor-demo button:hover {\n    border-color: var(--t-ink);\n    transform: translateY(-1px);\n  }\n\n  .tidal-scope .tidal-code-editor-demo-footer > button:hover {\n    color: var(--t-ink);\n    background: var(--t-surface);\n  }\n}\n\n.tidal-scope .tidal-code-editor-demo button:active {\n  transform: translateY(1px);\n}\n\n.tidal-scope .tidal-code-editor-demo button:focus-visible {\n  outline: 2px solid var(--t-ring);\n  outline-offset: 3px;\n}\n\n@media (max-width: 420px) {\n  .tidal-scope .tidal-code-editor-demo-footer {\n    grid-template-columns: minmax(0, 1fr);\n  }\n\n  .tidal-scope .tidal-code-editor-demo-footer > button {\n    width: 100%;\n  }\n}\n\n@media (prefers-reduced-motion: reduce) {\n  .tidal-scope .tidal-code-editor-demo button {\n    transition: none;\n  }\n\n  .tidal-scope .tidal-code-editor-demo button:hover,\n  .tidal-scope .tidal-code-editor-demo button:active {\n    transform: none;\n  }\n}";

const SAMPLE = `{
  // Keep refresh intervals explicit.
  "refreshMinutes": 15,
  "compactNavigation": true
}`;

export function CodeEditorDemo() {
  const formId = useId().replace(/[^a-zA-Z0-9_-]/g, "-");
  const [value, setValue] = useState(SAMPLE);
  const [status, setStatus] = useState("One local diagnostic is supplied.");
  const source = useRef<HTMLTextAreaElement>(null);
  const diagnostics = useMemo<readonly TidalCodeEditorDiagnostic[]>(
    () =>
      value.includes("//")
        ? [
            {
              id: "json-comment",
              line: 2,
              column: 3,
              message: "JSON does not allow comments.",
            },
          ]
        : [],
    [value],
  );

  return (
    <form
      id={formId}
      className="tidal-code-editor-demo"
      onSubmit={(event) => {
        event.preventDefault();
        const submitted = String(
          new FormData(event.currentTarget).get("config") ?? "",
        );
        setStatus(
          diagnostics.length
            ? "Fix the supplied diagnostic before local review."
            : `Reviewed ${submitted.length} local characters.`,
        );
      }}
    >
      <TidalCodeEditor
        label="Environment config"
        filename="workspace.config.json"
        language="JSON"
        value={value}
        onValueChange={(next) => {
          setValue(next);
          setStatus("Local draft updated.");
        }}
        diagnostics={diagnostics}
        textareaRef={source}
        textareaProps={{
          name: "config",
          required: true,
          rows: 8,
          "aria-label": "Environment config source",
        }}
        tabBehavior="indent"
        actions={
          <button
            type="button"
            onClick={() => {
              source.current?.focus({ preventScroll: true });
              source.current?.select();
              setStatus("Local source selected.");
            }}
          >
            Select all
          </button>
        }
        description="Tab inserts two spaces. Shift+Tab removes one indentation level."
      />
      <div className="tidal-code-editor-demo-footer">
        <button type="submit">Review locally</button>
        <output aria-live="polite">{status}</output>
      </div>
      <p className="tidal-code-editor-demo-note">
        Fictional sample. Editing and review stay in this page; no code runs or
        saves.
      </p>
    </form>
  );
}

export default function AgentExample() {
  return (
    <div className="tidal-scope" data-theme="light" dir="ltr">
      <style>{tidalExampleStyles}</style>
      <CodeEditorDemo />
    </div>
  );
}

```

## Gotchas

- Keep field state, validation results, submission, and persistence in the host form workflow.

## Theme and accessibility

{"tokens":["--t-accent","--t-border","--t-border-strong","--t-canvas","--t-danger","--t-display","--t-ease-out","--t-ease-spring","--t-faint","--t-font","--t-ink","--t-line","--t-muted","--t-primary","--t-primary-contrast","--t-radius-card","--t-radius-control","--t-radius-overlay","--t-radius-panel","--t-ring","--t-shadow-lg","--t-shadow-soft","--t-soft","--t-subtle","--t-surface","--t-wash"],"darkMode":true}

{"keyboard":["Tab and Shift+Tab follow the component's native focus order.","Arrow-key behavior follows the exported composite-control implementation."],"aria":"The component wires labels and relationships from consumer-provided visible text or ARIA props; preserve those labels in production.","notes":"Verify focus visibility, text alternatives, contrast, and reduced motion in the final composition."}

Required nonblank label, controlled value:string and onValueChange(value,event). The component renders one native textarea with direct textareaProps/textareaRef support for name/form/required/placeholder/rows/autocomplete and safe native attributes. Native input and change handlers run before the controlled proposal; prevention from either event suppresses it. disabled and readOnly map to the native textarea and defensively block escaped change proposals; disabled also sets the owned root aria-disabled state and makes the consumer action slot inert. showLineNumbers defaults true and displays logical line numbers when wrap is false; wrap defaults false for local long-line scrolling. tabBehavior defaults 'focus', preserving ordinary Tab navigation. Opt-in 'indent' handles unmodified Tab/Shift+Tab after caller-first keydown and IME/229 guards, proposes exact source, and restores the native selection only after synchronous acceptance while the textarea or body still owns focus. indentation accepts one to eight spaces or tab characters and defaults to two spaces. Consumer-supplied diagnostics require unique nonblank IDs, positive integer line/optional column, nonblank messages and error/warning/info severity; the exact localized list is linked to the textarea and only error severity sets aria-invalid. Optional filename, language, description, actions slot, localized labels, maxHeight 160–720, native root attrs/ref, numeric values within React content, 180px/320px containment, RTL, forced colors and reduced motion are supported. Owned controlled value, replacement markup, textarea role, availability and caller-supplied root aria-disabled channels are type-excluded and runtime-stripped. The editor does not highlight, parse, validate, execute, copy, upload, request, store or persist source.
