-
-
Notifications
You must be signed in to change notification settings - Fork 173
/
Copy pathEditor.tsx
410 lines (392 loc) · 14.1 KB
/
Editor.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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
import React, { useEffect, useReducer, useMemo, useRef, useImperativeHandle, CSSProperties } from 'react';
import MarkdownPreview, { MarkdownPreviewProps } from '@uiw/react-markdown-preview';
import TextArea, { ITextAreaProps } from './components/TextArea';
import Toolbar from './components/Toolbar';
import DragBar from './components/DragBar';
import { getCommands, getExtraCommands, ICommand, TextState, TextAreaCommandOrchestrator } from './commands';
import { reducer, EditorContext, ContextStore, PreviewType } from './Context';
import './index.less';
export interface IProps {
prefixCls?: string;
className?: string;
}
export interface Statistics extends TextState {
/** total length of the document */
length: number;
/** Get the number of lines in the editor. */
lineCount: number;
}
export interface MDEditorProps extends Omit<React.HTMLAttributes<HTMLDivElement>, 'onChange'>, IProps {
/**
* The Markdown value.
*/
value?: string;
/**
* Event handler for the `onChange` event.
*/
onChange?: (value?: string, event?: React.ChangeEvent<HTMLTextAreaElement>, state?: ContextStore) => void;
/**
* editor height change listener
*/
onHeightChange?: (value?: CSSProperties['height'], oldValue?: CSSProperties['height'], state?: ContextStore) => void;
/** Some data on the statistics editor. */
onStatistics?: (data: Statistics) => void;
/**
* Can be used to make `Markdown Editor` focus itself on initialization. Defaults to on.
* it will be set to true when either the source `textarea` is focused,
* or it has an `autofocus` attribute and no other element is focused.
*/
autoFocus?: ITextAreaProps['autoFocus'];
/**
* The height of the editor.
* ⚠️ `Dragbar` is invalid when **`height`** parameter percentage.
*/
height?: CSSProperties['height'];
/**
* Custom toolbar heigth
* @default 29px
*
* @deprecated toolbar height adaptive: https://github.com/uiwjs/react-md-editor/issues/427
*
*/
toolbarHeight?: number;
/**
* Show drag and drop tool. Set the height of the editor.
*/
visibleDragbar?: boolean;
/**
* @deprecated use `visibleDragbar`
*/
visiableDragbar?: boolean;
/**
* Show markdown preview.
*/
preview?: PreviewType;
/**
* Full screen display editor.
*/
fullscreen?: boolean;
/**
* Disable `fullscreen` setting body styles
*/
overflow?: boolean;
/**
* Maximum drag height. `visibleDragbar=true`
*/
maxHeight?: number;
/**
* Minimum drag height. `visibleDragbar=true`
*/
minHeight?: number;
/**
* This is reset [react-markdown](https://github.com/rexxars/react-markdown) settings.
*/
previewOptions?: Omit<MarkdownPreviewProps, 'source'>;
/**
* Set the `textarea` related props.
*/
textareaProps?: ITextAreaProps;
/**
* Use div to replace TextArea or re-render TextArea
* @deprecated Please use ~~`renderTextarea`~~ -> `components`
*/
renderTextarea?: ITextAreaProps['renderTextarea'];
/**
* re-render element
*/
components?: {
/** Use div to replace TextArea or re-render TextArea */
textarea?: ITextAreaProps['renderTextarea'];
/**
* Override the default command element
* _`toolbar`_ < _`command[].render`_
*/
toolbar?: ICommand['render'];
/** Custom markdown preview */
preview?: (source: string, state: ContextStore, dispath: React.Dispatch<ContextStore>) => JSX.Element;
};
/** Theme configuration */
'data-color-mode'?: 'light' | 'dark';
/**
* Disable editing area code highlighting. The value is `false`, which increases the editing speed.
* @default true
*/
highlightEnable?: boolean;
/**
* The number of characters to insert when pressing tab key.
* Default `2` spaces.
*/
tabSize?: number;
/**
* If `false`, the `tab` key inserts a tab character into the textarea. If `true`, the `tab` key executes default behavior e.g. focus shifts to next element.
*/
defaultTabEnable?: boolean;
/**
* You can create your own commands or reuse existing commands.
*/
commands?: ICommand[];
/**
* Filter or modify your commands.
* https://github.com/uiwjs/react-md-editor/issues/296
*/
commandsFilter?: (command: ICommand, isExtra: boolean) => false | ICommand;
/**
* You can create your own commands or reuse existing commands.
*/
extraCommands?: ICommand[];
/**
* Hide the tool bar
*/
hideToolbar?: boolean;
/** Whether to enable scrolling */
enableScroll?: boolean;
/** Toolbar on bottom */
toolbarBottom?: boolean;
/**
* The **`direction`** property sets the direction of text, table columns, and horizontal overflow. Use `rtl` for languages written from right to left (like Hebrew or Arabic), and `ltr` for those written from left to right (like English and most other languages).
*
* https://github.com/uiwjs/react-md-editor/issues/462
*/
direction?: CSSProperties['direction'];
}
function setGroupPopFalse(data: Record<string, boolean> = {}) {
Object.keys(data).forEach((keyname) => {
data[keyname] = false;
});
return data;
}
export interface RefMDEditor extends ContextStore {}
const InternalMDEditor = React.forwardRef<RefMDEditor, MDEditorProps>(
(props: MDEditorProps, ref: React.ForwardedRef<RefMDEditor>) => {
const {
prefixCls = 'w-md-editor',
className,
value: propsValue,
commands = getCommands(),
commandsFilter,
direction,
extraCommands = getExtraCommands(),
height = 200,
enableScroll = true,
visibleDragbar = typeof props.visiableDragbar === 'boolean' ? props.visiableDragbar : true,
highlightEnable = true,
preview: previewType = 'live',
fullscreen = false,
overflow = true,
previewOptions = {},
textareaProps,
maxHeight = 1200,
minHeight = 100,
autoFocus,
tabSize = 2,
defaultTabEnable = false,
onChange,
onStatistics,
onHeightChange,
hideToolbar,
toolbarBottom = false,
components,
renderTextarea,
...other
} = props || {};
const cmds = commands
.map((item) => (commandsFilter ? commandsFilter(item, false) : item))
.filter(Boolean) as ICommand[];
const extraCmds = extraCommands
.map((item) => (commandsFilter ? commandsFilter(item, true) : item))
.filter(Boolean) as ICommand[];
let [state, dispatch] = useReducer(reducer, {
markdown: propsValue,
preview: previewType,
components,
height,
highlightEnable,
tabSize,
defaultTabEnable,
scrollTop: 0,
scrollTopPreview: 0,
commands: cmds,
extraCommands: extraCmds,
fullscreen,
barPopup: {},
});
const container = useRef<HTMLDivElement>(null);
const previewRef = useRef<HTMLDivElement>(null);
const enableScrollRef = useRef(enableScroll);
useImperativeHandle(ref, () => ({ ...state, container: container.current, dispatch }));
useMemo(() => (enableScrollRef.current = enableScroll), [enableScroll]);
useEffect(() => {
const stateInit: ContextStore = {};
if (container.current) {
stateInit.container = container.current || undefined;
}
stateInit.markdown = propsValue || '';
stateInit.barPopup = {};
if (dispatch) {
dispatch({ ...state, ...stateInit });
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const cls = [
className,
'wmde-markdown-var',
direction ? `${prefixCls}-${direction}` : null,
prefixCls,
state.preview ? `${prefixCls}-show-${state.preview}` : null,
state.fullscreen ? `${prefixCls}-fullscreen` : null,
]
.filter(Boolean)
.join(' ')
.trim();
useMemo(
() => propsValue !== state.markdown && dispatch({ markdown: propsValue || '' }),
[propsValue, state.markdown],
);
// eslint-disable-next-line react-hooks/exhaustive-deps
useMemo(() => previewType !== state.preview && dispatch({ preview: previewType }), [previewType]);
// eslint-disable-next-line react-hooks/exhaustive-deps
useMemo(() => tabSize !== state.tabSize && dispatch({ tabSize }), [tabSize]);
useMemo(
() => highlightEnable !== state.highlightEnable && dispatch({ highlightEnable }),
// eslint-disable-next-line react-hooks/exhaustive-deps
[highlightEnable],
);
// eslint-disable-next-line react-hooks/exhaustive-deps
useMemo(() => autoFocus !== state.autoFocus && dispatch({ autoFocus: autoFocus }), [autoFocus]);
useMemo(
() => fullscreen !== state.fullscreen && dispatch({ fullscreen: fullscreen }),
// eslint-disable-next-line react-hooks/exhaustive-deps
[fullscreen],
);
// eslint-disable-next-line react-hooks/exhaustive-deps
useMemo(() => height !== state.height && dispatch({ height: height }), [height]);
useMemo(
() => height !== state.height && onHeightChange && onHeightChange(state.height, height, state),
[height, onHeightChange, state],
);
// eslint-disable-next-line react-hooks/exhaustive-deps
useMemo(() => commands !== state.commands && dispatch({ commands: cmds }), [props.commands]);
// eslint-disable-next-line react-hooks/exhaustive-deps
useMemo(
() => extraCommands !== state.extraCommands && dispatch({ extraCommands: extraCmds }),
[props.extraCommands],
);
const textareaDomRef = useRef<HTMLDivElement>();
const active = useRef<'text' | 'preview'>('preview');
const initScroll = useRef(false);
useMemo(() => {
textareaDomRef.current = state.textareaWarp;
if (state.textareaWarp) {
state.textareaWarp.addEventListener('mouseover', () => {
active.current = 'text';
});
state.textareaWarp.addEventListener('mouseleave', () => {
active.current = 'preview';
});
}
}, [state.textareaWarp]);
const handleScroll = (e: React.UIEvent<HTMLDivElement>, type: 'text' | 'preview') => {
if (!enableScrollRef.current) return;
const textareaDom = textareaDomRef.current;
const previewDom = previewRef.current ? previewRef.current : undefined;
if (!initScroll.current) {
active.current = type;
initScroll.current = true;
}
if (textareaDom && previewDom) {
const scale =
(textareaDom.scrollHeight - textareaDom.offsetHeight) / (previewDom.scrollHeight - previewDom.offsetHeight);
if (e.target === textareaDom && active.current === 'text') {
previewDom.scrollTop = textareaDom.scrollTop / scale;
}
if (e.target === previewDom && active.current === 'preview') {
textareaDom.scrollTop = previewDom.scrollTop * scale;
}
let scrollTop = 0;
if (active.current === 'text') {
scrollTop = textareaDom.scrollTop || 0;
} else if (active.current === 'preview') {
scrollTop = previewDom.scrollTop || 0;
}
dispatch({ scrollTop });
}
};
const previewClassName = `${prefixCls}-preview ${previewOptions.className || ''}`;
const handlePreviewScroll = (e: React.UIEvent<HTMLDivElement, UIEvent>) => handleScroll(e, 'preview');
let mdPreview = useMemo(
() => (
<div ref={previewRef} className={previewClassName}>
<MarkdownPreview {...previewOptions} onScroll={handlePreviewScroll} source={state.markdown || ''} />
</div>
),
[previewClassName, previewOptions, state.markdown],
);
const preview = components?.preview && components?.preview(state.markdown || '', state, dispatch);
if (preview && React.isValidElement(preview)) {
mdPreview = (
<div className={previewClassName} ref={previewRef} onScroll={handlePreviewScroll}>
{preview}
</div>
);
}
const containerStyle = { ...other.style, height: state.height || '100%' };
const containerClick = () => dispatch({ barPopup: { ...setGroupPopFalse(state.barPopup) } });
const dragBarChange = (newHeight: number) => dispatch({ height: newHeight });
const changeHandle = (evn: React.ChangeEvent<HTMLTextAreaElement>) => {
onChange && onChange(evn.target.value, evn, state);
if (textareaProps && textareaProps.onChange) {
textareaProps.onChange(evn);
}
if (state.textarea && state.textarea instanceof HTMLTextAreaElement && onStatistics) {
const obj = new TextAreaCommandOrchestrator(state.textarea!);
const objState = (obj.getState() || {}) as TextState;
onStatistics({
...objState,
lineCount: evn.target.value.split('\n').length,
length: evn.target.value.length,
});
}
};
return (
<EditorContext.Provider value={{ ...state, dispatch }}>
<div ref={container} className={cls} {...other} onClick={containerClick} style={containerStyle}>
{!hideToolbar && !toolbarBottom && (
<Toolbar prefixCls={prefixCls} overflow={overflow} toolbarBottom={toolbarBottom} />
)}
<div className={`${prefixCls}-content`}>
{/(edit|live)/.test(state.preview || '') && (
<TextArea
className={`${prefixCls}-input`}
prefixCls={prefixCls}
autoFocus={autoFocus}
{...textareaProps}
onChange={changeHandle}
renderTextarea={components?.textarea || renderTextarea}
onScroll={(e) => handleScroll(e, 'text')}
/>
)}
{/(live|preview)/.test(state.preview || '') && mdPreview}
</div>
{visibleDragbar && !state.fullscreen && (
<DragBar
prefixCls={prefixCls}
height={state.height as number}
maxHeight={maxHeight!}
minHeight={minHeight!}
onChange={dragBarChange}
/>
)}
{!hideToolbar && toolbarBottom && (
<Toolbar prefixCls={prefixCls} overflow={overflow} toolbarBottom={toolbarBottom} />
)}
</div>
</EditorContext.Provider>
);
},
);
type EditorComponent = typeof InternalMDEditor & {
Markdown: typeof MarkdownPreview;
};
const Editor = InternalMDEditor as EditorComponent;
Editor.Markdown = MarkdownPreview;
export default Editor;