import React, { forwardRef, useCallback, useImperativeHandle, useMemo, useRef, useState, } from 'react'; import { Dropdown, Input, Segmented, Tooltip } from 'antd'; import type { MenuProps } from 'antd'; import type { TextAreaRef } from 'antd/es/input/TextArea'; import { EDITOR_ACTIONS, applyEditorAction, handleMarkdownEnter, handleMarkdownTab, insertBlockChunk, type EditorAction, } from '../lib/editorActions'; import type { EditorMode } from '../lib/storage'; import { offsetAtLine, parseToc } from '../lib/toc'; import styles from '../App.module.scss'; const { TextArea } = Input; export type EditorPaneHandle = { runAction: (action: EditorAction) => void; runActionById: (id: string) => boolean; insertAtCursor: (chunk: string) => void; }; type Props = { content: string; onChange: (value: string) => void; mode: EditorMode; onModeChange: (mode: EditorMode) => void; tocOpen: boolean; onTocOpenChange: (open: boolean) => void; charCount: number; }; const EditorPane = forwardRef(function EditorPane( { content, onChange, mode, onModeChange, tocOpen, onTocOpenChange, charCount, }, ref, ) { const textareaRef = useRef(null); const [activeTocId, setActiveTocId] = useState(null); const getTextArea = () => textareaRef.current?.resizableTextArea?.textArea ?? null; const toc = useMemo(() => parseToc(content), [content]); const focusAndSelect = useCallback((start: number, end: number) => { window.requestAnimationFrame(() => { const el = getTextArea(); if (!el) return; el.focus(); el.setSelectionRange(start, end); const style = window.getComputedStyle(el); const lineHeight = parseFloat(style.lineHeight) || parseFloat(style.fontSize) * 1.7 || 24; const before = el.value.slice(0, start); const line = before.split('\n').length - 1; el.scrollTop = Math.max(0, line * lineHeight - el.clientHeight / 3); }); }, []); const applyResult = useCallback( (result: { next: string; selectionStart: number; selectionEnd: number }) => { onChange(result.next); focusAndSelect(result.selectionStart, result.selectionEnd); }, [focusAndSelect, onChange], ); const runAction = useCallback( (action: EditorAction) => { const el = getTextArea(); const start = el?.selectionStart ?? content.length; const end = el?.selectionEnd ?? content.length; applyResult(applyEditorAction(content, start, end, action)); }, [applyResult, content], ); const insertAtCursor = useCallback( (chunk: string) => { const el = getTextArea(); const start = el?.selectionStart ?? content.length; const end = el?.selectionEnd ?? content.length; applyResult(insertBlockChunk(content, start, end, chunk)); }, [applyResult, content], ); const runActionById = useCallback( (id: string) => { const action = EDITOR_ACTIONS.find((item) => item.id === id); if (!action) return false; runAction(action); return true; }, [runAction], ); useImperativeHandle( ref, () => ({ runAction, runActionById, insertAtCursor, }), [runAction, runActionById, insertAtCursor], ); const jumpToHeading = useCallback( (line: number, id: string) => { setActiveTocId(id); const start = offsetAtLine(content, line); const lineText = content.replace(/\r\n/g, '\n').split('\n')[line] ?? ''; focusAndSelect(start, start + lineText.length); }, [content, focusAndSelect], ); const onEditorKeyDown = useCallback( (event: React.KeyboardEvent) => { if (mode !== 'markdown') return; const el = event.currentTarget; const start = el.selectionStart; const end = el.selectionEnd; if (event.key === 'Enter' && !event.shiftKey && !event.ctrlKey && !event.metaKey) { const result = handleMarkdownEnter(content, start, end); if (result) { event.preventDefault(); applyResult(result); } return; } if (event.key === 'Tab') { event.preventDefault(); const result = handleMarkdownTab(content, start, end, event.shiftKey); if (result) { applyResult(result); } } }, [applyResult, content, mode], ); const contextItems: MenuProps['items'] = useMemo(() => { const groups: Array<{ key: string; label: string; ids: string[]; }> = [ { key: 'heading', label: '标题', ids: ['h1', 'h2', 'h3', 'h4'], }, { key: 'inline', label: '行内样式', ids: ['bold', 'italic', 'strike', 'code', 'link'], }, { key: 'block', label: '块级结构', ids: ['ul', 'ol', 'task', 'quote', 'hr'], }, { key: 'insert', label: '插入', ids: ['table', 'codeblock', 'image'], }, ]; const items: MenuProps['items'] = []; groups.forEach((group, index) => { if (index > 0) items.push({ type: 'divider' }); items.push({ key: `group-${group.key}`, type: 'group', label: group.label, children: group.ids.map((id) => { const action = EDITOR_ACTIONS.find((item) => item.id === id)!; return { key: action.id, label: action.label, onClick: () => runAction(action), }; }), }); }); return items; }, [runAction]); const isMarkdown = mode === 'markdown'; return (
{isMarkdown ? 'Markdown' : '普通编辑'}
onModeChange(value === 'plain' ? 'plain' : 'markdown') } options={[ { label: 'MD', value: 'markdown' }, { label: '普通', value: 'plain' }, ]} /> {charCount} 字
{tocOpen && ( )}