import React, { useImperativeHandle, useRef } from "react"; import { type MarkdownActionType, wrapMarkdownSyntax } from "../../domain/notes"; export interface NoteSourceEditorHandle { insertAction: (action: MarkdownActionType) => void; focus: () => void; } export interface NoteSourceEditorProps { value: string; placeholder?: string; onChange: (value: string) => void; className?: string; noteFontFamily?: string; noteFontSize?: number; } export const NoteSourceEditor = React.forwardRef( ({ value, placeholder = "", onChange, className = "", noteFontFamily, noteFontSize }, ref) => { const textareaRef = useRef(null); const lineNumbersRef = useRef(null); const lineCount = (value.match(/\n/g)?.length || 0) + 1; const lineNumbers = Array.from({ length: lineCount }, (_, i) => i + 1); const gutterWidth = Math.max(48, String(lineCount).length * 9 + 24); const handleScroll = () => { if (textareaRef.current && lineNumbersRef.current) { lineNumbersRef.current.scrollTop = textareaRef.current.scrollTop; } }; const handleKeyDown = (e: React.KeyboardEvent) => { const textarea = textareaRef.current; if (!textarea) return; // Handle Tab insertion if (e.key === "Tab") { e.preventDefault(); const start = textarea.selectionStart; const end = textarea.selectionEnd; const nextValue = `${value.substring(0, start)} ${value.substring(end)}`; onChange(nextValue); requestAnimationFrame(() => { textarea.selectionStart = start + 2; textarea.selectionEnd = start + 2; }); } }; useImperativeHandle(ref, () => ({ insertAction: (action: MarkdownActionType) => { const textarea = textareaRef.current; if (!textarea) return; const start = textarea.selectionStart; const end = textarea.selectionEnd; const result = wrapMarkdownSyntax(value, start, end, action); onChange(result.text); requestAnimationFrame(() => { textarea.focus(); textarea.setSelectionRange(result.selectionStart, result.selectionEnd); }); }, focus: () => { textareaRef.current?.focus(); }, })); return (
{/* Line numbers gutter */}
{ if (textareaRef.current) { textareaRef.current.scrollTop += e.deltaY; } }} > {lineNumbers.map((num) => (
{num}
))}
{/* Source Textarea */}