-
Notifications
You must be signed in to change notification settings - Fork 841
/
markdown_editor.tsx
526 lines (460 loc) Β· 17.4 KB
/
markdown_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
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
/*
* Licensed to Elasticsearch B.V. under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch B.V. licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import React, {
createElement,
HTMLAttributes,
useEffect,
useImperativeHandle,
useMemo,
useState,
useCallback,
useRef,
forwardRef,
} from 'react';
import unified, { PluggableList, Processor } from 'unified';
import { VFileMessage } from 'vfile-message';
import classNames from 'classnames';
import { CommonProps, OneOf } from '../common';
import MarkdownActions, { insertText } from './markdown_actions';
import { EuiMarkdownEditorToolbar } from './markdown_editor_toolbar';
import { EuiMarkdownEditorTextArea } from './markdown_editor_text_area';
import { EuiMarkdownFormat } from './markdown_format';
import { EuiMarkdownEditorDropZone } from './markdown_editor_drop_zone';
import { htmlIdGenerator } from '../../services/';
import { MARKDOWN_MODE, MODE_EDITING, MODE_VIEWING } from './markdown_modes';
import {
EuiMarkdownAstNode,
EuiMarkdownDropHandler,
EuiMarkdownEditorUiPlugin,
EuiMarkdownParseError,
EuiMarkdownStringTagConfig,
} from './markdown_types';
import { EuiOverlayMask } from '../overlay_mask';
import { EuiModal } from '../modal';
import { ContextShape, EuiMarkdownContext } from './markdown_context';
import * as MarkdownTooltip from './plugins/markdown_tooltip';
import {
defaultParsingPlugins,
defaultProcessingPlugins,
} from './plugins/markdown_default_plugins';
import { EuiResizeObserver } from '../observer/resize_observer';
type CommonMarkdownEditorProps = Omit<
HTMLAttributes<HTMLDivElement>,
'onChange'
> &
CommonProps & {
/** aria-label OR aria-labelledby must be set */
'aria-label'?: string;
/** aria-label OR aria-labelledby must be set */
'aria-labelledby'?: string;
/** ID of an element describing the text editor, useful for associating error messages */
'aria-describedby'?: string;
/** a unique ID to attach to the textarea. If one isn't provided, a random one
* will be generated */
editorId?: string;
/** A markdown content */
value: string;
/** callback function when markdown content is modified */
onChange: (value: string) => void;
/**
* Sets the `height` in pixels of the editor/preview area or pass `full` to allow
* the EuiMarkdownEditor to fill the height of its container.
* When in `full` mode the vertical resize is not allowed.
*/
height?: number | 'full';
/**
* Sets the `max-height` in pixels of the editor/preview area.
* It has no effect when the `height` is set to `full`.
*/
maxHeight?: number;
/**
* Automatically adjusts the preview height to fit all the content and avoid a scrollbar.
*/
autoExpandPreview?: boolean;
/** plugins to identify new syntax and parse it into an AST node */
parsingPluginList?: PluggableList;
/** plugins to process the markdown AST nodes into a React nodes */
processingPluginList?: PluggableList;
/** defines UI for plugins' buttons in the toolbar as well as any modals or extra UI that provides content to the editor */
uiPlugins?: EuiMarkdownEditorUiPlugin[];
/** errors to bubble up */
errors?: EuiMarkdownParseError[];
/** callback triggered when parsing results are available */
onParse?: (
error: EuiMarkdownParseError | null,
data: {
messages: VFileMessage[];
ast: EuiMarkdownAstNode;
}
) => void;
/** initial display mode for the editor */
initialViewMode?: MARKDOWN_MODE;
/** array defining any drag&drop handlers */
dropHandlers?: EuiMarkdownDropHandler[];
};
export type EuiMarkdownEditorProps = OneOf<
CommonMarkdownEditorProps,
'aria-label' | 'aria-labelledby'
>;
// TODO I wanted to use the useCombinedRefs
// but I can't because it's not allowed to use react hooks
// inside a callback.
const mergeRefs = (...refs: any[]) => {
const filteredRefs = refs.filter(Boolean);
if (!filteredRefs.length) return null;
if (filteredRefs.length === 0) return filteredRefs[0];
return (inst: any) => {
for (const ref of filteredRefs) {
if (typeof ref === 'function') {
ref(inst);
} else if (ref) {
ref.current = inst;
}
}
};
};
interface EuiMarkdownEditorRef {
textarea: HTMLTextAreaElement | null;
replaceNode: ContextShape['replaceNode'];
}
function isNewLine(char: string | undefined): boolean {
if (char == null) return true;
return !!char.match(/[\r\n]/);
}
function padWithNewlinesIfNeeded(textarea: HTMLTextAreaElement, text: string) {
const selectionStart = textarea.selectionStart;
const selectionEnd = textarea.selectionEnd;
// block parsing requires two leading new lines and none trailing, but we add an extra trailing line for readability
const isPrevNewLine = isNewLine(textarea.value[selectionStart - 1]);
const isPrevPrevNewLine = isNewLine(textarea.value[selectionStart - 2]);
const isNextNewLine = isNewLine(textarea.value[selectionEnd]);
// pad text with newlines as needed
text = `${isPrevNewLine ? '' : '\n'}${isPrevPrevNewLine ? '' : '\n'}${text}${
isNextNewLine ? '' : '\n'
}`;
return text;
}
export const EuiMarkdownEditor = forwardRef<
EuiMarkdownEditorRef,
EuiMarkdownEditorProps
>(
(
{
className,
editorId: _editorId,
value,
onChange,
height = 250,
maxHeight = 500,
autoExpandPreview = true,
parsingPluginList = defaultParsingPlugins,
processingPluginList = defaultProcessingPlugins,
uiPlugins = [],
onParse,
errors = [],
'aria-label': ariaLabel,
'aria-labelledby': ariaLabelledBy,
'aria-describedby': ariaDescribedBy,
initialViewMode = MODE_EDITING,
dropHandlers = [],
...rest
},
ref
) => {
const [viewMode, setViewMode] = useState<MARKDOWN_MODE>(initialViewMode);
const editorId = useMemo(() => _editorId || htmlIdGenerator()(), [
_editorId,
]);
const [pluginEditorPlugin, setPluginEditorPlugin] = useState<
EuiMarkdownEditorUiPlugin | undefined
>(undefined);
const toolbarPlugins = [...uiPlugins];
// @ts-ignore __originatedFromEui is a custom property
if (!uiPlugins.__originatedFromEui)
toolbarPlugins.unshift(MarkdownTooltip.plugin);
const markdownActions = useMemo(
() => new MarkdownActions(editorId, toolbarPlugins),
// toolbarPlugins _is_ accounted for
// eslint-disable-next-line react-hooks/exhaustive-deps
[editorId, toolbarPlugins.map(({ name }) => name).join(',')]
);
const parser = useMemo(() => {
const Compiler = (tree: any) => {
return tree;
};
function identityCompiler(this: Processor) {
this.Compiler = Compiler;
}
return unified().use(parsingPluginList).use(identityCompiler);
}, [parsingPluginList]);
const [parsed, parseError] = useMemo<
[any | null, EuiMarkdownParseError | null]
>(() => {
try {
const parsed = parser.processSync(value);
return [parsed, null];
} catch (e) {
return [null, e];
}
}, [parser, value]);
const isPreviewing = viewMode === MODE_VIEWING;
const isEditing = viewMode === MODE_EDITING;
const replaceNode = useCallback(
(position, next) => {
const leading = value.substr(0, position.start.offset);
const trailing = value.substr(position.end.offset);
onChange(`${leading}${next}${trailing}`);
},
[value, onChange]
);
const contextValue = useMemo<ContextShape>(
() => ({
openPluginEditor: (plugin: EuiMarkdownEditorUiPlugin) =>
setPluginEditorPlugin(() => plugin),
replaceNode,
}),
[replaceNode]
);
const [selectedNode, setSelectedNode] = useState<EuiMarkdownAstNode>();
const textareaRef = useRef<HTMLTextAreaElement>(null);
useEffect(() => {
if (textareaRef == null) return;
if (parsed == null) return;
const getCursorNode = () => {
const { selectionStart } = textareaRef.current!;
let node: EuiMarkdownAstNode = parsed.result ?? parsed.contents;
outer: while (true) {
if (node.children) {
for (let i = 0; i < node.children.length; i++) {
const child = node.children[i];
if (
child.position.start.offset < selectionStart &&
selectionStart < child.position.end.offset
) {
if (child.type === 'text') break outer; // don't dive into `text` nodes
node = child;
continue outer;
}
}
}
break;
}
setSelectedNode(node);
};
const textarea = textareaRef.current!;
textarea.addEventListener('keyup', getCursorNode);
textarea.addEventListener('mouseup', getCursorNode);
return () => {
textarea.removeEventListener('keyup', getCursorNode);
textarea.removeEventListener('mouseup', getCursorNode);
};
}, [parsed]);
useEffect(() => {
if (onParse) {
const messages = parsed ? parsed.messages : [];
const ast = parsed ? parsed.result ?? parsed.contents : null;
onParse(parseError, { messages, ast });
}
}, [onParse, parsed, parseError]);
useImperativeHandle(
ref,
() => ({ textarea: textareaRef.current, replaceNode }),
[replaceNode]
);
const textarea = textareaRef.current;
const previewRef = useRef<HTMLDivElement>(null);
const editorToolbarRef = useRef<HTMLDivElement>(null);
const [hasUnacceptedItems, setHasUnacceptedItems] = React.useState(false);
const [currentHeight, setCurrentHeight] = useState(height);
const [editorFooterHeight, setEditorFooterHeight] = useState(0);
const [editorToolbarHeight, setEditorToolbarHeight] = useState(0);
const classes = classNames(
'euiMarkdownEditor',
{ 'euiMarkdownEditor--fullHeight': height === 'full' },
{
'euiMarkdownEditor--isPreviewing': isPreviewing,
},
className
);
const onResize = () => {
if (textarea && isEditing && height !== 'full') {
const resizedTextareaHeight =
textarea.offsetHeight + editorFooterHeight;
setCurrentHeight(resizedTextareaHeight);
}
};
useEffect(() => {
setEditorToolbarHeight(editorToolbarRef.current!.offsetHeight);
}, [setEditorToolbarHeight]);
useEffect(() => {
if (isPreviewing && autoExpandPreview && height !== 'full') {
if (previewRef.current!.scrollHeight > currentHeight) {
// scrollHeight does not include the border or margin
// so we ask for the computed value for those,
// which is always in pixels because getComputedValue
// returns the resolved values
const elementComputedStyle = window.getComputedStyle(
previewRef.current!
);
const borderWidth =
parseFloat(elementComputedStyle.borderTopWidth) +
parseFloat(elementComputedStyle.borderBottomWidth);
const marginWidth =
parseFloat(elementComputedStyle.marginTop) +
parseFloat(elementComputedStyle.marginBottom);
// then add an extra pixel for safety and because the scrollHeight value is rounded
const extraHeight = borderWidth + marginWidth + 1;
setCurrentHeight(previewRef.current!.scrollHeight + extraHeight);
}
}
}, [currentHeight, isPreviewing, height, autoExpandPreview]);
const previewHeight =
height === 'full'
? `calc(100% - ${editorFooterHeight}px)`
: currentHeight;
const textAreaHeight =
height === 'full' ? '100%' : `calc(${height - editorFooterHeight}px)`;
const textAreaMaxHeight =
height !== 'full' ? `${maxHeight - editorFooterHeight}px` : '';
// safari needs this calc when the height is set to full
const editorToggleContainerHeight = `calc(100% - ${editorToolbarHeight}px)`;
return (
<EuiMarkdownContext.Provider value={contextValue}>
<div className={classes} {...rest}>
<EuiMarkdownEditorToolbar
ref={editorToolbarRef}
selectedNode={selectedNode}
markdownActions={markdownActions}
onClickPreview={() =>
setViewMode(isPreviewing ? MODE_EDITING : MODE_VIEWING)
}
viewMode={viewMode}
uiPlugins={toolbarPlugins}
/>
{isPreviewing && (
<div
ref={previewRef}
className="euiMarkdownEditorPreview"
style={{ height: previewHeight }}>
<EuiMarkdownFormat
parsingPluginList={parsingPluginList}
processingPluginList={processingPluginList}>
{value}
</EuiMarkdownFormat>
</div>
)}
{/* Toggle the editor's display instead of unmounting to retain its undo/redo history */}
<div
className="euiMarkdownEditor__toggleContainer"
style={{
height: editorToggleContainerHeight,
}}>
<EuiMarkdownEditorDropZone
setEditorFooterHeight={setEditorFooterHeight}
isEditing={isEditing}
dropHandlers={dropHandlers}
insertText={(
text: string,
config: EuiMarkdownStringTagConfig
) => {
if (config.block) {
text = padWithNewlinesIfNeeded(textareaRef.current!, text);
}
const originalSelectionStart = textareaRef.current!
.selectionStart;
const newSelectionPoint = originalSelectionStart + text.length;
insertText(textareaRef.current!, {
text,
selectionStart: newSelectionPoint,
selectionEnd: newSelectionPoint,
});
}}
uiPlugins={toolbarPlugins}
errors={errors}
hasUnacceptedItems={hasUnacceptedItems}
setHasUnacceptedItems={setHasUnacceptedItems}>
<EuiResizeObserver onResize={onResize}>
{(resizeRef) => {
return (
<EuiMarkdownEditorTextArea
height={textAreaHeight}
maxHeight={textAreaMaxHeight}
ref={mergeRefs(textareaRef, resizeRef)}
id={editorId}
onChange={(e) => onChange(e.target.value)}
value={value}
onFocus={() => setHasUnacceptedItems(false)}
{...{
'aria-label': ariaLabel,
'aria-labelledby': ariaLabelledBy,
'aria-describedby': ariaDescribedBy,
}}
/>
);
}}
</EuiResizeObserver>
</EuiMarkdownEditorDropZone>
{pluginEditorPlugin && (
<EuiOverlayMask>
<EuiModal onClose={() => setPluginEditorPlugin(undefined)}>
{createElement(pluginEditorPlugin.editor!, {
node:
selectedNode &&
selectedNode.type === pluginEditorPlugin.name
? selectedNode
: null,
onCancel: () => setPluginEditorPlugin(undefined),
onSave: (markdown, config) => {
if (
selectedNode &&
selectedNode.type === pluginEditorPlugin.name
) {
// modifying an existing node
textareaRef.current!.setSelectionRange(
selectedNode.position.start.offset,
selectedNode.position.end.offset
);
} else {
// creating a new node
if (config.block) {
// inject newlines if needed
markdown = padWithNewlinesIfNeeded(
textareaRef.current!,
markdown
);
}
}
insertText(textareaRef.current!, {
text: markdown,
selectionStart: undefined,
selectionEnd: undefined,
});
setPluginEditorPlugin(undefined);
},
})}
</EuiModal>
</EuiOverlayMask>
)}
</div>
</div>
</EuiMarkdownContext.Provider>
);
}
);
EuiMarkdownEditor.displayName = 'EuiMarkdownEditor';