forked from ant-design/md-editor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstore.ts
613 lines (582 loc) · 18.4 KB
/
store.ts
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
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
/* eslint-disable no-param-reassign */
import { action, makeAutoObservable } from 'mobx';
import React, { createContext, useContext } from 'react';
import { Subject } from 'rxjs';
import {
BaseSelection,
createEditor,
Editor,
Element,
Node,
NodeEntry,
Path,
Range,
Selection,
Transforms,
} from 'slate';
import { withHistory } from 'slate-history';
import { ReactEditor, withReact } from 'slate-react';
import { parse } from 'querystring';
import { CommentDataType, MarkdownEditorProps } from '..';
import { Elements, ListNode, MediaNode, TableCellNode } from '../el';
import { parserMdToSchema } from './parser/parserMdToSchema';
import { withMarkdown } from './plugins';
import { withErrorReporting } from './plugins/catchError';
import { KeyboardTask, Methods, schemaToMarkdown } from './utils';
import { getOffsetLeft, getOffsetTop } from './utils/dom';
import { EditorUtils } from './utils/editorUtils';
export const EditorStoreContext = createContext<{
store: EditorStore;
typewriter: boolean;
rootContainer?: React.MutableRefObject<HTMLDivElement | undefined>;
setShowComment: (list: CommentDataType[]) => void;
readonly: boolean;
keyTask$: Subject<{
key: Methods<KeyboardTask>;
args?: any[];
}>;
editorProps: MarkdownEditorProps;
} | null>(null);
export const useEditorStore = () => {
return (
useContext(EditorStoreContext)! || {
store: {} as Record<string, any>,
readonly: true,
typewriter: false,
editorProps: {} as MarkdownEditorProps,
}
);
};
const SUPPORT_TYPING_TAG = ['table-cell', 'code-line', 'paragraph', 'head'];
/**
* 编辑器存储类,用于管理Markdown编辑器的状态和操作。
*/
export class EditorStore {
editor = withMarkdown(withReact(withHistory(createEditor())));
manual = false;
initializing = false;
sel: BaseSelection | undefined;
selectTablePath: Path = [];
focus = false;
readonly = false;
private ableToEnter = new Set([
'paragraph',
'head',
'blockquote',
'code',
'table',
'list',
'media',
'attach',
]);
SEL_CELLS: WeakMap<Editor, NodeEntry[]> = new WeakMap();
CACHED_SEL_CELLS: WeakMap<Editor, NodeEntry[]> = new WeakMap();
draggedElement: null | HTMLElement = null;
openInsertCompletion = false;
insertCompletionText$ = new Subject<string>();
highlightCache = new Map<object, Range[]>();
refreshFloatBar = false;
mediaNode$ = new Subject<NodeEntry<MediaNode> | null>();
openInsertLink$ = new Subject<Selection>();
openLinkPanel = false;
tableCellNode: null | NodeEntry<TableCellNode> = null;
refreshHighlight = Date.now();
domRect: DOMRect | null = null;
domRange: HTMLElement | null = null;
container: null | HTMLDivElement = null;
preSelection: null | Selection = null;
inputComposition = false;
tableTask$ = new Subject<
| 'insertRowBefore'
| 'insertRowAfter'
| 'insertColBefore'
| 'insertColAfter'
| 'moveUpOneRow'
| 'moveDownOneRow'
| 'moveLeftOneCol'
| 'moveRightOneCol'
| 'removeCol'
| 'removeRow'
| 'in'
| 'insertTableCellBreak'
>();
floatBarOpen: boolean = false;
setFloatBarOpen(open: boolean) {
this.floatBarOpen = open;
}
get doc() {
return this.container?.querySelector(
'.markdown-editor-content',
) as HTMLDivElement;
}
doManual() {
this.manual = true;
setTimeout(() => (this.manual = false), 30);
}
constructor() {
this.dragStart = this.dragStart.bind(this);
withErrorReporting(this.editor);
makeAutoObservable(this, {
editor: false,
tableCellNode: false,
inputComposition: false,
container: false,
highlightCache: false,
draggedElement: false,
manual: false,
openLinkPanel: false,
initializing: false,
});
}
/**
* 查找最新的节点索引。
*
* @param node - 当前节点。
* @param index - 当前索引路径。
* @returns 最新节点的索引路径。
*/
findLatest(node: Elements, index: number[]): number[] {
if (Array.isArray((node as ListNode).children)) {
if (
(node as ListNode).children.length === 1 &&
(SUPPORT_TYPING_TAG.includes((node as ListNode).type) ||
!(node as ListNode).children[0].type)
) {
return index;
}
return this.findLatest((node as ListNode).children.at(-1)!, [
...index,
(node as ListNode).children.length - 1,
]);
}
return index;
}
/**
* 检查给定节点是否是最新节点。用于展示 闪动光标
*
* @param node - 要检查的节点。
* @returns 如果节点是最新节点,则返回 true;否则返回 false。
*/
isLatestNode(node: Node) {
try {
return this.findLatest(this.editor.children.at(-1)!, [
this.editor.children.length - 1,
])
.join('-')
.startsWith(ReactEditor.findPath(this.editor, node).join('-'));
} catch (error) {
return false;
}
}
/**
* 插入一个链接到编辑器中。
*
* @param filePath - 要插入的文件路径。如果路径以 'http' 开头,则链接文本为路径本身,否则为文件名。
*
* 该方法首先解析文件路径,并创建一个包含文本和 URL 的节点对象。
* 然后,它检查当前编辑器的选区是否存在且未折叠。如果选区不存在或已折叠,则方法返回。
*
* 接下来,它查找当前选区所在的最低层级的元素节点。如果节点类型是 'table-cell' 或 'paragraph',
* 则在当前选区插入链接节点并选中它。
*
* 如果当前选区所在的元素节点类型不是 'table-cell' 或 'paragraph',则查找包含当前选区的父级元素节点,
* 并在其后插入一个包含链接节点的新段落。
*/
insertLink(filePath: string) {
const p = parse(filePath);
const insertPath = filePath;
let node = {
text: filePath.startsWith('http') ? filePath : p.name,
url: insertPath,
};
const sel = this.editor.selection;
if (!sel || !Range.isCollapsed(sel)) return;
// @ts-ignore
const [cur] = Editor.nodes<any>(this.editor, {
match: (n) => Element.isElement(n),
mode: 'lowest',
});
if (node.text && ['table-cell', 'paragraph'].includes(cur[0].type)) {
Transforms.insertNodes(this.editor, node, { select: true });
} else {
// @ts-ignore
const [par] = Editor.nodes<any>(this.editor, {
match: (n) =>
Element.isElement(n) && ['table', 'code', 'head'].includes(n.type),
});
Transforms.insertNodes(
this.editor,
{
type: 'paragraph',
children: [node],
},
{ select: true, at: Path.next(par[1]) },
);
}
}
/**
* 插入节点到编辑器中。
*
* @param nodes - 要插入的节点,可以是单个节点或节点数组。
* @param options - 可选参数,用于指定插入节点的选项。
*/
insertNodes(nodes: Node | Node[], options?: any) {
Transforms.insertNodes(this.editor, nodes, options);
}
/**
* 计算指定 HTML 元素相对于文档顶部的偏移量。
*
* @param node - 要计算偏移量的 HTML 元素。
* @returns 元素相对于文档顶部的偏移量(以像素为单位)。
*/
offsetTop(node: HTMLElement) {
let top = 0;
const doc = this.doc;
while (doc?.contains(node.offsetParent) && doc !== node) {
top += node.offsetTop;
node = node.offsetParent as HTMLElement;
}
return top;
}
offsetLeft(node: HTMLElement) {
let left = 0;
const doc = this.doc;
while (doc.contains(node) && doc !== node) {
left += node.offsetLeft;
node = node.offsetParent as HTMLElement;
}
return left;
}
doRefreshHighlight() {
setTimeout(
action(() => {
this.refreshHighlight = Date.now();
}),
60,
);
}
setState(value: (state: EditorStore) => void) {
if (value instanceof Function) {
value(this);
} else {
for (let key of Object.keys(value)) {
// @ts-ignore
this[key] = value[key];
}
}
}
private toPath(el: HTMLElement) {
const node = ReactEditor.toSlateNode(this.editor, el);
const path = ReactEditor.findPath(this.editor, node);
return [path, node] as [Path, Node];
}
/**
*清空编辑器内容
*/
clearContent() {
Transforms.removeNodes(this.editor, {});
}
/**
* 设置编辑器内容
* @param md
*/
setMDContent(md?: string) {
if (md === undefined) return;
if (md === schemaToMarkdown(this.editor.children)) return;
const nodeList = parserMdToSchema(md).schema;
this.setContent(nodeList);
}
/**
* 设置编辑器内容,通过节点列表
* @param nodeList
*/
setContent(nodeList: Node[]) {
this.editor.children = nodeList;
this.editor.onChange();
this.editor.insertText('\n');
}
/**
* 比较两个节点并更新编辑器中的节点。
*
* @param node - 当前节点。
* @param preNode - 之前的节点。
* @param at - 节点在编辑器中的路径。
*
* 如果 `preNode` 和 `node` 的类型不同,或者节点类型为 'code' 或 'footnoteDefinition',
* 则删除当前路径和下一个路径的节点,并插入新的节点。
*
* 如果 `node` 有子节点,则递归比较和更新子节点。
*
* 如果 `node` 没有子节点但 `preNode` 有子节点,则删除当前路径的节点并插入新的节点。
*
* 如果 `node` 和 `preNode` 都没有子节点,则更新当前路径的节点,并插入文本(如果有)。
*/
diffNode = (node: Node, preNode: Node, at: number[]) => {
// 如果上个节点不存在,但是本次有,直接插入
if (node && !preNode) {
Transforms.insertNodes(this.editor, node, { at });
return;
}
if (node.type !== preNode.type) {
Transforms.removeNodes(this.editor, {
at,
});
Transforms.insertNodes(this.editor, node, { at });
return;
}
if (node.type === preNode.type) {
Transforms.setNodes(this.editor, node, { at });
if (node.text) {
Transforms.insertText(this.editor, node.text, { at });
}
}
if (node.children) {
node.children.forEach((child: any, index: any) => {
if (!this.editor.hasPath(at)) {
Transforms.insertNodes(this.editor, child, { at });
return;
}
this.diffNode(child, preNode.children[index], [...at, index]);
});
return;
}
return;
};
/**
* 更新节点列表的方法。
*
* @param nodeList - 新的节点列表。
*
* 该方法会比较新的节点列表和当前编辑器中的子节点列表,
* 并根据差异更新编辑器中的节点。
*
* 首先,它会创建一个映射来存储需要更新的节点。
* 然后,它会遍历新的节点列表,并将需要更新的节点添加到映射中。
* 接着,它会根据映射中的信息调用 `diffNode` 方法来更新节点。
* 最后,如果当前编辑器中的子节点比新的节点列表多,
* 它会移除多余的节点。
*/
updateNodeList(nodeList: Node[]) {
const childrenList = this.editor.children;
const updateMap = new Map<number, Node>();
nodeList
.filter((item: any) => {
if (item.type === 'p' && item.children.length === 0) {
return false;
}
if (item.type === 'list' && item.children.length === 0) {
return false;
}
if (item.type === 'listItem' && item.children.length === 0) {
return false;
}
return true;
})
.forEach((node, index) => {
if (JSON.stringify(node) === JSON.stringify(childrenList?.at(index))) {
return;
}
updateMap.set(index, node);
});
try {
updateMap.forEach((node, key) => {
this.diffNode(node, childrenList[key], [key]);
});
} catch (error) {
console.log('run', error);
this.editor.children = nodeList;
}
const maxSize = childrenList.length - nodeList.length;
if (maxSize > 0) {
childrenList.forEach((node, index) => {
if (nodeList.at(index)) return;
if (this.editor.hasPath([index])) {
Transforms.removeNodes(this.editor, { at: [index] });
}
});
}
}
/**
* 处理拖拽开始事件。
*
* @param e - React 拖拽事件对象。
*
* 此方法会在拖拽开始时调用,主要功能包括:
* - 阻止事件传播。
* - 初始化拖拽相关的元素和位置数据。
* - 添加拖拽过程中和拖拽结束时的事件监听器。
*
* 内部步骤:
* 1. 根据拖拽元素的数据集,确定哪些元素可以作为拖拽目标。
* 2. 遍历所有符合条件的元素,计算它们的位置信息并存储。
* 3. 在拖拽过程中,根据鼠标位置动态更新拖拽标记的位置。
* 4. 在拖拽结束时,移除事件监听器和拖拽标记,并根据拖拽目标位置更新编辑器内容。
*/
dragStart(e: React.DragEvent) {
e.stopPropagation();
console.log(e);
type MovePoint = {
el: HTMLDivElement;
direction: 'top' | 'bottom';
top: number;
left: number;
};
const ableToEnter =
this.draggedElement?.dataset?.be === 'list-item'
? new Set([
'paragraph',
'head',
'blockquote',
'code',
'table',
'list',
'list-item',
'media',
'attach',
])
: this.ableToEnter;
let mark: null | HTMLDivElement = null;
const els = document.querySelectorAll<HTMLDivElement>('[data-be]');
const points: MovePoint[] = [];
// @ts-ignore
for (let el of els) {
if (!ableToEnter.has(el.dataset.be!)) continue;
if (el.classList.contains('frontmatter')) continue;
const pre = el.previousSibling as HTMLElement;
if (
el.dataset.be === 'paragraph' &&
this.draggedElement?.dataset.be === 'list-item' &&
(!pre || pre.classList.contains('check-item'))
) {
continue;
}
if (el === this.draggedElement) continue;
const top = getOffsetTop(el, this.container!);
const left = getOffsetLeft(el, this.container!);
points.push({
el: el,
direction: 'top',
left:
el.dataset.be === 'list-item' && !el.classList.contains('task')
? left - 16
: left,
top: top - 2,
});
points.push({
el: el,
left:
el.dataset.be === 'list-item' && !el.classList.contains('task')
? left - 16
: left,
direction: 'bottom',
top: top + el.clientHeight + 2,
});
}
let last: MovePoint | null = null;
const dragover = (e: DragEvent) => {
e.preventDefault();
const top = e.clientY - 40 + this.container!.scrollTop;
let distance = 1000000;
let cur: MovePoint | null = null;
for (let p of points) {
let curDistance = Math.abs(p.top - top);
if (curDistance < distance) {
cur = p;
distance = curDistance;
}
}
if (cur) {
last = cur;
const width =
last.el.dataset.be === 'list-item'
? last.el.clientWidth + 20 + 'px'
: last.el.clientWidth + 'px';
if (!mark) {
mark = document.createElement('div');
mark.classList.add('move-mark');
mark.style.width = width;
mark.style.transform = `translate(${last.left}px, ${last.top}px)`;
this.container!.append(mark);
} else {
mark.style.width = width;
mark.style.transform = `translate(${last.left}px, ${last.top}px)`;
}
}
};
window.addEventListener('dragover', dragover);
window.addEventListener(
'dragend',
action(() => {
try {
window.removeEventListener('dragover', dragover);
this.readonly = false;
if (mark) this.container!.removeChild(mark);
if (last && this.draggedElement) {
let [dragPath, dragNode] = this.toPath(this.draggedElement);
let [targetPath] = this.toPath(last.el);
let toPath =
last.direction === 'top' ? targetPath : Path.next(targetPath);
if (!Path.equals(targetPath, dragPath)) {
const parent = Node.parent(this.editor, dragPath);
if (
Path.equals(Path.parent(targetPath), Path.parent(dragPath)) &&
Path.compare(dragPath, targetPath) === -1
) {
toPath = Path.previous(toPath);
}
let delPath = Path.parent(dragPath);
const targetNode = Node.get(this.editor, targetPath);
if (dragNode.type === 'list-item') {
if (targetNode.type !== 'list-item') {
Transforms.delete(this.editor, { at: dragPath });
Transforms.insertNodes(
this.editor,
{
...parent,
children: [EditorUtils.copy(dragNode)],
},
{ at: toPath, select: true },
);
if (parent.children?.length === 1) {
if (
EditorUtils.isNextPath(Path.parent(dragPath), targetPath)
) {
delPath = Path.next(Path.parent(dragPath));
} else {
delPath = Path.parent(dragPath);
}
}
} else {
Transforms.moveNodes(this.editor, {
at: dragPath,
to: toPath,
});
}
} else {
Transforms.moveNodes(this.editor, {
at: dragPath,
to: toPath,
});
}
if (parent.children?.length === 1) {
if (
Path.equals(Path.parent(toPath), Path.parent(delPath)) &&
Path.compare(toPath, delPath) !== 1
) {
delPath = Path.next(delPath);
}
Transforms.delete(this.editor, { at: delPath });
}
}
if (dragNode?.type !== 'media')
this.draggedElement!.draggable = false;
}
this.draggedElement = null;
} catch (error) {
console.error(error);
}
}),
{ once: true },
);
}
}