Markdown editor
Markdown composer with Write/Preview tabs, selection-wrapping formatting toolbar, character counter, and safe DOM preview.
pnpm dlx shadcn@latest add @haze/markdown-editor---
import { Bold, Code, Heading2, Italic, Link2, List, Quote } from "@lucide/astro";
import { cn } from "../../../lib/haze/utils";
interface Props {
id: string;
name?: string;
label?: string;
value?: string;
placeholder?: string;
rows?: number;
class?: string;
}
const {
id,
name = id,
label = "Release notes",
value = "## Summary\n- Aligned UI primitives with **opaque hairlines**\n- Added `pnpm check` contrast validation\n\n> Ready for production deployment.",
placeholder = "Write in Markdown…",
rows = 6,
class: className,
} = Astro.props;
const actions = [
{ key: "h2", title: "Heading", pre: "## ", post: "", Icon: Heading2, divider: false },
{ key: "bold", title: "Bold", pre: "**", post: "**", Icon: Bold, divider: false },
{ key: "italic", title: "Italic", pre: "*", post: "*", Icon: Italic, divider: false },
{ key: "code", title: "Inline code", pre: "`", post: "`", Icon: Code, divider: true },
{ key: "link", title: "Link", pre: "[", post: "](https://)", Icon: Link2, divider: false },
{ key: "list", title: "List item", pre: "- ", post: "", Icon: List, divider: true },
{ key: "quote", title: "Quote", pre: "> ", post: "", Icon: Quote, divider: false },
];
const tab = "relative inline-flex h-8 cursor-pointer items-center rounded-sm border border-transparent px-3 font-medium text-muted-foreground transition-[color,scale] duration-150 ease-snappy select-none hover:text-foreground aria-selected:border-frame aria-selected:bg-background aria-selected:text-foreground aria-selected:shadow-key [[data-enhanced]_&]:aria-selected:border-transparent [[data-enhanced]_&]:aria-selected:bg-transparent [[data-enhanced]_&]:aria-selected:shadow-none focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-ring active:scale-[0.97] active:duration-75";
// Same rhythm as the typography component at size sm.
const prose = "text-[0.8125rem]/6 text-foreground [&_h2]:text-lg/7 [&_h3]:text-base/6 [&_h2]:font-semibold [&_h3]:font-semibold [&_h2]:tracking-tight [&_h3]:tracking-tight [&>*+*]:mt-3.5 [&>h2]:mt-8 [&>h3]:mt-6 [&>h2+*]:mt-2 [&>h3+*]:mt-2 [&>:first-child]:mt-0 [&_strong]:font-semibold [&_em]:italic [&_:where(p,li,blockquote)]:wrap-break-word [&_ul]:list-disc [&_:where(ul)]:pl-5 [&_:where(ul)]: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 id={`${id}-wrap`} data-haze-markdown-editor class={cn("grid min-w-0 gap-2", className)}>
<label for={id} class="text-[0.8125rem]/5 font-medium text-foreground">{label}</label>
<div class="min-w-0 overflow-hidden rounded-xl border border-frame-input bg-field transition-[border-color,box-shadow] duration-150 ease-snappy hover:border-frame-foreground has-[:is(textarea):focus-visible]:border-ring has-[:is(textarea):focus-visible]:ring-3 has-[:is(textarea):focus-visible]:ring-ring/24">
<!-- Header bar: mode switcher + formatting toolbar -->
<div class="hidden flex-wrap items-center justify-between gap-x-3 gap-y-2 border-b [[data-enhanced]_&]:flex border-border bg-muted/40 px-2.5 py-2">
<div role="tablist" aria-label="Editor mode" data-md-tabs class="relative isolate inline-flex items-center gap-1 rounded-lg border border-frame bg-muted p-1 text-[0.8125rem]/5">
<span data-md-indicator aria-hidden="true" class="pointer-events-none absolute top-0 left-0 -z-10 hidden h-(--md-h) w-(--md-w) translate-x-(--md-x) translate-y-(--md-y) rounded-sm border border-frame bg-background shadow-key [[data-enhanced]_&]:block [[data-ready]_&]:transition-[translate,width] [[data-ready]_&]:duration-200 [[data-ready]_&]:ease-snappy motion-reduce:[[data-ready]_&]:transition-none"></span>
<button type="button" role="tab" id={`${id}-tab-write`} aria-controls={id} data-md-mode="write" aria-selected="true" tabindex="0" class={tab}>Write</button>
<button type="button" role="tab" id={`${id}-tab-preview`} aria-controls={`${id}-preview`} data-md-mode="preview" aria-selected="false" tabindex="-1" class={tab}>Preview</button>
</div>
<div role="toolbar" aria-label="Markdown formatting" data-md-toolbar class="flex min-w-0 items-center gap-0.5 overflow-x-auto p-0.5">
{
actions.map(({ key, title, pre, post, Icon, divider }) => (
<>
{divider && <span aria-hidden="true" class="mx-1 h-5 w-px shrink-0 bg-border" />}
<button
type="button"
data-md-act={key}
data-pre={pre}
data-post={post}
aria-label={title}
title={title}
class="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"
>
<Icon class="size-4" aria-hidden="true" />
</button>
</>
))
}
</div>
</div>
<textarea
id={id}
name={name}
rows={rows}
placeholder={placeholder}
data-md-textarea
class="block w-full min-w-0 resize-y bg-transparent px-3.5 py-3 font-mono text-xs/6 text-foreground placeholder:font-sans placeholder:text-muted-foreground focus:outline-hidden"
>{value}</textarea>
<div data-md-preview id={`${id}-preview`} role="tabpanel" aria-labelledby={`${id}-tab-preview`} hidden class={cn("min-h-36 px-3.5 py-3", prose)}></div>
<div class="flex items-center justify-between border-t border-border bg-muted/30 px-3 py-1.5 text-[0.6875rem] text-muted-foreground">
<span>Markdown supported</span>
<span data-md-count class="font-mono tabular-nums">{value.length} chars</span>
</div>
</div>
</div>
<script>
function renderMarkdownSafely(container: HTMLElement, src: string) {
container.replaceChildren();
const lines = src.split(/\r?\n/);
let ul: HTMLUListElement | null = null;
const flushList = () => {
if (ul) {
container.append(ul);
ul = null;
}
};
const appendInline = (parent: HTMLElement, text: string) => {
const tokens = text.split(/(`[^`]+`|\*\*[^*]+\*\*|\*[^*]+\*)/g);
for (const tok of tokens) {
if (!tok) continue;
if (tok.startsWith("`") && tok.endsWith("`")) {
const code = document.createElement("code");
code.textContent = tok.slice(1, -1);
parent.append(code);
} else if (tok.startsWith("**") && tok.endsWith("**")) {
const strong = document.createElement("strong");
strong.textContent = tok.slice(2, -2);
parent.append(strong);
} else if (tok.startsWith("*") && tok.endsWith("*")) {
const em = document.createElement("em");
em.textContent = tok.slice(1, -1);
parent.append(em);
} else {
parent.append(document.createTextNode(tok));
}
}
};
for (const raw of lines) {
const line = raw.trimEnd();
if (!line.trim()) {
flushList();
continue;
}
if (line.startsWith("- ") || line.startsWith("* ")) {
if (!ul) {
ul = document.createElement("ul");
}
const li = document.createElement("li");
appendInline(li, line.slice(2));
ul.append(li);
continue;
}
flushList();
const heading = /^(#{1,3}) (.*)$/.exec(line);
if (heading) {
const h = document.createElement(heading[1].length === 3 ? "h3" : "h2");
appendInline(h, heading[2]);
container.append(h);
} else if (line.startsWith("> ")) {
const bq = document.createElement("blockquote");
appendInline(bq, line.slice(2));
container.append(bq);
} else {
const p = document.createElement("p");
appendInline(p, line);
container.append(p);
}
}
flushList();
if (!container.childNodes.length) {
const empty = document.createElement("p");
empty.className = "text-muted-foreground";
empty.textContent = "Nothing to preview yet.";
container.append(empty);
}
}
function initMarkdownEditors() {
document.querySelectorAll<HTMLElement>("[data-haze-markdown-editor]:not([data-enhanced])").forEach((root) => {
root.setAttribute("data-enhanced", "");
const area = root.querySelector<HTMLTextAreaElement>("[data-md-textarea]");
const preview = root.querySelector<HTMLElement>("[data-md-preview]");
const toolbar = root.querySelector<HTMLElement>("[data-md-toolbar]");
const countEl = root.querySelector<HTMLElement>("[data-md-count]");
const modeBtns = Array.from(root.querySelectorAll<HTMLButtonElement>("[data-md-mode]"));
if (!area || !preview) return;
const updateCount = () => {
if (countEl) countEl.textContent = `${area.value.length} chars`;
};
area.addEventListener("input", updateCount);
const tabs = root.querySelector<HTMLElement>("[data-md-tabs]");
const indicator = root.querySelector<HTMLElement>("[data-md-indicator]");
const place = (slide = false) => {
const current = modeBtns.find((b) => b.getAttribute("aria-selected") === "true");
if (!tabs || !indicator || !current) return;
tabs.toggleAttribute("data-ready", slide);
indicator.style.setProperty("--md-x", `${current.offsetLeft}px`);
indicator.style.setProperty("--md-y", `${current.offsetTop}px`);
indicator.style.setProperty("--md-w", `${current.offsetWidth}px`);
indicator.style.setProperty("--md-h", `${current.offsetHeight}px`);
};
root.setAttribute("data-enhanced", "");
place(false);
if ("ResizeObserver" in window && tabs) new ResizeObserver(() => requestAnimationFrame(() => place(false))).observe(tabs);
document.fonts?.ready.then(() => { if (root.isConnected) place(false); });
modeBtns.forEach((btn, index) => {
btn.addEventListener("keydown", (event) => {
const last = modeBtns.length - 1;
const next = event.key === "ArrowRight" ? (index + 1) % modeBtns.length : event.key === "ArrowLeft" ? (index + last) % modeBtns.length : event.key === "Home" ? 0 : event.key === "End" ? last : -1;
if (next < 0) return;
event.preventDefault();
modeBtns[next].focus();
modeBtns[next].click();
});
btn.addEventListener("click", () => {
const isPreview = btn.dataset.mdMode === "preview";
if (isPreview) preview.style.minHeight = `${area.offsetHeight}px`;
modeBtns.forEach((b) => { b.setAttribute("aria-selected", String(b === btn)); b.tabIndex = b === btn ? 0 : -1; });
area.hidden = isPreview;
preview.hidden = !isPreview;
if (toolbar) toolbar.hidden = isPreview;
place(true);
if (isPreview) renderMarkdownSafely(preview, area.value);
});
});
root.querySelectorAll<HTMLButtonElement>("[data-md-act]").forEach((btn) => {
btn.addEventListener("click", () => {
const pre = btn.dataset.pre ?? "";
const post = btn.dataset.post ?? "";
const start = area.selectionStart ?? area.value.length;
const end = area.selectionEnd ?? start;
const selected = area.value.slice(start, end) || "text";
area.setRangeText(`${pre}${selected}${post}`, start, end, "select");
area.focus();
updateCount();
});
});
});
}
initMarkdownEditors();
if (!document.documentElement.hasAttribute("data-haze-md-listener")) {
document.documentElement.setAttribute("data-haze-md-listener", "");
document.addEventListener("astro:page-load", initMarkdownEditors);
}
</script>When to use
- Authoring release notes, issue descriptions, or changelog entries in Markdown
- Developer-facing forms needing plain Markdown stored in a textarea
When not to use
- Plain multi-line input needs no preview; use textarea
- WYSIWYG formatting is required; use rich-text-editor
Installation
Add the Haze registry to components.json once, then install Markdown editor with the shadcn CLI. Works in any Astro project with Tailwind CSS v4.
pnpm dlx shadcn@latest add @haze/markdown-editornpx shadcn@latest add @haze/markdown-editoryarn dlx shadcn@latest add @haze/markdown-editorbunx --bun shadcn@latest add @haze/markdown-editorFirst time? Registry and theme setup
1. Add to components.json:
{
"registries": {
"@haze": "http://localhost:4329/r/{name}.json"
}
}2. Install the theme once: npx shadcn@latest add @haze/theme, then import it after Tailwind in your global CSS:@import "./haze.css";
API reference
| Prop | Type | Default | Description |
|---|---|---|---|
| id* | string | – | Id and form field name for the underlying textarea. |
| label | string | "Release notes" | Field label above the editor frame. |
| value | string | – | Initial Markdown string. |
| rows | number | 6 | Initial textarea row height. |
Accessibility
- Formatting toolbar preserves undo/selection state using native HTMLTextAreaElement.setRangeText.
- Preview pane constructs semantic headings, lists, and blockquotes safely via DOM nodes rather than raw HTML injection.
Notes for AI
Copy into Claude Code, Cursor, Codex or any coding agent. Agents can also read the Markdown version of this page.
Install and use
Install the Haze UI component "Markdown editor" with `npx shadcn@latest add @haze/markdown-editor`. If components.json has no "@haze" registry yet, add "registries": { "@haze": "http://localhost:4329/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 MarkdownEditor from "@/components/haze/ui/markdown-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: http://localhost:4329/ui/markdown-editor.md
Customize with real content
Adapt the Haze markdown-editor ui for our product. Replace the demo values of these props with our real content: id, label, value, rows. Keep the layout, the heading level rules and these accessibility details: Formatting toolbar preserves undo/selection state using native HTMLTextAreaElement.setRangeText. Preview pane constructs semantic headings, lists, and blockquotes safely via DOM nodes rather than raw HTML injection. Do not add raw color classes; use the Haze tokens.
Choose the right block
Before using markdown-editor, check it fits: use it when authoring release notes, issue descriptions, or changelog entries in markdown; developer-facing forms needing plain markdown stored in a textarea. Avoid it when plain multi-line input needs no preview; use textarea; wysiwyg formatting is required; use rich-text-editor. Alternatives: @haze/rich-text-editor, @haze/textarea.
Dependencies
- npm: @lucide/astro
- @haze/utils
- @haze/theme (one-time setup)
Source · Original Haze UI work.