316 lines
9.0 KiB
TypeScript
316 lines
9.0 KiB
TypeScript
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<EditorPaneHandle, Props>(function EditorPane(
|
||
{
|
||
content,
|
||
onChange,
|
||
mode,
|
||
onModeChange,
|
||
tocOpen,
|
||
onTocOpenChange,
|
||
charCount,
|
||
},
|
||
ref,
|
||
) {
|
||
const textareaRef = useRef<TextAreaRef>(null);
|
||
const [activeTocId, setActiveTocId] = useState<string | null>(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<HTMLTextAreaElement>) => {
|
||
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 (
|
||
<section className={`${styles.pane} ${styles.editorPane}`}>
|
||
<div className={styles.paneHeader}>
|
||
<div className={styles.paneHeaderLeft}>
|
||
<span className={styles.paneTitle}>
|
||
{isMarkdown ? 'Markdown' : '普通编辑'}
|
||
</span>
|
||
<Tooltip title={tocOpen ? '收起目录' : '展开目录'}>
|
||
<button
|
||
type="button"
|
||
className={styles.tocToggle}
|
||
onClick={() => onTocOpenChange(!tocOpen)}
|
||
aria-expanded={tocOpen}
|
||
aria-label={tocOpen ? '收起目录' : '展开目录'}
|
||
>
|
||
目录 {tocOpen ? '◂' : '▸'}
|
||
</button>
|
||
</Tooltip>
|
||
</div>
|
||
<div className={styles.paneHeaderRight}>
|
||
<Segmented
|
||
size="small"
|
||
value={mode}
|
||
onChange={(value) =>
|
||
onModeChange(value === 'plain' ? 'plain' : 'markdown')
|
||
}
|
||
options={[
|
||
{ label: 'MD', value: 'markdown' },
|
||
{ label: '普通', value: 'plain' },
|
||
]}
|
||
/>
|
||
<span className={styles.paneMeta}>{charCount} 字</span>
|
||
</div>
|
||
</div>
|
||
|
||
<div className={styles.editorBody}>
|
||
{tocOpen && (
|
||
<aside className={styles.tocPanel} aria-label="标题大纲">
|
||
<div className={styles.tocTitle}>大纲</div>
|
||
{toc.length === 0 ? (
|
||
<p className={styles.tocEmpty}>暂无标题,用 # 写一级标题</p>
|
||
) : (
|
||
<ul className={styles.tocList}>
|
||
{toc.map((item) => (
|
||
<li key={item.id}>
|
||
<button
|
||
type="button"
|
||
className={`${styles.tocItem} ${
|
||
activeTocId === item.id ? styles.tocItemActive : ''
|
||
}`}
|
||
style={{ paddingLeft: 8 + (item.level - 1) * 12 }}
|
||
onClick={() => jumpToHeading(item.line, item.id)}
|
||
title={item.text}
|
||
>
|
||
<span className={styles.tocLevel}>H{item.level}</span>
|
||
{item.text}
|
||
</button>
|
||
</li>
|
||
))}
|
||
</ul>
|
||
)}
|
||
</aside>
|
||
)}
|
||
|
||
<Dropdown
|
||
menu={{ items: isMarkdown ? contextItems : [] }}
|
||
trigger={isMarkdown ? ['contextMenu'] : []}
|
||
>
|
||
<div
|
||
className={`${styles.editorWrap} ${
|
||
isMarkdown ? styles.editorMarkdown : styles.editorPlain
|
||
}`}
|
||
>
|
||
<TextArea
|
||
ref={textareaRef}
|
||
className={styles.editor}
|
||
value={content}
|
||
onChange={(e) => onChange(e.target.value)}
|
||
onKeyDown={onEditorKeyDown}
|
||
placeholder={
|
||
isMarkdown
|
||
? `在此输入 Markdown…
|
||
|
||
右键插入 · Enter 续列表 · Tab 缩进
|
||
快捷键:Ctrl+B 加粗 · Ctrl+I 斜体 · Ctrl+K 链接`
|
||
: `普通文本编辑模式
|
||
|
||
适合自由写作;切换回 MD 后仍可一键转公众号预览`
|
||
}
|
||
autoFocus
|
||
spellCheck={mode === 'plain'}
|
||
aria-label={isMarkdown ? 'Markdown 编辑器' : '普通文本编辑器'}
|
||
style={{ height: '100%', resize: 'none' }}
|
||
/>
|
||
</div>
|
||
</Dropdown>
|
||
</div>
|
||
</section>
|
||
);
|
||
});
|
||
|
||
export default EditorPane;
|