import React, { useCallback } from 'react' import type { EditorView } from '@codemirror/view' interface EditorToolbarProps { viewRef: React.MutableRefObject } export const EditorToolbar = React.memo(function EditorToolbar({ viewRef }: EditorToolbarProps) { const insertFormatting = useCallback((before: string, after: string, placeholder: string) => { const view = viewRef.current if (!view) return const { from, to } = view.state.selection.main const selected = view.state.sliceDoc(from, to) const text = selected || placeholder const insert = before + text + after view.dispatch({ changes: { from, to, insert }, selection: { anchor: from + before.length, head: from + before.length + text.length } }) view.focus() }, [viewRef]) const insertLinePrefix = useCallback((prefix: string) => { const view = viewRef.current if (!view) return const { from } = view.state.selection.main const line = view.state.doc.lineAt(from) const currentLine = view.state.sliceDoc(line.from, line.to) if (currentLine.startsWith(prefix)) { view.dispatch({ changes: { from: line.from, to: line.from + prefix.length, insert: '' } }) } else { view.dispatch({ changes: { from: line.from, to: line.from, insert: prefix } }) } view.focus() }, [viewRef]) const insertBlock = useCallback((text: string) => { const view = viewRef.current if (!view) return const { from } = view.state.selection.main const line = view.state.doc.lineAt(from) const insertPos = line.to + 1 view.dispatch({ changes: { from: insertPos, to: insertPos, insert: '\n' + text + '\n' }, selection: { anchor: insertPos + 1, head: insertPos + 1 + text.length } }) view.focus() }, [viewRef]) return (
) }) EditorToolbar.displayName = 'EditorToolbar'