# Rich text editor

> Edit formatted prose with a compact native toolbar, safe link insertion and an editable Markdown source field.

- Kind: ui · Category: Forms · Interactivity: script
- Install: `npx shadcn@latest add @haze/rich-text-editor`
- File: `src/components/haze/ui/rich-text-editor.astro`
- npm dependencies: @lucide/astro
- Registry dependencies: @haze/utils
- Docs page: https://hazeui.com/ui/rich-text-editor

## Use when
- Project notes or updates need headings, emphasis, lists and links without a large editor dependency.
- The submitted document should be Markdown and remain editable with scripting disabled.

## Avoid when
- Use textarea for plain prose without formatting.
- Choose a dedicated document editor when collaborative cursors, tables, media or lossless arbitrary HTML are required.

## Alternatives
- [textarea](https://hazeui.com/ui/textarea.md)
- [input](https://hazeui.com/ui/input.md)
- [code-block](https://hazeui.com/ui/code-block.md)

## Props

| Name | Type | Default | Required | Description |
|---|---|---|---|---|
| id | `string` |  | yes | Unique caller supplied prefix for the control and its associated content. |
| name | `string` | id | no | Name submitted by the native form control. |
| label | `string` | Project update | no | Visible editor label shared by the formatted surface and source. |
| value | `string` | Demo handoff note | no | Initial Markdown; supports headings, simple emphasis, unordered lists, code and links. |
| placeholder | `string` | Write an update… | no | Placeholder of the native Markdown textarea. |
| rows | `number` | 9 | no | Starting textarea row count in Markdown mode. |
| required | `boolean` | false | no | Uses native required validation on the submitted source field. |
| disabled | `boolean` | false | no | Prevents user changes through the native disabled state. |
| readonly | `boolean` | false | no | Keeps both the formatted surface and source read only. |
| class | `string` |  | no | Additional classes on this component's outer wrapper. |
| [key: string] | `unknown` |  | no | Other native textarea attributes. |

## Accessibility
- A labelled contenteditable textbox provides formatted editing, while the Markdown toggle exposes the real textarea used for form submission.
- Formatting buttons preserve the text selection, expose pressed state where appropriate and remain ordinary keyboard reachable buttons.
- Pasted material is inserted as plain text; source rendering constructs DOM nodes rather than injecting HTML, and links accept only http, https or mailto destinations.
- If native validation rejects the required source field, Markdown mode opens so the browser can focus the invalid control.
- The enhancement uses the browser's editing commands and supports a compact Markdown subset; it is not a lossless round trip for arbitrary HTML or Markdown extensions.
- Key Ctrl/⌘ B / I in the editor: Use the browser's native bold and italic editing commands.
- Key Tab, Enter / Space: Reach formatting, link insertion and Markdown source controls.
- Key Enter / Esc in the link field: Insert the link, or close the link row and return focus to the Link button.
- Key Ctrl/⌘ Z / Shift Z: Use the browser editing history while the formatted surface is focused.

## Agent prompts

### Install and use

Install the Haze UI component "Rich text editor" with `npx shadcn@latest add @haze/rich-text-editor`. If components.json has no "@haze" registry yet, add "registries": { "@haze": "https://hazeui.com/r/{name}.json" }. If src/styles/haze.css does not exist yet, run `npx shadcn@latest add @haze/theme` once and import it from the global stylesheet after Tailwind. The CLI stops at an overwrite question when a Haze file already exists and differs, even with --yes, and then installs nothing after it: read its output. If the user has not edited their Haze files, re-run with --overwrite to take the registry versions; if they have, ask them before overwriting. Then import RichTextEditor from "@/components/haze/ui/rich-text-editor.astro" (or the relative path) and render it where it fits the page. Keep Haze token classes (bg-background, text-muted-foreground, border-border...) and never hardcode colors. Docs: https://hazeui.com/ui/rich-text-editor.md

### Customize with real content

Adapt the Haze rich-text-editor ui for our product. Replace the demo values of these props with our real content: id, name, label, value, placeholder, rows, required, disabled, readonly, class, [key: string]. Keep the layout, the heading level rules and these accessibility details: A labelled contenteditable textbox provides formatted editing, while the Markdown toggle exposes the real textarea used for form submission. Formatting buttons preserve the text selection, expose pressed state where appropriate and remain ordinary keyboard reachable buttons. Pasted material is inserted as plain text; source rendering constructs DOM nodes rather than injecting HTML, and links accept only http, https or mailto destinations. If native validation rejects the required source field, Markdown mode opens so the browser can focus the invalid control. The enhancement uses the browser's editing commands and supports a compact Markdown subset; it is not a lossless round trip for arbitrary HTML or Markdown extensions. Do not add raw color classes; use the Haze tokens.

### Choose the right block

Before using rich-text-editor, check it fits: use it when project notes or updates need headings, emphasis, lists and links without a large editor dependency.; the submitted document should be markdown and remain editable with scripting disabled.. Avoid it when use textarea for plain prose without formatting.; choose a dedicated document editor when collaborative cursors, tables, media or lossless arbitrary html are required.. Alternatives: @haze/textarea, @haze/input, @haze/code-block.

## Example requests that should lead here
- Add a project update editor with bold, headings, links and Markdown source
- Use a lightweight formatted editor that submits a real Markdown textarea value

## Source

```astro
---
import { Bold, FileCode, Heading2, Italic, Link2, List, Pilcrow, Redo2, Undo2 } from "@lucide/astro";
import { cn } from "../../../lib/haze/utils";

interface Props {
  id: string;
  name?: string;
  label?: string;
  value?: string;
  placeholder?: string;
  rows?: number;
  required?: boolean;
  disabled?: boolean;
  readonly?: boolean;
  class?: string;
  [key: string]: unknown;
}
const { id, name = id, label = "Project update", value = "## A clearer handoff\n\nThe release checklist is ready for **review**.\n\n- Confirm the owner\n- Share the next step", placeholder = "Write an update…", rows = 9, required, disabled, readonly = false, class: className, ...rest } = Astro.props;
const tool = "inline-flex size-8 shrink-0 cursor-pointer items-center justify-center rounded-lg text-muted-foreground transition-[background-color,color,scale] duration-150 ease-snappy hover:bg-accent hover:text-foreground focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-ring active:scale-[0.97] active:duration-75 aria-pressed:bg-accent aria-pressed:text-foreground disabled:cursor-not-allowed disabled:opacity-50";
const divider = "mx-1 h-5 w-px shrink-0 bg-border";
// Same rhythm as the typography component at size sm: headings sit closer to what follows than to what precedes.
const prose = "text-[0.8125rem]/6 text-foreground [&_h2]:text-lg/7 [&_h2]:font-semibold [&_h2]:tracking-tight [&>*+*]:mt-3.5 [&>h2]:mt-8 [&>h2+*]:mt-2 [&>:first-child]:mt-0 [&_strong]:font-semibold [&_em]:italic [&_a]:text-foreground [&_a]:underline [&_a]:decoration-border-strong [&_a]:underline-offset-4 [&_:where(p,li,blockquote)]:wrap-break-word [&_ul]:list-disc [&_ol]:list-decimal [&_:where(ul,ol)]:pl-5 [&_:where(ul,ol)]:marker:text-muted-foreground [&_li]:pl-1 [&_li+li]:mt-1.5 [&_blockquote]:pl-4 [&_blockquote]:italic [&_blockquote]:text-muted-foreground [&_code]:rounded-sm [&_code]:bg-muted [&_code]:px-1 [&_code]:py-0.5 [&_code]:font-mono [&_code]:text-[0.875em] [&_code]:font-medium";
---
<div data-haze-rich-text-editor data-readonly={readonly || disabled ? "true" : "false"} class={cn("grid w-full min-w-0 gap-2", className)}>
  <label id={`${id}-label`} for={id} class="text-[0.8125rem]/5 font-medium text-foreground">{label}{required && <span aria-hidden="true"> *</span>}</label>
  <div class="min-w-0 overflow-hidden rounded-xl border border-frame-input bg-field text-foreground transition-[border-color,box-shadow] duration-150 ease-snappy hover:border-frame-foreground has-[:is(textarea,[role=textbox]):focus-visible]:border-ring has-[:is(textarea,[role=textbox]):focus-visible]:ring-3 has-[:is(textarea,[role=textbox]):focus-visible]:ring-ring/24">
    <div data-editor-toolbar hidden class="flex items-center gap-0.5 overflow-x-auto border-b border-border bg-muted p-1.5" role="group" aria-label="Text formatting">
      <button type="button" data-command="bold" aria-pressed="false" class={tool} aria-label="Bold" title="Bold (Ctrl/⌘ B)"><Bold aria-hidden="true" class="size-4" /></button>
      <button type="button" data-command="italic" aria-pressed="false" class={tool} aria-label="Italic" title="Italic (Ctrl/⌘ I)"><Italic aria-hidden="true" class="size-4" /></button>
      <span aria-hidden="true" class={divider}></span>
      <button type="button" data-command="formatBlock" data-argument="h2" aria-pressed="false" class={tool} aria-label="Heading" title="Heading"><Heading2 aria-hidden="true" class="size-4" /></button>
      <button type="button" data-command="formatBlock" data-argument="p" aria-pressed="false" class={tool} aria-label="Paragraph" title="Paragraph"><Pilcrow aria-hidden="true" class="size-4" /></button>
      <button type="button" data-command="insertUnorderedList" aria-pressed="false" class={tool} aria-label="Bulleted list" title="Bulleted list"><List aria-hidden="true" class="size-4" /></button>
      <button type="button" data-editor-link-toggle aria-expanded="false" aria-controls={`${id}-link-panel`} class={cn(tool, "aria-expanded:bg-accent aria-expanded:text-foreground")} aria-label="Add a link to the selection" title="Add a link to the selection"><Link2 aria-hidden="true" class="size-4" /></button>
      <span aria-hidden="true" class={divider}></span>
      <button type="button" data-command="undo" class={tool} aria-label="Undo" title="Undo (Ctrl/⌘ Z)"><Undo2 aria-hidden="true" class="size-4" /></button>
      <button type="button" data-command="redo" class={tool} aria-label="Redo" title="Redo (Ctrl/⌘ Shift Z)"><Redo2 aria-hidden="true" class="size-4" /></button>
      <span aria-hidden="true" class={cn(divider, "ml-auto")}></span>
      <button type="button" data-editor-source aria-pressed="false" class={cn(tool, "w-auto gap-1.5 px-2 text-xs/4 font-medium")} title="Edit the Markdown source"><FileCode aria-hidden="true" class="size-4" />Markdown</button>
    </div>
    <div data-editor-link-tools hidden>
      <div data-editor-link-panel id={`${id}-link-panel`} class="grid grid-rows-[0fr] border-b border-transparent transition-[grid-template-rows,border-color] duration-200 ease-snappy data-[open]:grid-rows-[1fr] data-[open]:border-border motion-reduce:transition-none">
        <div class="min-h-0 overflow-hidden">
          <div class="flex min-w-0 items-center gap-2 p-2">
            <input id={`${id}-url`} data-editor-url type="url" tabindex="-1" aria-label="Link destination URL" placeholder="https://example.com" class="h-8 min-w-0 flex-1 rounded-lg border border-frame-input bg-field px-2.5 text-[0.8125rem] text-foreground transition-[border-color,box-shadow] duration-150 ease-snappy placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/24 focus-visible:outline-hidden" />
            <button type="button" data-editor-add-link tabindex="-1" class="inline-flex h-8 shrink-0 cursor-pointer items-center rounded-lg border border-frame bg-field px-3 text-[0.8125rem]/5 font-medium text-foreground shadow-key transition-[background-color,scale] duration-150 ease-snappy hover:bg-accent focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring active:scale-[0.97] active:duration-75">Insert</button>
          </div>
        </div>
      </div>
    </div>
    <div data-editor-surface hidden role="textbox" aria-multiline="true" aria-labelledby={`${id}-label`} aria-describedby={`${id}-help`} aria-required={required ? "true" : undefined} aria-readonly={readonly ? "true" : undefined} class={cn("min-h-48 min-w-0 overflow-x-auto p-4 focus-visible:outline-hidden", prose)} />
    <textarea id={id} name={name} data-editor-value rows={rows} placeholder={placeholder} required={required} disabled={disabled} readonly={readonly} aria-describedby={`${id}-help`} class="block min-h-48 w-full min-w-0 resize-y bg-transparent p-3 font-mono text-sm/6 text-foreground placeholder:text-muted-foreground focus-visible:outline-hidden disabled:opacity-50" {...rest}>{value}</textarea>
  </div>
  <div class="flex flex-wrap items-baseline justify-between gap-2"><p id={`${id}-help`} class="text-xs text-muted-foreground">Formatting is saved as Markdown. Pasted content is inserted as plain text.</p><output data-editor-count for={id} aria-hidden="true" class="text-xs text-muted-foreground tabular-nums">{Array.from(value).length} characters</output></div>
  <p data-editor-status role="status" class="sr-only"></p>
</div>
<script>
  function enhance(root: HTMLElement) {
    if (root.hasAttribute("data-enhanced")) return;
    const source = root.querySelector<HTMLTextAreaElement>("[data-editor-value]");
    const surface = root.querySelector<HTMLElement>("[data-editor-surface]");
    const toolbar = root.querySelector<HTMLElement>("[data-editor-toolbar]");
    const toggle = root.querySelector<HTMLButtonElement>("[data-editor-source]");
    const status = root.querySelector<HTMLElement>("[data-editor-status]");
    const count = root.querySelector<HTMLOutputElement>("[data-editor-count]");
    const url = root.querySelector<HTMLInputElement>("[data-editor-url]");
    const linkToggle = root.querySelector<HTMLButtonElement>("[data-editor-link-toggle]");
    const linkPanel = root.querySelector<HTMLElement>("[data-editor-link-panel]");
    const linkTools = root.querySelector<HTMLElement>("[data-editor-link-tools]");
    const addLink = root.querySelector<HTMLButtonElement>("[data-editor-add-link]");
    if (!source || !surface || !toolbar || !toggle || !status || !count || !url || !linkToggle || !linkPanel || !linkTools || !addLink) return;
    const readOnly = root.dataset.readonly === "true";
    let saved: Range | null = null;
    const safeUrl = (value: string) => { try { const parsed = new URL(value); return ["https:", "http:", "mailto:"].includes(parsed.protocol) ? parsed.href : null; } catch { return null; } };
    const inline = (text: string, depth = 0): DocumentFragment => {
      const fragment = document.createDocumentFragment();
      if (depth >= 16) { fragment.append(document.createTextNode(text)); return fragment; }
      const tokens = /\*\*\*([^*]+)\*\*\*|\*\*([^\n]+?)\*\*|\*([^*]+)\*|`([^`]+)`|\[([^\]]+)\]\(([^)]+)\)/g;
      let offset = 0;
      for (const match of text.matchAll(tokens)) {
        fragment.append(document.createTextNode(text.slice(offset, match.index)));
        let node: HTMLElement;
        if (match[1]) { node = document.createElement("strong"); const emphasis = document.createElement("em"); emphasis.append(inline(match[1], depth + 1)); node.append(emphasis); }
        else if (match[2]) { node = document.createElement("strong"); node.append(inline(match[2], depth + 1)); }
        else if (match[3]) { node = document.createElement("em"); node.append(inline(match[3], depth + 1)); }
        else if (match[4]) { node = document.createElement("code"); node.textContent = match[4]; }
        else { const href = safeUrl(match[6]); if (href) { const anchor = document.createElement("a"); anchor.href = href; anchor.append(inline(match[5], depth + 1)); node = anchor; } else { node = document.createElement("span"); node.textContent = match[0]; } }
        fragment.append(node); offset = (match.index || 0) + match[0].length;
      }
      fragment.append(document.createTextNode(text.slice(offset))); return fragment;
    };
    const render = () => {
      const fragment = document.createDocumentFragment(); let list: HTMLUListElement | null = null;
      source.value.replace(/\r\n/g, "\n").split("\n").forEach((line) => {
        if (!line.trim()) { list = null; return; }
        if (/^- /.test(line)) { if (!list) { list = document.createElement("ul"); fragment.append(list); } const item = document.createElement("li"); item.append(inline(line.slice(2))); list.append(item); return; }
        list = null;
        const heading = /^#{1,6} /.exec(line), quote = /^> /.test(line);
        const node = document.createElement(heading ? "h2" : quote ? "blockquote" : "p");
        const text = heading ? line.slice(heading[0].length) : quote ? line.slice(2) : line;
        if (text) node.append(inline(text)); else node.append(document.createElement("br"));
        fragment.append(node);
      });
      if (!fragment.childNodes.length) { const empty = document.createElement("p"); empty.append(document.createElement("br")); fragment.append(empty); }
      surface.replaceChildren(fragment);
    };
    const setLink = (open: boolean, focus = true) => {
      linkPanel.toggleAttribute("data-open", open); linkToggle.setAttribute("aria-expanded", String(open));
      linkPanel.querySelectorAll<HTMLElement>("input, button").forEach((control) => control.tabIndex = open ? 0 : -1);
      if (open && focus) url.focus({ preventScroll: true }); else if (!open && focus) linkToggle.focus();
    };
    const serialize = (node: Node): string => {
      if (node.nodeType === Node.TEXT_NODE) return node.textContent || "";
      if (!(node instanceof HTMLElement)) return "";
      const content = Array.from(node.childNodes).map(serialize).join("");
      const tag = node.tagName.toLowerCase();
      if (["strong", "b"].includes(tag)) return `**${content}**`;
      if (["em", "i"].includes(tag)) return `*${content}*`;
      if (tag === "code") return `\`${content}\``;
      if (tag === "a") { const href = safeUrl(node.getAttribute("href") || ""); return href ? `[${content}](${href})` : content; }
      if (["h1", "h2", "h3", "h4", "h5", "h6"].includes(tag)) return `## ${content}\n\n`;
      if (tag === "li") return `- ${content.trim()}\n`;
      if (["ul", "ol"].includes(tag)) return `${content}\n`;
      if (tag === "blockquote") return `> ${content.trim()}\n\n`;
      if (["p", "div"].includes(tag)) return `${content}\n\n`;
      if (tag === "br") return "\n";
      return content;
    };
    const sync = (emit = true) => {
      source.value = Array.from(surface.childNodes).map(serialize).join("").replace(/\n{3,}/g, "\n\n").trimEnd();
      count.textContent = `${Array.from(source.value).length} characters`;
      if (emit) { source.dispatchEvent(new Event("input", { bubbles: true })); root.dispatchEvent(new CustomEvent("haze:editor-change", { bubbles: true, detail: { markdown: source.value } })); }
    };
    const selection = () => { const selected = window.getSelection(); if (selected?.rangeCount && surface.contains(selected.anchorNode) && surface.contains(selected.focusNode)) saved = selected.getRangeAt(0).cloneRange(); };
    const states = () => {
      selection();
      toolbar.querySelectorAll<HTMLButtonElement>("[aria-pressed][data-command]").forEach((button) => { const command = button.dataset.command!; const selected = command === "formatBlock" ? document.queryCommandValue(command).toLowerCase() === button.dataset.argument : document.queryCommandState(command); button.setAttribute("aria-pressed", String(selected)); });
    };
    const execute = (command: string, argument?: string) => {
      if (readOnly || !source.hidden) return;
      surface.focus();
      const selected = window.getSelection(); if (saved && surface.contains(saved.commonAncestorContainer)) { selected?.removeAllRanges(); selected?.addRange(saved); }
      if (command === "formatBlock" && selected?.anchorNode && (selected.anchorNode instanceof Element ? selected.anchorNode : selected.anchorNode.parentElement)?.closest("li")) document.execCommand("insertUnorderedList");
      document.execCommand(command, false, argument); sync(); states(); status.textContent = command === "createLink" ? "Link added." : "Formatting updated.";
    };
    toolbar.querySelectorAll<HTMLButtonElement>("[data-command]").forEach((button) => { button.disabled = readOnly; button.addEventListener("pointerdown", (event) => event.preventDefault()); button.addEventListener("click", () => execute(button.dataset.command!, button.dataset.argument)); });
    surface.contentEditable = readOnly ? "false" : "true"; surface.tabIndex = source.disabled ? -1 : 0; surface.setAttribute("aria-readonly", String(readOnly));
    surface.addEventListener("input", () => { sync(); states(); });
    ["keyup", "pointerup", "focusout"].forEach((type) => surface.addEventListener(type, states));
    surface.addEventListener("paste", (event) => { if (readOnly) return; event.preventDefault(); document.execCommand("insertText", false, event.clipboardData?.getData("text/plain") || ""); sync(); });
    surface.addEventListener("drop", (event) => event.preventDefault());
    source.addEventListener("input", () => { count.textContent = `${Array.from(source.value).length} characters`; });
    toggle.addEventListener("click", () => {
      if (source.hidden) { sync(false); source.hidden = false; surface.hidden = true; source.focus(); saved = null; }
      else { render(); source.hidden = true; surface.hidden = false; surface.focus(); }
      toggle.setAttribute("aria-pressed", String(!source.hidden));
      toolbar.querySelectorAll<HTMLButtonElement>("[data-command]").forEach((button) => button.disabled = readOnly || !source.hidden);
      linkTools.hidden = readOnly || !source.hidden;
      linkToggle.disabled = readOnly || !source.hidden;
      if (!source.hidden) setLink(false, false);
    });
    linkToggle.disabled = readOnly;
    linkToggle.addEventListener("pointerdown", (event) => event.preventDefault());
    linkToggle.addEventListener("click", () => { if (readOnly || !source.hidden) return; selection(); setLink(!linkPanel.hasAttribute("data-open")); });
    const insertLink = () => {
      const href = safeUrl(url.value.trim()); url.setCustomValidity(href ? "" : "Enter a complete https, http or mailto URL."); if (!href) { url.reportValidity(); return; }
      execute("createLink", href); setLink(false, false); url.value = "";
    };
    addLink.addEventListener("click", insertLink);
    url.addEventListener("keydown", (event) => { if (event.key === "Enter") { event.preventDefault(); insertLink(); } else if (event.key === "Escape") { event.preventDefault(); setLink(false); } });
    url.addEventListener("input", () => url.setCustomValidity(""));
    root.querySelector<HTMLLabelElement>(`label[for="${CSS.escape(source.id)}"]`)?.addEventListener("click", (event) => { if (source.hidden) { event.preventDefault(); surface.focus(); } });
    source.addEventListener("invalid", () => { source.hidden = false; surface.hidden = true; toggle.setAttribute("aria-pressed", "true"); });
    source.form?.addEventListener("reset", () => queueMicrotask(() => { render(); saved = null; count.textContent = `${Array.from(source.value).length} characters`; status.textContent = "Editor reset."; }));
    render(); source.hidden = true; surface.hidden = false; toolbar.hidden = false;
    linkTools.hidden = readOnly;
    root.setAttribute("data-enhanced", "");
  }
  const init = () => document.querySelectorAll<HTMLElement>("[data-haze-rich-text-editor]").forEach(enhance);
  init();
  if (!document.documentElement.hasAttribute("data-haze-rich-text-editor-listener")) {
    document.documentElement.setAttribute("data-haze-rich-text-editor-listener", "");
    document.addEventListener("astro:page-load", init);
  }
</script>
```
