-
Notifications
You must be signed in to change notification settings - Fork 23
/
index.tsx
85 lines (81 loc) · 2.81 KB
/
index.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import React, { useState, createRef, useRef, useEffect } from 'react';
import { IProps } from './common/props';
import CodeMirror, { ICodeMirror } from './components/CodeMirror';
import MarkdownPreview, { MarkdownPreviewProps } from '@uiw/react-markdown-preview';
import ToolBar, { IToolBarProps } from './components/ToolBar';
import { getCommands, getModeCommands } from './commands';
import './index.less';
export * from './commands';
export interface IMarkdownEditor extends IProps, ICodeMirror {
prefixCls?: string,
value?: string,
height?: number,
visible?: boolean,
visibleEditor?: boolean,
toolbars?: IToolBarProps['toolbars'],
toolbarsMode?: IToolBarProps['toolbars'],
previewProps?: MarkdownPreviewProps;
options?: CodeMirror.EditorConfiguration,
}
export default function MarkdownEditor(props: IMarkdownEditor) {
const {
prefixCls = 'md-editor', className,
onChange,
toolbars = getCommands(),
toolbarsMode = getModeCommands(),
visible = true,
visibleEditor = true,
previewProps = {}, ...codemirrorProps } = props;
const [value, setValue] = useState(props.value || '');
const codeMirror = createRef<CodeMirror>();
const previewContainer = useRef<HTMLDivElement | null>()
const [editor, setEditor] = useState<CodeMirror.Editor>();
const container = useRef<HTMLDivElement>(null);
const containerEditor = useRef<HTMLDivElement>(null);
useEffect(() => {
if (codeMirror.current) {
setEditor(codeMirror.current.editor);
}
}, [codeMirror.current]);
const toolBarProps = {
editor,
preview: previewContainer.current,
container: container.current,
containerEditor: containerEditor.current,
editorProps: props
}
return (
<div ref={container}>
<div className={`${prefixCls || ''} ${className || ''}`}>
<ToolBar {...toolBarProps} toolbars={toolbarsMode} mode />
<ToolBar {...toolBarProps} toolbars={toolbars} />
<div className={`${prefixCls}-content`}>
<div className={`${prefixCls}-content-editor`} ref={containerEditor}>
{visibleEditor && (
<CodeMirror
visibleEditor={visibleEditor}
{...codemirrorProps}
ref={codeMirror}
onChange={(editor, data) => {
setValue(editor.getValue());
onChange && onChange(editor, data, editor.getValue())
}}
/>
)}
</div>
<MarkdownPreview
{...previewProps}
data-visible={!!visible}
className={`${prefixCls}-preview`}
ref={(instance) => {
if(instance && instance.mdp) {
previewContainer.current = instance.mdp.current
}
}}
source={value}
/>
</div>
</div>
</div>
);
}