Skip to documentation
Design system / Sources & standards
Current repository source
markdown-textarea.tsx
src/components/ui/markdown-textarea.tsx
This view contains the escaped source read during the deployment build. Code and policy text are unchanged. Markdown is shown as source, not rendered as a document. A new deployment refreshes the content.
"use client";
import { useCallback, useRef, type KeyboardEvent } from "react";
import { Button } from "@/components/ui/button";
import { Textarea } from "@/components/ui/textarea";
import { Bold, Italic } from "lucide-react";
type MarkdownTextareaProps = {
value: string;
onChange: (value: string) => void;
id?: string;
name?: string;
placeholder?: string;
rows?: number;
className?: string;
};
export function MarkdownTextarea({
value,
onChange,
id,
name,
placeholder,
rows = 4,
className,
}: MarkdownTextareaProps) {
const textareaRef = useRef<HTMLTextAreaElement>(null);
const wrapSelection = useCallback(
(wrapper: string) => {
const textarea = textareaRef.current;
if (!textarea) return;
const { selectionStart, selectionEnd } = textarea;
const before = value.slice(0, selectionStart);
const selected = value.slice(selectionStart, selectionEnd);
const after = value.slice(selectionEnd);
const wrapped = `${before}${wrapper}${selected}${wrapper}${after}`;
onChange(wrapped);
requestAnimationFrame(() => {
textarea.focus();
const cursorPos = selected
? selectionEnd + wrapper.length * 2
: selectionStart + wrapper.length;
textarea.setSelectionRange(cursorPos, cursorPos);
});
},
[value, onChange],
);
const handleBold = useCallback(() => wrapSelection("**"), [wrapSelection]);
const handleItalic = useCallback(() => wrapSelection("*"), [wrapSelection]);
const handleKeyDown = useCallback(
(event: KeyboardEvent<HTMLTextAreaElement>) => {
if ((event.ctrlKey || event.metaKey) && event.key === "b") {
event.preventDefault();
handleBold();
}
if ((event.ctrlKey || event.metaKey) && event.key === "i") {
event.preventDefault();
handleItalic();
}
},
[handleBold, handleItalic],
);
return (
<div className={className}>
<div className="flex items-center gap-0.5 rounded-t-md border border-b-0 border-input bg-muted/40 px-1.5 py-0.5">
<Button
type="button"
variant="ghost"
size="icon"
className="h-7 w-7"
onClick={handleBold}
title="Bold (Ctrl+B)"
aria-label="Bold"
>
<Bold className="h-3.5 w-3.5" />
</Button>
<Button
type="button"
variant="ghost"
size="icon"
className="h-7 w-7"
onClick={handleItalic}
title="Italic (Ctrl+I)"
aria-label="Italic"
>
<Italic className="h-3.5 w-3.5" />
</Button>
<span className="ml-auto text-supporting text-muted-foreground">
Markdown supported
</span>
</div>
<Textarea
ref={textareaRef}
id={id}
name={name}
value={value}
onChange={(event) => onChange(event.target.value)}
onKeyDown={handleKeyDown}
placeholder={placeholder}
rows={rows}
className="rounded-t-none border-t-0 focus-visible:ring-0 focus-visible:ring-offset-0"
/>
</div>
);
}All sources and standards