forked from siyuan-note/siyuan
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
1888 lines (1833 loc) · 107 KB
/
index.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
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {paste} from "../util/paste";
import {
hasClosestBlock,
hasClosestByAttribute,
hasClosestByClassName,
hasClosestByMatchTag,
hasTopClosestByClassName,
} from "../util/hasClosest";
import {
focusBlock,
focusByRange,
focusByWbr,
focusSideBlock,
getEditorRange,
getSelectionOffset,
} from "../util/selection";
import {Constants} from "../../constants";
import {getSearch, isMobile} from "../../util/functions";
import {isLocalPath, pathPosix} from "../../util/pathName";
import {genEmptyElement} from "../../block/util";
import {previewImage} from "../preview/image";
import {contentMenu, imgMenu, linkMenu, refMenu, setFold, zoomOut} from "../../menus/protyle";
import * as dayjs from "dayjs";
import {dropEvent} from "../util/editorCommonEvent";
import {input} from "./input";
import {
getContenteditableElement,
getLastBlock, getNextBlock,
getPreviousHeading,
getTopAloneElement,
hasNextSibling, hasPreviousSibling,
isNotEditBlock
} from "./getBlock";
import {transaction, updateTransaction} from "./transaction";
import {hideElements} from "../ui/hideElements";
/// #if !BROWSER
import {shell} from "electron";
import {getCurrentWindow} from "@electron/remote";
/// #endif
import {removeEmbed} from "./removeEmbed";
import {keydown} from "./keydown";
import {openMobileFileById} from "../../mobile/editor";
import {removeBlock} from "./remove";
import {highlightRender} from "../markdown/highlightRender";
import {openAttr} from "../../menus/commonMenuItem";
import {blockRender} from "../markdown/blockRender";
/// #if !MOBILE
import {getAllModels} from "../../layout/getAll";
import {pushBack} from "../../util/backForward";
import {openAsset, openBy, openFileById} from "../../editor/util";
import {openGlobalSearch} from "../../search/util";
/// #endif
import {BlockPanel} from "../../block/Panel";
import {isCtrl, openByMobile} from "../util/compatibility";
import {MenuItem} from "../../menus/Menu";
import {fetchPost} from "../../util/fetch";
import {onGet} from "../util/onGet";
import {setTableAlign} from "../util/table";
import {countBlockWord, countSelectWord} from "../../layout/status";
import {showMessage} from "../../dialog/message";
export class WYSIWYG {
public lastHTMLs: { [key: string]: string } = {};
public element: HTMLDivElement;
public preventKeyup: boolean;
constructor(protyle: IProtyle) {
this.element = document.createElement("div");
this.element.className = "protyle-wysiwyg";
this.element.setAttribute("spellcheck", "false");
if (navigator && navigator.maxTouchPoints > 1 && navigator.platform === "MacIntel") {
// iPhone,iPad 端输入 contenteditable 为 true 时会在块中间插入 span
this.element.setAttribute("contenteditable", "false");
} else {
this.element.setAttribute("contenteditable", "true");
}
if (window.siyuan.config.editor.displayBookmarkIcon) {
this.element.classList.add("protyle-wysiwyg--attr");
}
this.bindCommonEvent(protyle);
if (protyle.options.action.includes(Constants.CB_GET_HISTORY)) {
return;
}
this.bindEvent(protyle);
keydown(protyle, this.element);
dropEvent(protyle, this.element);
}
public renderCustom(ial: IObject) {
const ialKeys = Object.keys(ial);
for (let i = 0; i < this.element.attributes.length; i++) {
const oldKey = this.element.attributes[i].nodeName;
if (!["type", "class", "spellcheck", "contenteditable", "data-doc-type", "style", "scroll"].includes(oldKey) &&
!ialKeys.includes(oldKey)) {
this.element.removeAttribute(oldKey);
i--;
}
}
ialKeys.forEach((key: string) => {
if (!["title-img", "title", "updated", "icon", "id", "type", "class", "spellcheck", "contenteditable", "data-doc-type", "style"].includes(key)) {
this.element.setAttribute(key, ial[key]);
}
});
}
private escapeInline(protyle: IProtyle, range: Range, event: InputEvent) {
if (!event.data) {
return;
}
const inputData = event.data;
protyle.toolbar.range = range;
const inlineElement = range.startContainer.parentElement;
let outElement = inlineElement;
if (!["DIV", "TD", "TH"].includes(inlineElement.tagName) && !["DIV", "TD", "TH"].includes(inlineElement.parentElement.tagName) && !hasNextSibling(inlineElement)) {
// 表格行内公式之前无法插入文字 https://github.com/siyuan-note/siyuan/issues/3908
// 引用外面加粗体且引用后无文字 https://github.com/siyuan-note/siyuan/issues/3103
outElement = inlineElement.parentElement;
}
if (// 表格行内公式之前无法插入文字 https://github.com/siyuan-note/siyuan/issues/3908
!["DIV", "TD", "TH"].includes(inlineElement.tagName) &&
range.toString() === "" && range.startContainer.nodeType === 3 && protyle.toolbar.getCurrentType().length > 0 &&
inlineElement.textContent.replace(Constants.ZWSP, "").length >= inputData.length && // 为空的时候需要等于
!protyle.toolbar.isNewEmptyInline) {
const position = getSelectionOffset(inlineElement, protyle.wysiwyg.element, range);
let dataLength = inputData.length;
if (inputData === "<" || inputData === ">") {
// 使用 inlineElement.innerHTML 会出现 https://ld246.com/article/1627185027423 中的第2个问题
dataLength = 4;
}
// ctrl+k 会产生 ZWSP,需要移除
const html = inlineElement.innerHTML.replace(Constants.ZWSP, "");
if (position.start === inlineElement.textContent.length) {
// 使用 inlineElement.textContent **$a$b** 中数学公式消失
inlineElement.innerHTML = html.substr(0, html.length - dataLength);
const textNode = document.createTextNode(inputData);
outElement.after(textNode);
range.selectNodeContents(textNode);
range.collapse(false);
} else if (position.start === inputData.length) {
inlineElement.innerHTML = html.substr(dataLength);
const textNode = document.createTextNode(inputData);
outElement.before(textNode);
range.selectNodeContents(textNode);
range.collapse(false);
}
}
}
private setEmptyOutline(protyle: IProtyle, element: HTMLElement) {
// 图片移除选择状态应放在前面,否则 https://github.com/siyuan-note/siyuan/issues/4173
const selectImgElement = protyle.wysiwyg.element.querySelector(".img--select");
if (selectImgElement) {
selectImgElement.classList.remove("img--select");
}
let nodeElement = element;
if (!element.getAttribute("data-node-id")) {
const tempElement = hasClosestBlock(element);
if (!tempElement) {
return;
}
nodeElement = tempElement;
}
/// #if !MOBILE
if (protyle.model) {
getAllModels().outline.forEach(item => {
if (item.blockId === protyle.block.rootID) {
if (nodeElement.getAttribute("data-type") === "NodeHeading") {
item.setCurrent(nodeElement.getAttribute("data-node-id"));
return;
}
const headingElement = getPreviousHeading(nodeElement);
if (headingElement) {
item.setCurrent(headingElement.getAttribute("data-node-id"));
return;
}
item.setCurrent("");
}
});
}
/// #endif
}
private bindCommonEvent(protyle: IProtyle) {
this.element.addEventListener("copy", (event: ClipboardEvent & { target: HTMLElement }) => {
// https://github.com/siyuan-note/siyuan/issues/4600
if (event.target.tagName === "PROTYLE-HTML") {
event.stopPropagation();
return;
}
event.stopPropagation();
event.preventDefault();
const range = getEditorRange(protyle.wysiwyg.element);
const nodeElement = hasClosestBlock(range.startContainer);
if (!nodeElement) {
return;
}
const selectImgElement = nodeElement.querySelector(".img--select");
let selectElements = Array.from(protyle.wysiwyg.element.querySelectorAll(".protyle-wysiwyg--select"));
if (selectElements.length === 0 && range.toString() === "" && !range.cloneContents().querySelector("img") &&
!selectImgElement) {
nodeElement.classList.add("protyle-wysiwyg--select");
countBlockWord([nodeElement.getAttribute("data-node-id")]);
selectElements = [nodeElement];
}
let html = "";
let textPlain = "";
if (selectElements.length > 0) {
if (selectElements[0].getAttribute("data-type") === "NodeListItem" && selectElements[0].parentElement.childElementCount - 1 === selectElements.length) {
html = selectElements[0].parentElement.outerHTML;
} else {
selectElements.forEach(item => {
const topElement = getTopAloneElement(item);
html += removeEmbed(topElement);
});
}
} else {
const tempElement = document.createElement("div");
// https://github.com/siyuan-note/siyuan/issues/5540
const selectTypes = protyle.toolbar.getCurrentType(range);
if ((selectTypes.length > 0 || range.startContainer.parentElement.parentElement.getAttribute("data-type") === "NodeHeading") &&
(
(range.startContainer.nodeType === 3 && range.startContainer.parentElement.textContent === range.toString()) ||
(range.startContainer.nodeType !== 3 && range.startContainer.textContent === range.toString())
)) {
if (range.startContainer.parentElement.parentElement.getAttribute("data-type") === "NodeHeading") {
// 复制标题 https://github.com/siyuan-note/insider/issues/297
tempElement.append(range.startContainer.parentElement.parentElement.cloneNode(true));
} else if (!["DIV", "TD", "TH"].includes(range.startContainer.parentElement.tagName)) {
// 复制行内元素 https://github.com/siyuan-note/insider/issues/191
tempElement.append(range.startContainer.parentElement.cloneNode(true));
} else {
// 直接复制块 https://github.com/siyuan-note/insider/issues/318
tempElement.append(range.cloneContents());
}
html = tempElement.innerHTML;
} else if (selectImgElement) {
html = selectImgElement.outerHTML;
} else {
tempElement.append(range.cloneContents());
const inlineMathElement = hasClosestByAttribute(range.commonAncestorContainer, "data-type", "inline-math");
if (inlineMathElement) {
// 表格内复制数学公式 https://ld246.com/article/1631708573504
html = inlineMathElement.outerHTML;
} else {
html = tempElement.innerHTML;
}
// 不能使用 commonAncestorContainer https://ld246.com/article/1643282894693
if (hasClosestByAttribute(range.startContainer, "data-type", "NodeCodeBlock") ||
hasClosestByMatchTag(range.startContainer, "CODE")) {
textPlain = tempElement.textContent.replace(Constants.ZWSP, "");
}
}
}
event.clipboardData.setData("text/plain", textPlain || protyle.lute.BlockDOM2StdMd(html).trimEnd());
event.clipboardData.setData("text/html", html + Constants.ZWSP);
});
this.element.addEventListener("mousedown", (event: MouseEvent) => {
if (event.button === 2 || window.siyuan.ctrlIsPressed) {
// 右键
return;
}
if (!window.siyuan.shiftIsPressed) {
// https://github.com/siyuan-note/siyuan/issues/3026
hideElements(["select"], protyle);
}
const target = event.target as HTMLElement;
if (hasClosestByClassName(target, "protyle-action")) {
return;
}
const documentSelf = document;
const rect = protyle.element.getBoundingClientRect();
const mostLeft = rect.left + parseInt(protyle.wysiwyg.element.style.paddingLeft) + 1;
const mostRight = mostLeft + protyle.wysiwyg.element.firstElementChild.clientWidth - 1;
const mostBottom = rect.bottom;
const y = event.clientY;
// 图片、iframe、video 缩放
if (!protyle.disabled && target.classList.contains("protyle-action__drag")) {
const nodeElement = hasClosestBlock(target);
if (!nodeElement) {
return;
}
let isCenter = true;
if (["NodeIFrame", "NodeWidget", "NodeVideo"].includes(nodeElement.getAttribute("data-type"))) {
nodeElement.classList.add("iframe--drag");
if (nodeElement.style.textAlign === "left" || nodeElement.style.textAlign === "right") {
isCenter = false;
}
} else if (target.parentElement.parentElement.getAttribute("data-type") === "img") {
target.parentElement.parentElement.classList.add("img--drag");
}
const id = nodeElement.getAttribute("data-node-id");
const html = nodeElement.outerHTML;
const x = event.clientX;
const dragElement = target.previousElementSibling as HTMLElement;
const dragWidth = dragElement.clientWidth;
const dragHeight = dragElement.clientHeight;
documentSelf.onmousemove = (moveEvent: MouseEvent) => {
if (dragElement.tagName === "IMG") {
dragElement.parentElement.parentElement.style.width = "";
}
if (moveEvent.clientX > x - dragWidth + 8 && moveEvent.clientX < mostRight) {
if ((dragElement.tagName === "IMG" && dragElement.parentElement.parentElement.style.display !== "block") || !isCenter) {
dragElement.style.width = Math.max(17, dragWidth + (moveEvent.clientX - x)) + "px";
} else {
dragElement.style.width = Math.max(17, dragWidth + (moveEvent.clientX - x) * 2) + "px";
}
}
if (dragElement.tagName !== "IMG") {
if (moveEvent.clientY > y - dragHeight + 8 && moveEvent.clientY < mostBottom) {
dragElement.style.height = (dragHeight + (moveEvent.clientY - y)) + "px";
}
} else {
dragElement.parentElement.parentElement.style.maxWidth = (parseInt(dragElement.style.width) + 10) + "px";
}
};
documentSelf.onmouseup = () => {
documentSelf.onmousemove = null;
documentSelf.onmouseup = null;
documentSelf.ondragstart = null;
documentSelf.onselectstart = null;
documentSelf.onselect = null;
if (target.classList.contains("protyle-action__drag") && nodeElement) {
updateTransaction(protyle, id, nodeElement.outerHTML, html);
}
nodeElement.classList.remove("iframe--drag");
target.parentElement.parentElement.classList.remove("img--drag");
};
return;
}
// table cell select
let tableBlockElement: HTMLElement | false;
if (target.tagName === "TH" || target.tagName === "TD" || target.firstElementChild?.tagName === "TABLE" || target.classList.contains("table__resize") || target.classList.contains("table__select")) {
tableBlockElement = hasClosestBlock(target);
if (tableBlockElement) {
tableBlockElement.querySelector("table").classList.remove("select");
tableBlockElement.querySelector(".table__select").removeAttribute("style");
window.siyuan.menus.menu.remove();
event.stopPropagation();
}
// 后续拖拽操作写在多选节点中
}
// table col resize
if (!protyle.disabled && target.classList.contains("table__resize")) {
const nodeElement = hasClosestBlock(target);
if (!nodeElement) {
return;
}
const html = nodeElement.outerHTML;
// https://github.com/siyuan-note/siyuan/issues/4455
if (getSelection().rangeCount > 0) {
getSelection().getRangeAt(0).collapse(false);
}
// @ts-ignore
nodeElement.firstElementChild.style.webkitUserModify = "read-only";
nodeElement.style.cursor = "col-resize";
target.removeAttribute("style");
const id = nodeElement.getAttribute("data-node-id");
const x = event.clientX;
const colElement = nodeElement.querySelectorAll("table col")[parseInt(target.getAttribute("data-col-index"))] as HTMLElement;
// 兼容 1.8.2
(nodeElement.querySelectorAll("table th")[parseInt(target.getAttribute("data-col-index"))] as HTMLElement).style.width = "";
const oldWidth = colElement.clientWidth;
const hasScroll = nodeElement.firstElementChild.clientWidth < nodeElement.firstElementChild.scrollWidth;
documentSelf.onmousemove = (moveEvent: MouseEvent) => {
if (nodeElement.style.textAlign === "center" && !hasScroll) {
colElement.style.width = (oldWidth + (moveEvent.clientX - x) * 2) + "px";
} else {
colElement.style.width = (oldWidth + (moveEvent.clientX - x)) + "px";
}
};
documentSelf.onmouseup = () => {
// @ts-ignore
nodeElement.firstElementChild.style.webkitUserModify = "";
nodeElement.style.cursor = "";
documentSelf.onmousemove = null;
documentSelf.onmouseup = null;
documentSelf.ondragstart = null;
documentSelf.onselectstart = null;
documentSelf.onselect = null;
if (nodeElement) {
updateTransaction(protyle, id, nodeElement.outerHTML, html);
}
};
return;
}
// 多选节点
let x = event.clientX;
if (event.clientX > mostRight) {
x = mostRight;
} else if (event.clientX < mostLeft) {
x = mostLeft;
}
const mostTop = rect.top + (protyle.options.render.breadcrumb ? protyle.breadcrumb.element.parentElement.clientHeight : 0);
let mouseElement: Element;
let moveCellElement: HTMLElement;
documentSelf.onmousemove = (moveEvent: MouseEvent) => {
const moveTarget = moveEvent.target as HTMLElement;
// table cell select
if (!protyle.disabled && tableBlockElement && tableBlockElement.contains(moveTarget) && !hasClosestByClassName(tableBlockElement, "protyle-wysiwyg__embed")) {
if ((moveTarget.tagName === "TH" || moveTarget.tagName === "TD") && !moveTarget.isSameNode(target) && (!moveCellElement || !moveCellElement.isSameNode(moveTarget))) {
// @ts-ignore
tableBlockElement.firstElementChild.style.webkitUserModify = "read-only";
let width = target.offsetLeft + target.clientWidth - moveTarget.offsetLeft;
let left = moveTarget.offsetLeft;
if (target.offsetLeft === moveTarget.offsetLeft) {
width = Math.max(target.clientWidth, moveTarget.clientWidth);
} else if (target.offsetLeft < moveTarget.offsetLeft) {
width = moveTarget.offsetLeft + moveTarget.clientWidth - target.offsetLeft;
left = target.offsetLeft;
}
let height = target.offsetTop + target.clientHeight - moveTarget.offsetTop;
let top = moveTarget.offsetTop;
if (target.offsetTop === moveTarget.offsetTop) {
height = Math.max(target.clientHeight, moveTarget.clientHeight);
} else if (target.offsetTop < moveTarget.offsetTop) {
height = moveTarget.offsetTop + moveTarget.clientHeight - target.offsetTop;
top = target.offsetTop;
}
// https://github.com/siyuan-note/insider/issues/1015
Array.from(tableBlockElement.querySelectorAll("th, td")).find((item: HTMLElement) => {
const updateWidth = item.offsetLeft < left + width && item.offsetLeft + item.clientWidth > left + width;
const updateWidth2 = item.offsetLeft < left && item.offsetLeft + item.clientWidth > left;
if (item.offsetTop < top && item.offsetTop + item.clientHeight > top) {
if ((item.offsetLeft + 6 > left && item.offsetLeft + item.clientWidth - 6 < left + width) || updateWidth || updateWidth2) {
height = top + height - item.offsetTop;
top = item.offsetTop;
}
if (updateWidth) {
width = item.offsetLeft + item.clientWidth - left;
}
if (updateWidth2) {
width = left + width - item.offsetLeft;
left = item.offsetLeft;
}
} else if (item.offsetTop < top + height && item.offsetTop + item.clientHeight > top + height) {
if ((item.offsetLeft + 6 > left && item.offsetLeft + item.clientWidth - 6 < left + width) || updateWidth || updateWidth2) {
height = item.clientHeight + item.offsetTop - top;
}
if (updateWidth) {
width = item.offsetLeft + item.clientWidth - left;
}
if (updateWidth2) {
width = left + width - item.offsetLeft;
left = item.offsetLeft;
}
} else if (updateWidth2 && item.offsetTop + 6 > top && item.offsetTop + item.clientHeight - 6 < top + height) {
width = left + width - item.offsetLeft;
left = item.offsetLeft;
} else if (updateWidth && item.offsetTop + 6 > top && item.offsetTop + item.clientHeight - 6 < top + height) {
width = item.offsetLeft + item.clientWidth - left;
}
});
tableBlockElement.querySelector("table").classList.add("select");
tableBlockElement.querySelector(".table__select").setAttribute("style", `left:${left - tableBlockElement.firstElementChild.scrollLeft}px;top:${top}px;height:${height}px;width:${width + 1}px;`);
moveCellElement = moveTarget;
}
return;
}
protyle.selectElement.classList.remove("fn__none");
// 向左选择,遇到 gutter 就不会弹出 toolbar
hideElements(["gutter"], protyle);
let newTop = 0;
let newLeft = 0;
let newWidth = 0;
let newHeight = 0;
if (moveEvent.clientX < x) {
if (moveEvent.clientX < mostLeft) {
// 向左越界
newLeft = mostLeft;
} else {
// 向左
newLeft = moveEvent.clientX;
}
newWidth = x - newLeft;
} else {
if (moveEvent.clientX > mostRight) {
// 向右越界
newLeft = x;
newWidth = mostRight - newLeft;
} else {
// 向右
newLeft = x;
newWidth = moveEvent.clientX - x;
}
}
if (moveEvent.clientY > y) {
if (moveEvent.clientY > mostBottom) {
// 向下越界
newTop = y;
newHeight = mostBottom - y;
} else {
// 向下
newTop = y;
newHeight = moveEvent.clientY - y;
}
} else {
if (moveEvent.clientY < mostTop) {
// 向上越界
newTop = mostTop;
} else {
// 向上
newTop = moveEvent.clientY;
}
newHeight = y - newTop;
}
protyle.selectElement.setAttribute("style", `background-color: ${protyle.selectElement.style.backgroundColor};top:${newTop}px;height:${newHeight}px;left:${newLeft + 2}px;width:${newWidth - 2}px;`);
const newMouseElement = document.elementFromPoint(moveEvent.clientX, moveEvent.clientY);
if (mouseElement && mouseElement.isSameNode(newMouseElement) && !mouseElement.classList.contains("protyle-wysiwyg") &&
!mouseElement.classList.contains("list") && !mouseElement.classList.contains("bq") && !mouseElement.classList.contains("sb")) {
// 性能优化,同一个p元素不进行选中计算
return;
} else {
mouseElement = newMouseElement;
}
hideElements(["select"], protyle);
let firstElement = document.elementFromPoint(newLeft - 1, newTop);
if (!firstElement) {
return;
}
if (firstElement.classList.contains("protyle-wysiwyg") || firstElement.classList.contains("list") || firstElement.classList.contains("sb") || firstElement.classList.contains("bq")) {
firstElement = document.elementFromPoint(newLeft - 1, newTop + 16);
}
if (!firstElement || firstElement.classList.contains("protyle-wysiwyg")) {
return;
}
const firstBlockElement = hasClosestBlock(firstElement);
if (!firstBlockElement) {
return;
}
let selectElements: Element[] = [];
let currentElement: Element | boolean = firstBlockElement;
let hasJump = false;
while (currentElement) {
if (currentElement && !currentElement.classList.contains("protyle-attr")) {
const currentRect = currentElement.getBoundingClientRect();
if (currentRect.height > 0 && currentRect.top < newTop + newHeight && currentRect.left < newLeft + newWidth) {
if (hasJump) {
// 父节点的下个节点在选中范围内才可使用父节点作为选中节点
if (currentElement.nextElementSibling && !currentElement.nextElementSibling.classList.contains("protyle-attr")) {
const nextRect = currentElement.nextElementSibling.getBoundingClientRect();
if (nextRect.top < newTop + newHeight && nextRect.left < newLeft + newWidth) {
selectElements = [currentElement];
currentElement = currentElement.nextElementSibling;
hasJump = false;
} else if (currentElement.parentElement.classList.contains("sb")) {
currentElement = hasClosestBlock(currentElement.parentElement);
hasJump = true;
} else {
break;
}
} else {
currentElement = hasClosestBlock(currentElement.parentElement);
hasJump = true;
}
} else {
selectElements.push(currentElement);
currentElement = currentElement.nextElementSibling;
}
} else if (currentElement.parentElement.classList.contains("sb")) {
// 跳出超级块横向排版中的未选中元素
currentElement = hasClosestBlock(currentElement.parentElement);
hasJump = true;
} else if (currentRect.height === 0 && currentRect.width === 0 && currentElement.parentElement.getAttribute("fold") === "1") {
currentElement = currentElement.parentElement;
selectElements = [];
} else {
break;
}
} else {
currentElement = hasClosestBlock(currentElement.parentElement);
hasJump = true;
}
}
if (selectElements.length === 1 && !selectElements[0].classList.contains("list") && !selectElements[0].classList.contains("bq") && !selectElements[0].classList.contains("sb")) {
// 只有一个 p 时不选中
protyle.selectElement.style.backgroundColor = "transparent";
} else {
selectElements.forEach(item => {
if (!hasClosestByClassName(item, "protyle-wysiwyg__embed")) {
item.classList.add("protyle-wysiwyg--select");
}
});
protyle.selectElement.style.backgroundColor = "";
}
};
documentSelf.onmouseup = (mouseUpEvent) => {
documentSelf.onmousemove = null;
documentSelf.onmouseup = null;
documentSelf.ondragstart = null;
documentSelf.onselectstart = null;
documentSelf.onselect = null;
protyle.selectElement.classList.add("fn__none");
protyle.selectElement.removeAttribute("style");
if (!protyle.disabled && tableBlockElement) {
// @ts-ignore
tableBlockElement.firstElementChild.style.webkitUserModify = "";
const tableSelectElement = tableBlockElement.querySelector(".table__select") as HTMLElement;
if (tableSelectElement.getAttribute("style")) {
if (getSelection().rangeCount > 0) {
getSelection().getRangeAt(0).collapse(false);
}
window.siyuan.menus.menu.remove();
window.siyuan.menus.menu.append(new MenuItem({
label: window.siyuan.languages.mergeCell,
click: () => {
if (tableBlockElement) {
const selectCellElements: HTMLTableCellElement[] = [];
const colIndexList: number[] = [];
const colCount = tableBlockElement.querySelectorAll("th").length;
let fnNoneMax = 0;
const scrollLeft = tableBlockElement.firstElementChild.scrollLeft;
let isTHead = false;
let isTBody = false;
tableBlockElement.querySelectorAll("th, td").forEach((item: HTMLTableCellElement, index: number) => {
if (item.classList.contains("fn__none")) {
// 合并的元素中间有 fn__none 的元素
if (item.previousElementSibling && item.previousElementSibling.isSameNode(selectCellElements[selectCellElements.length - 1])) {
selectCellElements.push(item);
if (!isTHead && item.parentElement.parentElement.tagName === "THEAD") {
isTHead = true;
} else if (!isTBody && item.parentElement.parentElement.tagName === "TBODY") {
isTBody = true;
}
} else {
if (index < fnNoneMax && colIndexList.includes((index + 1) % colCount)) {
selectCellElements.push(item);
if (!isTHead && item.parentElement.parentElement.tagName === "THEAD") {
isTHead = true;
} else if (!isTBody && item.parentElement.parentElement.tagName === "TBODY") {
isTBody = true;
}
}
}
} else {
if (item.offsetLeft + 6 > tableSelectElement.offsetLeft + scrollLeft && item.offsetLeft + item.clientWidth - 6 < tableSelectElement.offsetLeft + scrollLeft + tableSelectElement.clientWidth &&
item.offsetTop + 6 > tableSelectElement.offsetTop && item.offsetTop + item.clientHeight - 6 < tableSelectElement.offsetTop + tableSelectElement.clientHeight) {
selectCellElements.push(item);
if (!isTHead && item.parentElement.parentElement.tagName === "THEAD") {
isTHead = true;
} else if (!isTBody && item.parentElement.parentElement.tagName === "TBODY") {
isTBody = true;
}
colIndexList.push((index + 1) % colCount);
// https://github.com/siyuan-note/insider/issues/1014
fnNoneMax = Math.max((item.rowSpan - 1) * colCount + index + 1, fnNoneMax);
}
}
});
tableBlockElement.querySelector("table").classList.remove("select");
tableSelectElement.removeAttribute("style");
const oldHTML = tableBlockElement.outerHTML;
let cellElement = selectCellElements[0];
let colSpan = cellElement.colSpan;
let index = 1;
while (cellElement.nextElementSibling && cellElement.nextElementSibling.isSameNode(selectCellElements[index])) {
cellElement = cellElement.nextElementSibling as HTMLTableCellElement;
if (!cellElement.classList.contains("fn__none")) { // https://github.com/siyuan-note/insider/issues/1007#issuecomment-1046195608
colSpan += cellElement.colSpan;
}
index++;
}
let html = "";
let rowElement: Element = selectCellElements[0].parentElement;
let rowSpan = selectCellElements[0].rowSpan;
selectCellElements.forEach((item, index) => {
let cellHTML = item.innerHTML.trim();
if (cellHTML.endsWith("<br>")) {
cellHTML = cellHTML.substr(0, cellHTML.length - 4);
}
html += cellHTML + ((!cellHTML || index === selectCellElements.length - 1) ? "" : "<br>");
if (index !== 0) {
if (!rowElement.isSameNode(item.parentElement)) {
if (!item.classList.contains("fn__none")) { // https://github.com/siyuan-note/insider/issues/1011
rowSpan += item.rowSpan;
}
rowElement = item.parentElement;
if (selectCellElements[0].parentElement.parentElement.tagName === "THEAD" && item.parentElement.parentElement.tagName !== "THEAD") {
selectCellElements[0].parentElement.parentElement.insertAdjacentElement("beforeend", item.parentElement);
}
}
item.classList.add("fn__none");
item.innerHTML = "";
}
});
// https://github.com/siyuan-note/insider/issues/1017
if (isTHead && isTBody) {
rowElement = rowElement.parentElement.nextElementSibling.firstElementChild;
while (rowElement && rowElement.parentElement.tagName !== "THEAD") {
let colSpanCount = 0;
let noneCount = 0;
Array.from(rowElement.children).forEach((item: HTMLTableCellElement) => {
colSpanCount += item.colSpan - 1;
if (item.classList.contains("fn__none")) {
noneCount++;
}
});
if (colSpanCount !== noneCount) {
selectCellElements[0].parentElement.parentElement.insertAdjacentElement("beforeend", rowElement);
rowElement = rowElement.parentElement.nextElementSibling.firstElementChild;
} else {
break;
}
}
}
// 合并背景色不会修改,需要等计算完毕
setTimeout(() => {
if (tableBlockElement) {
selectCellElements[0].innerHTML = html;
selectCellElements[0].colSpan = colSpan;
selectCellElements[0].rowSpan = rowSpan;
updateTransaction(protyle, tableBlockElement.getAttribute("data-node-id"), tableBlockElement.outerHTML, oldHTML);
}
});
}
}
}).element);
window.siyuan.menus.menu.append(new MenuItem({type: "separator"}).element);
window.siyuan.menus.menu.append(new MenuItem({
icon: "iconAlignLeft",
accelerator: window.siyuan.config.keymap.editor.general.alignLeft.custom,
label: window.siyuan.languages.alignLeft,
click: () => {
if (tableBlockElement) {
const selectCellElements: HTMLTableCellElement[] = [];
const scrollLeft = tableBlockElement.firstElementChild.scrollLeft;
tableBlockElement.querySelectorAll("th, td").forEach((item: HTMLTableCellElement) => {
if (!item.classList.contains("fn__none") &&
item.offsetLeft + 6 > tableSelectElement.offsetLeft + scrollLeft && item.offsetLeft + item.clientWidth - 6 < tableSelectElement.offsetLeft + scrollLeft + tableSelectElement.clientWidth &&
item.offsetTop + 6 > tableSelectElement.offsetTop && item.offsetTop + item.clientHeight - 6 < tableSelectElement.offsetTop + tableSelectElement.clientHeight &&
(selectCellElements.length === 0 || (selectCellElements.length > 0 && item.offsetTop === selectCellElements[0].offsetTop))) {
selectCellElements.push(item);
}
});
tableBlockElement.querySelector("table").classList.remove("select");
tableSelectElement.removeAttribute("style");
setTableAlign(protyle, selectCellElements, tableBlockElement, "left", getEditorRange(tableBlockElement));
}
}
}).element);
window.siyuan.menus.menu.append(new MenuItem({
icon: "iconAlignCenter",
accelerator: window.siyuan.config.keymap.editor.general.alignCenter.custom,
label: window.siyuan.languages.alignCenter,
click: () => {
if (tableBlockElement) {
const selectCellElements: HTMLTableCellElement[] = [];
const scrollLeft = tableBlockElement.firstElementChild.scrollLeft;
tableBlockElement.querySelectorAll("th, td").forEach((item: HTMLTableCellElement) => {
if (!item.classList.contains("fn__none") &&
item.offsetLeft + 6 > tableSelectElement.offsetLeft + scrollLeft && item.offsetLeft + item.clientWidth - 6 < tableSelectElement.offsetLeft + scrollLeft + tableSelectElement.clientWidth &&
item.offsetTop + 6 > tableSelectElement.offsetTop && item.offsetTop + item.clientHeight - 6 < tableSelectElement.offsetTop + tableSelectElement.clientHeight &&
(selectCellElements.length === 0 || (selectCellElements.length > 0 && item.offsetTop === selectCellElements[0].offsetTop))) {
selectCellElements.push(item);
}
});
tableBlockElement.querySelector("table").classList.remove("select");
tableSelectElement.removeAttribute("style");
setTableAlign(protyle, selectCellElements, tableBlockElement, "center", getEditorRange(tableBlockElement));
}
}
}).element);
window.siyuan.menus.menu.append(new MenuItem({
icon: "iconAlignRight",
accelerator: window.siyuan.config.keymap.editor.general.alignRight.custom,
label: window.siyuan.languages.alignRight,
click: () => {
if (tableBlockElement) {
const selectCellElements: HTMLTableCellElement[] = [];
const scrollLeft = tableBlockElement.firstElementChild.scrollLeft;
tableBlockElement.querySelectorAll("th, td").forEach((item: HTMLTableCellElement) => {
if (!item.classList.contains("fn__none") &&
item.offsetLeft + 6 > tableSelectElement.offsetLeft + scrollLeft && item.offsetLeft + item.clientWidth - 6 < tableSelectElement.offsetLeft + scrollLeft + tableSelectElement.clientWidth &&
item.offsetTop + 6 > tableSelectElement.offsetTop && item.offsetTop + item.clientHeight - 6 < tableSelectElement.offsetTop + tableSelectElement.clientHeight &&
(selectCellElements.length === 0 || (selectCellElements.length > 0 && item.offsetTop === selectCellElements[0].offsetTop))) {
selectCellElements.push(item);
}
});
tableBlockElement.querySelector("table").classList.remove("select");
tableSelectElement.removeAttribute("style");
setTableAlign(protyle, selectCellElements, tableBlockElement, "right", getEditorRange(tableBlockElement));
}
}
}).element);
window.siyuan.menus.menu.append(new MenuItem({type: "separator"}).element);
window.siyuan.menus.menu.append(new MenuItem({
label: window.siyuan.languages.remove,
icon: "iconTrashcan",
click() {
if (tableBlockElement) {
const selectCellElements: HTMLTableCellElement[] = [];
const scrollLeft = tableBlockElement.firstElementChild.scrollLeft;
tableBlockElement.querySelectorAll("th, td").forEach((item: HTMLTableCellElement) => {
if (!item.classList.contains("fn__none") &&
item.offsetLeft + 6 > tableSelectElement.offsetLeft + scrollLeft && item.offsetLeft + item.clientWidth - 6 < tableSelectElement.offsetLeft + scrollLeft + tableSelectElement.clientWidth &&
item.offsetTop + 6 > tableSelectElement.offsetTop && item.offsetTop + item.clientHeight - 6 < tableSelectElement.offsetTop + tableSelectElement.clientHeight) {
selectCellElements.push(item);
}
});
tableBlockElement.querySelector("table").classList.remove("select");
tableSelectElement.removeAttribute("style");
const oldHTML = tableBlockElement.outerHTML;
selectCellElements.forEach(item => {
item.innerHTML = "";
});
updateTransaction(protyle, tableBlockElement.getAttribute("data-node-id"), tableBlockElement.outerHTML, oldHTML);
}
}
}).element);
window.siyuan.menus.menu.popup({x: mouseUpEvent.clientX - 8, y: mouseUpEvent.clientY - 16});
}
}
const ids: string[] = [];
const selectElement = protyle.wysiwyg.element.querySelectorAll(".protyle-wysiwyg--select");
selectElement.forEach(item => {
ids.push(item.getAttribute("data-node-id"));
});
countBlockWord(ids);
// 划选后不能存在跨块的 range https://github.com/siyuan-note/siyuan/issues/4473
if (getSelection().rangeCount > 0) {
const range = getSelection().getRangeAt(0);
if (range.toString() === "" ||
window.siyuan.shiftIsPressed // https://ld246.com/article/1650096678723
) {
return;
}
if (selectElement.length > 0) {
range.collapse(true);
return;
}
const startBlockElement = hasClosestBlock(range.startContainer);
let endBlockElement: false | HTMLElement;
if (mouseUpEvent.detail === 3 && range.endContainer.nodeType !== 3 && (range.endContainer as HTMLElement).tagName === "DIV" && range.endOffset === 0) {
// 三击选中段落块时,rangeEnd 会在下一个块
if ((range.endContainer as HTMLElement).classList.contains("protyle-attr")) {
// 三击在悬浮层中会选择到 attr https://github.com/siyuan-note/siyuan/issues/4636
range.setEndAfter(range.endContainer.previousSibling.lastChild);
}
} else {
endBlockElement = hasClosestBlock(range.endContainer);
}
if (startBlockElement && endBlockElement && !endBlockElement.isSameNode(startBlockElement)) {
range.collapse(true);
}
}
};
});
}
private bindEvent(protyle: IProtyle) {
this.element.addEventListener("focusout", () => {
if (getSelection().rangeCount > 0 && !this.element.contains(getSelection().getRangeAt(0).startContainer)) {
// 对 ctrl+tab 切换后 range 已经在新页面中才会触发的 focusout 进行忽略,因为在切换之前已经 dispatchEvent 了。
if (!protyle.toolbar.range) {
protyle.toolbar.range = this.element.ownerDocument.createRange();
protyle.toolbar.range.setStart(getContenteditableElement(this.element) || this.element, 0);
protyle.toolbar.range.collapse(true);
}
} else {
protyle.toolbar.range = getEditorRange(this.element);
}
});
this.element.addEventListener("cut", (event: ClipboardEvent & { target: HTMLElement }) => {
if (event.target.tagName === "PROTYLE-HTML") {
event.stopPropagation();
return;
}
event.stopPropagation();
event.preventDefault();
if (protyle.options.render.breadcrumb) {
protyle.breadcrumb.hide();
}
const range = getEditorRange(protyle.wysiwyg.element);
let nodeElement = hasClosestBlock(range.startContainer);
if (!nodeElement) {
return;
}
const selectImgElement = nodeElement.querySelector(".img--select");
let selectElements = Array.from(protyle.wysiwyg.element.querySelectorAll(".protyle-wysiwyg--select"));
if (selectElements.length === 0 && range.toString() === "" && !range.cloneContents().querySelector("img") &&
!selectImgElement) {
nodeElement.classList.add("protyle-wysiwyg--select");
selectElements = [nodeElement];
}
let html = "";
if (selectElements.length > 0) {
if (selectElements[0].getAttribute("data-type") === "NodeListItem" && selectElements[0].parentElement.childElementCount - 1 === selectElements.length) {
html = selectElements[0].parentElement.outerHTML;
} else {
selectElements.forEach(item => {
const topElement = getTopAloneElement(item);
if (item.getAttribute("data-type") === "NodeHeading" && item.getAttribute("fold") === "1") {
html += removeEmbed(topElement).replace('fold="1"', "");
} else {
html += removeEmbed(topElement);
}
});
if (selectElements[0].getAttribute("data-type") === "NodeListItem") {
html = `<div data-subtype="${selectElements[0].getAttribute("data-subtype")}" data-node-id="${Lute.NewNodeID()}" data-type="NodeList" class="list">${html}<div class="protyle-attr" contenteditable="false">${Constants.ZWSP}</div></div>`;
}
}
const nextElement = getNextBlock(selectElements[selectElements.length - 1]);
removeBlock(protyle, nodeElement, range);
if (nextElement) {
// Ctrl+X 剪切后光标应跳到下一行行首 https://github.com/siyuan-note/siyuan/issues/5485
focusBlock(nextElement);
}
} else {
const id = nodeElement.getAttribute("data-node-id");
const oldHTML = nodeElement.outerHTML;
const tempElement = document.createElement("div");
// 首次选中标题时,range.startContainer 会为空
let startContainer = range.startContainer;
if (startContainer.nodeType === 3 && startContainer.textContent === "") {
const nextSibling = hasNextSibling(range.startContainer);
if (nextSibling) {
startContainer = nextSibling;
}
}
// 选中整个标题 https://github.com/siyuan-note/siyuan/issues/4329
const headElement = hasClosestByAttribute(startContainer, "data-type", "NodeHeading");
let isFoldHeading = false;
if (headElement && range.toString() === headElement.firstElementChild.textContent) {
const doOperations: IOperation[] = [{
action: "delete",
id: headElement.getAttribute("data-node-id")
}];
const undoOperations: IOperation[] = [{
action: "insert",
id: headElement.getAttribute("data-node-id"),
data: headElement.outerHTML,
previousID: headElement.previousElementSibling?.getAttribute("data-node-id"),
parentID: headElement.parentElement?.getAttribute("data-node-id") || protyle.block.parentID
}];
if (headElement.getAttribute("fold") === "1") {
isFoldHeading = true;
const headCloneElement = headElement.cloneNode(true) as HTMLElement;
headCloneElement.removeAttribute("fold");
tempElement.append(headCloneElement);
undoOperations[0].data = headCloneElement.outerHTML;
setFold(protyle, headElement, undefined, true);
} else {
if ((headElement.parentElement.childElementCount === 3 && headElement.parentElement.classList.contains("li")) ||
(headElement.parentElement.childElementCount === 2 && (headElement.parentElement.classList.contains("bq") || headElement.parentElement.classList.contains("sb"))) ||
(headElement.parentElement.childElementCount === 1 && headElement.parentElement.classList.contains("protyle-wysiwyg")) // 全选剪切标题
) {
// https://github.com/siyuan-note/siyuan/issues/4040
const emptyId = Lute.NewNodeID();
const emptyElement = genEmptyElement(false, false, emptyId);
doOperations.push({
id: emptyId,
data: emptyElement.outerHTML,
action: "insert",
parentID: headElement.parentElement.getAttribute("data-node-id") || protyle.block.parentID
});
undoOperations.push({
id: emptyId,
action: "delete",
});
headElement.before(emptyElement);
}
focusSideBlock(headElement);
tempElement.append(headElement);
}
transaction(protyle, doOperations, undoOperations);
} else if (range.toString() !== "" && startContainer.isSameNode(range.endContainer) && range.startContainer.nodeType === 3
&& range.endOffset === range.endContainer.textContent.length && range.startOffset === 0 &&
!["DIV", "TD", "TH"].includes(range.startContainer.parentElement.tagName)) {
// 选中整个内联元素
tempElement.append(range.startContainer.parentElement);
} else if (selectImgElement) {
tempElement.append(selectImgElement);
} else {
if (range.cloneContents().querySelectorAll("td, th").length > 0) {
// 表格内多格子 cut https://github.com/siyuan-note/insider/issues/564
const wbrElement = document.createElement("wbr");
range.insertNode(wbrElement);
range.setStartAfter(wbrElement);
tempElement.append(range.extractContents());
nodeElement.outerHTML = protyle.lute.SpinBlockDOM(nodeElement.outerHTML);
nodeElement = protyle.wysiwyg.element.querySelector(`[data-node-id="${id}"]`) as HTMLElement;
focusByWbr(nodeElement, range);
} else {
const inlineMathElement = hasClosestByAttribute(range.commonAncestorContainer, "data-type", "inline-math");
if (inlineMathElement) {
// 表格内剪切数学公式 https://ld246.com/article/1631708573504
tempElement.append(inlineMathElement);
} else {