import { Bold, Italic, Heading2, Link, Quote, List, ListOrdered, Minus } from 'lucide-react' interface Props { textareaRef: React.RefObject onUpdate: (value: string) => void dark?: boolean } type FormatAction = { type: 'wrap'; before: string; after: string } | { type: 'line'; prefix: string } | { type: 'insert'; text: string } const ACTIONS: Array<{ icon: typeof Bold; label: string; action: FormatAction }> = [ { icon: Bold, label: 'Bold', action: { type: 'wrap', before: '**', after: '**' } }, { icon: Italic, label: 'Italic', action: { type: 'wrap', before: '_', after: '_' } }, { icon: Heading2, label: 'Heading', action: { type: 'line', prefix: '## ' } }, { icon: Quote, label: 'Quote', action: { type: 'line', prefix: '> ' } }, { icon: Link, label: 'Link', action: { type: 'wrap', before: '[', after: '](url)' } }, { icon: List, label: 'List', action: { type: 'line', prefix: '- ' } }, { icon: ListOrdered, label: 'Ordered', action: { type: 'line', prefix: '1. ' } }, { icon: Minus, label: 'Divider', action: { type: 'insert', text: '\n\n---\n\n' } }, ] export default function MarkdownToolbar({ textareaRef, onUpdate, dark }: Props) { const apply = (action: FormatAction) => { const ta = textareaRef.current if (!ta) return const start = ta.selectionStart const end = ta.selectionEnd const text = ta.value const selected = text.slice(start, end) let result: string let cursorPos: number if (action.type === 'wrap') { result = text.slice(0, start) + action.before + selected + action.after + text.slice(end) cursorPos = selected ? end + action.before.length + action.after.length : start + action.before.length } else if (action.type === 'insert') { result = text.slice(0, start) + action.text + text.slice(end) cursorPos = start + action.text.length } else { // line prefix — find start of current line const lineStart = text.lastIndexOf('\n', start - 1) + 1 result = text.slice(0, lineStart) + action.prefix + text.slice(lineStart) cursorPos = start + action.prefix.length } onUpdate(result) // restore cursor after React re-render requestAnimationFrame(() => { ta.focus() ta.setSelectionRange(cursorPos, cursorPos) }) } return (
{ACTIONS.map(a => ( ))}
) }