vditor 4.0.2-alpha.6 → 4.0.2-alpha.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (96) hide show
  1. package/README.md +69 -5
  2. package/dist/index.css +35 -29
  3. package/dist/index.d.ts +1 -0
  4. package/dist/index.js +6485 -5445
  5. package/dist/index.min.js +1 -1
  6. package/dist/index.mjs +17599 -0
  7. package/dist/js/graphviz/LICENSE.expat +21 -0
  8. package/dist/js/graphviz/LICENSE.graphviz +277 -0
  9. package/dist/js/graphviz/LICENSE.viz +21 -0
  10. package/dist/js/graphviz/README.md +10 -0
  11. package/dist/js/graphviz/viz.js +6 -330
  12. package/dist/js/lute/lute.min.js +21 -19
  13. package/dist/method.d.ts +2 -2
  14. package/dist/method.js +2017 -1903
  15. package/dist/method.min.js +1 -1
  16. package/dist/method.mjs +3243 -0
  17. package/dist/ts/constants.d.ts +2 -0
  18. package/dist/ts/ir/index.d.ts +1 -0
  19. package/dist/ts/markdown/mathRender.d.ts +24 -1
  20. package/dist/ts/markdown/outlineRender.d.ts +2 -1
  21. package/dist/ts/markdown/plantumlRender.d.ts +1 -1
  22. package/dist/ts/outline/index.d.ts +2 -0
  23. package/dist/ts/sv/index.d.ts +1 -0
  24. package/dist/ts/tip/index.d.ts +6 -1
  25. package/dist/ts/undo/index.d.ts +1 -0
  26. package/dist/ts/upload/linkToImg.d.ts +1 -0
  27. package/dist/ts/util/addScript.d.ts +1 -2
  28. package/dist/ts/util/compatibility.d.ts +1 -1
  29. package/dist/ts/util/expandHTMLTags.d.ts +1 -0
  30. package/dist/ts/util/imageDrag.d.ts +1 -0
  31. package/dist/ts/util/notifyConfigChange.d.ts +1 -0
  32. package/dist/ts/util/pairedSymbols.d.ts +5 -0
  33. package/dist/ts/util/pasteIntoTable.d.ts +6 -0
  34. package/dist/ts/util/pasteLink.d.ts +1 -0
  35. package/dist/ts/util/processCode.d.ts +1 -0
  36. package/dist/ts/util/tableWheel.d.ts +1 -0
  37. package/dist/ts/util/taskNavigation.d.ts +1 -0
  38. package/dist/ts/wysiwyg/index.d.ts +1 -0
  39. package/dist/types/index.d.ts +56 -1
  40. package/package.json +3 -2
  41. package/src/assets/less/_hint.less +6 -0
  42. package/src/assets/less/_reset.less +29 -0
  43. package/src/assets/less/_tooltipped.less +2 -2
  44. package/src/assets/less/_wysiwyg.less +4 -0
  45. package/src/index.ts +28 -6
  46. package/src/ts/constants.ts +4 -0
  47. package/src/ts/ir/expandMarker.ts +3 -0
  48. package/src/ts/ir/index.ts +11 -1
  49. package/src/ts/ir/process.ts +3 -0
  50. package/src/ts/markdown/chartRender.ts +28 -2
  51. package/src/ts/markdown/graphvizRender.ts +51 -39
  52. package/src/ts/markdown/highlightRender.ts +6 -2
  53. package/src/ts/markdown/mathRender.ts +26 -38
  54. package/src/ts/markdown/mediaRender.ts +1 -1
  55. package/src/ts/markdown/mermaidRender.ts +4 -3
  56. package/src/ts/markdown/outlineRender.ts +44 -15
  57. package/src/ts/markdown/plantumlRender.ts +24 -5
  58. package/src/ts/markdown/previewRender.ts +5 -1
  59. package/src/ts/markdown/setLute.ts +1 -0
  60. package/src/ts/outline/index.ts +72 -0
  61. package/src/ts/preview/index.ts +1 -1
  62. package/src/ts/sv/index.ts +1 -0
  63. package/src/ts/sv/process.ts +3 -0
  64. package/src/ts/tip/index.ts +25 -9
  65. package/src/ts/toolbar/CodeTheme.ts +2 -0
  66. package/src/ts/toolbar/ContentTheme.ts +2 -0
  67. package/src/ts/toolbar/EditMode.ts +4 -0
  68. package/src/ts/toolbar/Headings.ts +4 -6
  69. package/src/ts/toolbar/Outline.ts +2 -0
  70. package/src/ts/toolbar/Record.ts +5 -0
  71. package/src/ts/ui/initUI.ts +9 -1
  72. package/src/ts/ui/setPreviewMode.ts +2 -0
  73. package/src/ts/undo/index.ts +14 -4
  74. package/src/ts/upload/index.ts +1 -1
  75. package/src/ts/upload/linkToImg.ts +91 -0
  76. package/src/ts/util/Options.ts +2 -0
  77. package/src/ts/util/addScript.ts +15 -24
  78. package/src/ts/util/compatibility.ts +2 -2
  79. package/src/ts/util/editorCommonEvent.ts +47 -4
  80. package/src/ts/util/expandHTMLTags.ts +36 -0
  81. package/src/ts/util/fixBrowserBehavior.ts +29 -61
  82. package/src/ts/util/imageDrag.ts +108 -0
  83. package/src/ts/util/notifyConfigChange.ts +16 -0
  84. package/src/ts/util/pairedSymbols.ts +109 -0
  85. package/src/ts/util/pasteIntoTable.ts +136 -0
  86. package/src/ts/util/pasteLink.ts +51 -0
  87. package/src/ts/util/processCode.ts +33 -8
  88. package/src/ts/util/selection.ts +11 -2
  89. package/src/ts/util/tableWheel.ts +31 -0
  90. package/src/ts/util/taskNavigation.ts +113 -0
  91. package/src/ts/util/toc.ts +9 -3
  92. package/src/ts/wysiwyg/afterRenderEvent.ts +3 -0
  93. package/src/ts/wysiwyg/highlightToolbarWYSIWYG.ts +5 -4
  94. package/src/ts/wysiwyg/index.ts +17 -6
  95. package/src/ts/wysiwyg/setHeading.ts +4 -0
  96. package/dist/js/graphviz/full.render.js +0 -90
@@ -3,11 +3,12 @@ import {input as IRInput} from "../ir/input";
3
3
  import {processAfterRender} from "../ir/process";
4
4
  import {processAfterRender as processSVAfterRender, processPaste} from "../sv/process";
5
5
  import {uploadFiles} from "../upload/index";
6
- import {setHeaders} from "../upload/setHeaders";
6
+ import {uploadLinkToImg} from "../upload/linkToImg";
7
7
  import {afterRenderEvent} from "../wysiwyg/afterRenderEvent";
8
8
  import {input} from "../wysiwyg/input";
9
9
  import {isCtrl, isFirefox} from "./compatibility";
10
10
  import {scrollCenter} from "./editorCommonEvent";
11
+ import {parseMarkdownTableRows, pasteIntoTable} from "./pasteIntoTable";
11
12
  import {
12
13
  getTopList,
13
14
  hasClosestBlock,
@@ -18,7 +19,8 @@ import {
18
19
  import {getLastNode} from "./hasClosest";
19
20
  import {highlightToolbar} from "./highlightToolbar";
20
21
  import {matchHotKey} from "./hotKey";
21
- import {processCodeRender, processPasteCode} from "./processCode";
22
+ import {isPlainTextPaste, processCodeRender, processPasteCode} from "./processCode";
23
+ import {getPastedLink} from "./pasteLink";
22
24
  import {
23
25
  getEditorRange,
24
26
  getSelectPosition,
@@ -1476,6 +1478,7 @@ export const paste = async (vditor: IVditor, event: (ClipboardEvent | DragEvent)
1476
1478
  }
1477
1479
  }
1478
1480
  const renderers: {
1481
+ HTML2Md?: ILuteRender,
1479
1482
  HTML2VditorDOM?: ILuteRender,
1480
1483
  HTML2VditorIRDOM?: ILuteRender,
1481
1484
  Md2VditorDOM?: ILuteRender,
@@ -1498,62 +1501,15 @@ export const paste = async (vditor: IVditor, event: (ClipboardEvent | DragEvent)
1498
1501
 
1499
1502
  const src = node.TokensStr();
1500
1503
  if (node.__internal_object__.Parent.Type === 34 && src && src.indexOf("file://") === -1 &&
1501
- vditor.options.upload.linkToImgUrl) {
1502
- const xhr = new XMLHttpRequest();
1503
- xhr.open("POST", vditor.options.upload.linkToImgUrl);
1504
- if (vditor.options.upload.token) {
1505
- xhr.setRequestHeader("X-Upload-Token", vditor.options.upload.token);
1506
- }
1507
- if (vditor.options.upload.withCredentials) {
1508
- xhr.withCredentials = true;
1509
- }
1510
- setHeaders(vditor, xhr);
1511
- xhr.setRequestHeader("Content-Type", "application/json; charset=utf-8");
1512
- xhr.onreadystatechange = () => {
1513
- if (xhr.readyState === XMLHttpRequest.DONE) {
1514
- if (xhr.status === 200) {
1515
- let responseText = xhr.responseText;
1516
- if (vditor.options.upload.linkToImgFormat) {
1517
- responseText = vditor.options.upload.linkToImgFormat(xhr.responseText);
1518
- }
1519
- const responseJSON = JSON.parse(responseText);
1520
- if (responseJSON.code !== 0) {
1521
- vditor.tip.show(responseJSON.msg);
1522
- return;
1523
- }
1524
- const original = responseJSON.data.originalURL;
1525
- if (vditor.currentMode === "sv") {
1526
- const selectionStart = vditor.sv.element.selectionStart;
1527
- const selectionEnd = vditor.sv.element.selectionEnd;
1528
- vditor.sv.element.value = vditor.sv.element.value.split(original)
1529
- .join(responseJSON.data.url);
1530
- vditor.sv.element.setSelectionRange(selectionStart, selectionEnd);
1531
- } else {
1532
- const imgElement: HTMLImageElement =
1533
- vditor[vditor.currentMode].element.querySelector(`img[src="${original}"]`);
1534
- imgElement.src = responseJSON.data.url;
1535
- if (vditor.currentMode === "ir") {
1536
- imgElement.previousElementSibling.previousElementSibling.innerHTML =
1537
- responseJSON.data.url;
1538
- }
1539
- }
1540
- execAfterRender(vditor);
1541
- } else {
1542
- vditor.tip.show(xhr.responseText);
1543
- }
1544
- if (vditor.options.upload.linkToImgCallback) {
1545
- vditor.options.upload.linkToImgCallback(xhr.responseText);
1546
- }
1547
- }
1548
- };
1549
- xhr.send(JSON.stringify({url: src}));
1504
+ (vditor.options.upload.linkToImgUrl || vditor.options.upload.linkToImgHandler)) {
1505
+ uploadLinkToImg(vditor, src, () => execAfterRender(vditor));
1550
1506
  }
1551
1507
  if (vditor.currentMode === "ir") {
1552
- return [`<span class="vditor-ir__marker vditor-ir__marker--link">${Lute.EscapeHTMLStr(src)}</span>`, Lute.WalkContinue];
1508
+ return [`<span class="vditor-ir__marker vditor-ir__marker--link">${Lute.EscapeHTMLStr(src.replace(/ /g, "%20"))}</span>`, Lute.WalkContinue];
1553
1509
  } else if (vditor.currentMode === "wysiwyg") {
1554
1510
  return ["", Lute.WalkContinue];
1555
1511
  } else {
1556
- return ["", Lute.WalkContinue];
1512
+ return [src, Lute.WalkContinue];
1557
1513
  }
1558
1514
  };
1559
1515
 
@@ -1571,6 +1527,10 @@ export const paste = async (vditor: IVditor, event: (ClipboardEvent | DragEvent)
1571
1527
  textHTML = doc.body.innerHTML;
1572
1528
  }
1573
1529
  textHTML = Lute.Sanitize(textHTML);
1530
+ const transfer = "clipboardData" in event ? event.clipboardData : event.dataTransfer;
1531
+ if (textPlain && isPlainTextPaste(textHTML, transfer.getData("vscode-editor-data"))) {
1532
+ textHTML = "";
1533
+ }
1574
1534
  vditor.wysiwyg.getComments(vditor);
1575
1535
 
1576
1536
  // process code
@@ -1582,7 +1542,7 @@ export const paste = async (vditor: IVditor, event: (ClipboardEvent | DragEvent)
1582
1542
  const cellElement = vditor.currentMode === "wysiwyg" &&
1583
1543
  (hasClosestByMatchTag(getEditorRange(vditor).startContainer, "TD") ||
1584
1544
  hasClosestByMatchTag(getEditorRange(vditor).startContainer, "TH"));
1585
- if (cellElement && /[\r\n]/.test(textPlain)) {
1545
+ if (cellElement && !textHTML && /[\r\n]/.test(textPlain) && !parseMarkdownTableRows(textPlain)) {
1586
1546
  // 表格单元格内的换行使用 br 表示,避免自旋时解析为新的表格行
1587
1547
  insertHTML(Lute.EscapeHTMLStr(textPlain).replace(/\r\n|\r|\n/g, "<br>"), vditor);
1588
1548
  } else if (codeElement) {
@@ -1622,7 +1582,9 @@ export const paste = async (vditor: IVditor, event: (ClipboardEvent | DragEvent)
1622
1582
  tempElement.querySelectorAll(".vditor-copy").forEach((e) => {
1623
1583
  e.remove();
1624
1584
  });
1625
- if (vditor.currentMode === "ir") {
1585
+ if (pasteIntoTable(vditor, tempElement.innerHTML)) {
1586
+ // 单元格填充与普通粘贴共用后续规范化和撤销记录。
1587
+ } else if (vditor.currentMode === "ir") {
1626
1588
  renderers.HTML2VditorIRDOM = {renderLinkDest};
1627
1589
  vditor.lute.SetJSRenderers({renderers});
1628
1590
  insertHTML(vditor.lute.HTML2VditorIRDOM(tempElement.innerHTML), vditor);
@@ -1631,6 +1593,8 @@ export const paste = async (vditor: IVditor, event: (ClipboardEvent | DragEvent)
1631
1593
  vditor.lute.SetJSRenderers({renderers});
1632
1594
  insertHTML(vditor.lute.HTML2VditorDOM(tempElement.innerHTML), vditor);
1633
1595
  } else {
1596
+ renderers.HTML2Md = {renderLinkDest};
1597
+ vditor.lute.SetJSRenderers({renderers});
1634
1598
  processPaste(vditor, vditor.lute.HTML2Md(tempElement.innerHTML).trimRight());
1635
1599
  }
1636
1600
  vditor.outline.render(vditor);
@@ -1666,12 +1630,10 @@ export const paste = async (vditor: IVditor, event: (ClipboardEvent | DragEvent)
1666
1630
  }
1667
1631
  }
1668
1632
  } else if (textPlain.trim() !== "" && files.length === 0) {
1669
- const selectedText = vditor.currentMode === "sv" ? vditor.sv.element.value.substring(
1670
- vditor.sv.element.selectionStart, vditor.sv.element.selectionEnd) : getEditorRange(vditor).toString();
1671
- if (selectedText !== "" && vditor.lute.IsValidLinkDest(textPlain)) {
1672
- textPlain = `[${selectedText}](${textPlain})`;
1673
- }
1674
- if (vditor.currentMode === "ir") {
1633
+ textPlain = getPastedLink(vditor, textPlain);
1634
+ if (pasteIntoTable(vditor, "", textPlain)) {
1635
+ // 单元格填充与普通粘贴共用后续规范化和撤销记录。
1636
+ } else if (vditor.currentMode === "ir") {
1675
1637
  renderers.Md2VditorIRDOM = {renderLinkDest};
1676
1638
  vditor.lute.SetJSRenderers({renderers});
1677
1639
  insertHTML(Lute.Sanitize(vditor.lute.Md2VditorIRDOM(textPlain)), vditor);
@@ -1680,6 +1642,12 @@ export const paste = async (vditor: IVditor, event: (ClipboardEvent | DragEvent)
1680
1642
  vditor.lute.SetJSRenderers({renderers});
1681
1643
  insertHTML(Lute.Sanitize(vditor.lute.Md2VditorDOM(textPlain)), vditor);
1682
1644
  } else {
1645
+ if (vditor.options.upload.linkToImgUrl || vditor.options.upload.linkToImgHandler ||
1646
+ vditor.options.upload.renderLinkDest) {
1647
+ renderers.Md2VditorDOM = {renderLinkDest};
1648
+ vditor.lute.SetJSRenderers({renderers});
1649
+ vditor.lute.Md2VditorDOM(textPlain);
1650
+ }
1683
1651
  processPaste(vditor, textPlain);
1684
1652
  }
1685
1653
  vditor.outline.render(vditor);
@@ -0,0 +1,108 @@
1
+ import {execAfterRender} from "./fixBrowserBehavior";
2
+ import {setSelectionFocus} from "./selection";
3
+
4
+ const getImageNode = (image: HTMLImageElement, mode: string): HTMLElement => {
5
+ if (mode === "ir") {
6
+ const node = image.closest<HTMLElement>("[data-type='img']");
7
+ if (!node) {
8
+ return undefined;
9
+ }
10
+ const link = node.parentElement;
11
+ if (link.getAttribute("data-type") === "a" && Array.from(link.childNodes).every(child =>
12
+ child === node || (child.nodeType === Node.TEXT_NODE && !child.textContent.trim()) ||
13
+ (child instanceof HTMLElement && child.classList.contains("vditor-ir__marker")))) {
14
+ return link;
15
+ }
16
+ return node;
17
+ }
18
+ const link = image.parentElement;
19
+ return link.tagName === "A" && link.childNodes.length === 1 ? link : image;
20
+ };
21
+
22
+ export const bindImageDrag = (vditor: IVditor, editor: HTMLElement) => {
23
+ let dragged: HTMLElement;
24
+ const editable = () => vditor.currentMode !== "sv" && vditor[vditor.currentMode].element === editor &&
25
+ editor.getAttribute("contenteditable") === "true";
26
+ const copy = (event: DragEvent) => event.ctrlKey || event.altKey || event.metaKey;
27
+
28
+ editor.addEventListener("dragstart", (event: DragEvent) => {
29
+ dragged = undefined;
30
+ if (!(event.target instanceof HTMLImageElement)) {
31
+ return;
32
+ }
33
+ if (!editable() || event.target.closest("[contenteditable='false'], .vditor-ir__preview, .vditor-wysiwyg__preview")) {
34
+ event.preventDefault();
35
+ return;
36
+ }
37
+ dragged = getImageNode(event.target, vditor.currentMode);
38
+ if (dragged) {
39
+ event.dataTransfer.effectAllowed = "copyMove";
40
+ } else {
41
+ event.preventDefault();
42
+ }
43
+ });
44
+ editor.addEventListener("dragend", () => { dragged = undefined; });
45
+ editor.addEventListener("dragover", (event: DragEvent) => {
46
+ if (dragged && editable()) {
47
+ event.preventDefault();
48
+ event.dataTransfer.dropEffect = copy(event) ? "copy" : "move";
49
+ }
50
+ });
51
+
52
+ return (event: DragEvent) => {
53
+ if (!dragged) {
54
+ return false;
55
+ }
56
+ const source = dragged;
57
+ dragged = undefined;
58
+ event.preventDefault();
59
+ if (!editable() || !editor.contains(source)) {
60
+ return true;
61
+ }
62
+ // 浏览器命中位置只用于定位,图片和 Markdown 标记作为同一个节点移动。
63
+ const doc = editor.ownerDocument as Document & {
64
+ caretPositionFromPoint?: (x: number, y: number) => {offsetNode: Node, offset: number} | null;
65
+ };
66
+ let range: Range;
67
+ if (doc.caretRangeFromPoint) {
68
+ range = doc.caretRangeFromPoint(event.clientX, event.clientY);
69
+ } else {
70
+ const position = doc.caretPositionFromPoint?.(event.clientX, event.clientY);
71
+ if (position) {
72
+ range = doc.createRange();
73
+ range.setStart(position.offsetNode, position.offset);
74
+ range.collapse(true);
75
+ }
76
+ }
77
+ if (!range || !editor.contains(range.startContainer) || source.contains(range.startContainer)) {
78
+ return true;
79
+ }
80
+ const target = range.startContainer instanceof Element ? range.startContainer : range.startContainer.parentElement;
81
+ if (target.closest("[contenteditable='false'], .vditor-ir__marker, .vditor-ir__preview, " +
82
+ ".vditor-wysiwyg__block, .vditor-wysiwyg__preview, code, [data-type='code-block'], [data-type='img'], " +
83
+ "[data-type='math-inline'], [data-type='math-block'], [data-type='html-inline'], [data-type='html-block'], " +
84
+ "[data-type='link-ref-defs-block']")) {
85
+ return true;
86
+ }
87
+
88
+ const sourceRange = doc.createRange();
89
+ sourceRange.selectNode(source);
90
+ setSelectionFocus(sourceRange);
91
+ vditor.undo.addToUndoStack(vditor);
92
+ const node = copy(event) ? source.cloneNode(true) : source;
93
+ if (range.startContainer === editor) {
94
+ const paragraph = doc.createElement("p");
95
+ paragraph.setAttribute("data-block", "0");
96
+ range.insertNode(paragraph);
97
+ range.selectNodeContents(paragraph);
98
+ }
99
+ range.insertNode(node);
100
+ range.setStartAfter(node);
101
+ range.collapse(true);
102
+ setSelectionFocus(range);
103
+ // 即使撤销延迟未到,也为一次拖拽保留完整的前后状态。
104
+ execAfterRender(vditor);
105
+ vditor.undo.addToUndoStack(vditor);
106
+ return true;
107
+ };
108
+ };
@@ -0,0 +1,16 @@
1
+ export const notifyConfigChange = (vditor: IVditor) => {
2
+ vditor.options.configChange?.({
3
+ mode: vditor.currentMode,
4
+ theme: vditor.options.theme,
5
+ preview: {
6
+ mode: vditor.options.preview.mode,
7
+ theme: {current: vditor.options.preview.theme.current},
8
+ hljs: {style: vditor.options.preview.hljs.style},
9
+ },
10
+ outline: {
11
+ enable: vditor.options.outline.enable,
12
+ position: vditor.options.outline.position,
13
+ ...(vditor.options.outline.width === undefined ? {} : {width: vditor.options.outline.width}),
14
+ },
15
+ });
16
+ };
@@ -0,0 +1,109 @@
1
+ import {input as irInput} from "../ir/input";
2
+ import {processAfterRender} from "../sv/process";
3
+ import {input} from "../wysiwyg/input";
4
+ import {getEditorRange, setSelectionFocus} from "./selection";
5
+
6
+ export const pairedSymbols: {[key: string]: string} = {
7
+ "\"": "\"", "'": "'", "`": "`", "(": ")", "[": "]", "{": "}",
8
+ "“": "”", "‘": "’", "(": ")", "【": "】", "「": "」", "『": "』", "《": "》",
9
+ };
10
+
11
+ export const wrapSelection = (vditor: IVditor, opening: string): boolean => {
12
+ if (!opening || opening.length !== 1) {
13
+ return false;
14
+ }
15
+ const closing = pairedSymbols[opening];
16
+ if (!closing) {
17
+ return false;
18
+ }
19
+ const editor = vditor[vditor.currentMode].element;
20
+ if (vditor.currentMode === "sv") {
21
+ const textarea = vditor.sv.element;
22
+ if (textarea.disabled || textarea.selectionStart === textarea.selectionEnd) {
23
+ return false;
24
+ }
25
+ const start = textarea.selectionStart;
26
+ const end = textarea.selectionEnd;
27
+ textarea.setRangeText(opening + textarea.value.substring(start, end) + closing, start, end, "end");
28
+ processAfterRender(vditor);
29
+ return true;
30
+ }
31
+ const range = getEditorRange(vditor);
32
+ if (editor.getAttribute("contenteditable") !== "true" || range.toString() === "" ||
33
+ !editor.contains(range.startContainer) || !editor.contains(range.endContainer)) {
34
+ return false;
35
+ }
36
+ const contents = range.extractContents();
37
+ const fragment = document.createDocumentFragment();
38
+ const end = document.createTextNode(closing);
39
+ fragment.append(document.createTextNode(opening), contents, end);
40
+ range.insertNode(fragment);
41
+ range.setStartAfter(end);
42
+ range.collapse(true);
43
+ setSelectionFocus(range);
44
+ if (vditor.currentMode === "ir") {
45
+ irInput(vditor, range, true);
46
+ } else {
47
+ input(vditor, range);
48
+ }
49
+ return true;
50
+ };
51
+
52
+ export const deleteEmptyPair = (vditor: IVditor): boolean => {
53
+ if (vditor.currentMode === "sv") {
54
+ const textarea = vditor.sv.element;
55
+ const offset = textarea.selectionStart;
56
+ if (textarea.disabled || offset !== textarea.selectionEnd || !isPair(textarea.value[offset - 1], textarea.value[offset])) {
57
+ return false;
58
+ }
59
+ const depth = pairDepth(textarea.value.substring(0, offset), textarea.value.substring(offset));
60
+ textarea.setRangeText("", offset - depth, offset + depth, "end");
61
+ processAfterRender(vditor);
62
+ return true;
63
+ }
64
+ const editor = vditor[vditor.currentMode].element;
65
+ const range = getEditorRange(vditor).cloneRange();
66
+ if (editor.getAttribute("contenteditable") !== "true" || range.toString() !== "" || !editor.contains(range.startContainer)) {
67
+ return false;
68
+ }
69
+ range.collapse(true);
70
+ const node = range.startContainer;
71
+ const offset = range.startOffset;
72
+ const isText = node.nodeType === Node.TEXT_NODE;
73
+ const left = isText ? (offset ? node : node.previousSibling) : node.childNodes[offset - 1];
74
+ const right = isText ? (offset < node.textContent.length ? node : node.nextSibling) : node.childNodes[offset];
75
+ if (left?.nodeType !== Node.TEXT_NODE || right?.nodeType !== Node.TEXT_NODE || left.parentNode !== right.parentNode) {
76
+ return false;
77
+ }
78
+ const start = left === node ? offset - 1 : left.textContent.length - 1;
79
+ const end = right === node ? offset : 0;
80
+ if (!isPair(left.textContent[start], right.textContent[end])) {
81
+ return false;
82
+ }
83
+ const depth = pairDepth(left.textContent.substring(0, start + 1), right.textContent.substring(end));
84
+ range.setStart(left, start - depth + 1);
85
+ range.setEnd(right, end + depth);
86
+ range.deleteContents();
87
+ setSelectionFocus(range);
88
+ if (vditor.currentMode === "ir") {
89
+ irInput(vditor, range, true);
90
+ } else {
91
+ input(vditor, range);
92
+ }
93
+ return true;
94
+ };
95
+
96
+ const isPair = (opening: string, closing: string) => !!opening && !!closing &&
97
+ (pairedSymbols[opening] === closing || (["*", "~", "$"].includes(opening) && opening === closing));
98
+
99
+ const pairDepth = (left: string, right: string) => {
100
+ const marker = left[left.length - 1];
101
+ if (!["*", "~", "$", "`"].includes(marker)) {
102
+ return 1;
103
+ }
104
+ let before = 0;
105
+ let after = 0;
106
+ while (left[left.length - before - 1] === marker) { before++; }
107
+ while (right[after] === marker) { after++; }
108
+ return Math.min(before, after);
109
+ };
@@ -0,0 +1,136 @@
1
+ import {hasClosestByMatchTag} from "./hasClosest";
2
+ import {getEditorRange, setSelectionFocus} from "./selection";
3
+
4
+ const getCell = (node: Node) => (hasClosestByMatchTag(node, "TD") ||
5
+ hasClosestByMatchTag(node, "TH")) as HTMLTableCellElement | false;
6
+
7
+ const getOnlyTable = (root: Element): HTMLTableElement | undefined => {
8
+ const nodes = Array.from(root.childNodes).filter(node =>
9
+ node.nodeType !== Node.COMMENT_NODE && (node.nodeType !== Node.TEXT_NODE || node.textContent.trim()));
10
+ if (nodes.length !== 1 || !(nodes[0] instanceof HTMLElement)) {
11
+ return;
12
+ }
13
+ const element = nodes[0];
14
+ if (element.tagName === "TABLE") {
15
+ return element as HTMLTableElement;
16
+ }
17
+ if (["DIV", "BODY", "HTML", "SPAN"].includes(element.tagName)) {
18
+ return getOnlyTable(element);
19
+ }
20
+ };
21
+
22
+ export const parseMarkdownTableRows = (text: string): string[][] | null => {
23
+ const lines = text.trim().split(/\r?\n/);
24
+ const matrix: string[][] = [];
25
+ for (const line of lines) {
26
+ const row = line.trim();
27
+ if (!row.startsWith("|") || !row.endsWith("|")) {
28
+ return null;
29
+ }
30
+ const cells: string[] = [];
31
+ let cell = "";
32
+ for (let i = 1; i < row.length - 1; i++) {
33
+ if (row[i] === "\\" && i + 1 < row.length - 1) {
34
+ cell += row[i] + row[++i];
35
+ } else if (row[i] === "|") {
36
+ cells.push(cell.trim());
37
+ cell = "";
38
+ } else {
39
+ cell += row[i];
40
+ }
41
+ }
42
+ cells.push(cell.trim());
43
+ if (matrix.length === 1 && cells.every(value => /^:?-+:?$/.test(value))) {
44
+ continue;
45
+ }
46
+ matrix.push(cells);
47
+ }
48
+ return matrix.length ? matrix : null;
49
+ };
50
+
51
+ export const pasteIntoTable = (vditor: IVditor, html: string, markdown = ""): boolean => {
52
+ if (vditor.currentMode === "sv") {
53
+ return false;
54
+ }
55
+ const range = getEditorRange(vditor);
56
+ const startCell = getCell(range.startContainer);
57
+ if (!startCell || startCell !== getCell(range.endContainer)) {
58
+ return false;
59
+ }
60
+ const source = document.createElement("div");
61
+ if (markdown) {
62
+ const matrix = parseMarkdownTableRows(markdown);
63
+ if (!matrix) {
64
+ return false;
65
+ }
66
+ const rows = matrix.map(row => "| " + row.join(" | ") + " |");
67
+ rows.splice(1, 0, "| " + matrix[0].map(() => "---").join(" | ") + " |");
68
+ html = vditor.lute.Md2HTML(rows.join("\n"));
69
+ }
70
+ html = Lute.Sanitize(html);
71
+ source.innerHTML = html;
72
+ if (!getOnlyTable(source)) {
73
+ return false;
74
+ }
75
+ // 通过解析器生成目标模式的单元格,避免带入外部样式和不支持的嵌套结构。
76
+ source.innerHTML = vditor.currentMode === "ir" ? vditor.lute.HTML2VditorIRDOM(html) :
77
+ vditor.lute.HTML2VditorDOM(html);
78
+ const sourceTable = source.querySelector("table");
79
+ if (!sourceTable?.rows.length || !sourceTable.rows[0].cells.length) {
80
+ return false;
81
+ }
82
+ const table = startCell.closest("table");
83
+ const rowIndex = (startCell.parentElement as HTMLTableRowElement).rowIndex;
84
+ const colIndex = startCell.cellIndex;
85
+ const width = Math.max(table.rows[0].cells.length, colIndex + sourceTable.rows[0].cells.length);
86
+ // 所有行保持相同宽度,防止 Markdown 规范化时截断新增列。
87
+ while (table.rows.length < rowIndex + sourceTable.rows.length) {
88
+ const body = table.tBodies[0] || table.createTBody();
89
+ body.insertRow();
90
+ }
91
+ Array.from(table.rows).forEach(row => {
92
+ while (row.cells.length < width) {
93
+ row.appendChild(document.createElement(row.parentElement.tagName === "THEAD" ? "th" : "td"));
94
+ }
95
+ });
96
+ let lastCell = startCell;
97
+ Array.from(sourceTable.rows).forEach((row, r) => {
98
+ Array.from(row.cells).forEach((cell, c) => {
99
+ lastCell = table.rows[rowIndex + r].cells[colIndex + c];
100
+ lastCell.innerHTML = cell.innerHTML;
101
+ });
102
+ });
103
+ range.selectNodeContents(lastCell);
104
+ range.collapse(false);
105
+ setSelectionFocus(range);
106
+ return true;
107
+ };
108
+
109
+ export const buildTableSelectionClipboard = (vditor: IVditor, range: Range): {html: string; plain: string} | null => {
110
+ const start = getCell(range.startContainer);
111
+ const end = getCell(range.endContainer);
112
+ if (!start || !end || start === end || start.closest("table") !== end.closest("table")) {
113
+ return null;
114
+ }
115
+ const table = start.closest("table");
116
+ const firstRow = (start.parentElement as HTMLTableRowElement).rowIndex;
117
+ const lastRow = (end.parentElement as HTMLTableRowElement).rowIndex;
118
+ const left = Math.min(start.cellIndex, end.cellIndex);
119
+ const right = Math.max(start.cellIndex, end.cellIndex);
120
+ let html = "<table><thead>";
121
+ for (let r = firstRow; r <= lastRow; r++) {
122
+ html += "<tr>";
123
+ for (let c = left; c <= right; c++) {
124
+ const tag = r === firstRow ? "th" : "td";
125
+ html += `<${tag}>${table.rows[r].cells[c]?.innerHTML || ""}</${tag}>`;
126
+ }
127
+ html += "</tr>";
128
+ if (r === firstRow) {
129
+ html += "</thead><tbody>";
130
+ }
131
+ }
132
+ html += "</tbody></table>";
133
+ const plain = (vditor.currentMode === "ir" ? vditor.lute.VditorIRDOM2Md(html) :
134
+ vditor.lute.VditorDOM2Md(html)).trim();
135
+ return {plain, html: vditor.lute.Md2HTML(plain)};
136
+ };
@@ -0,0 +1,51 @@
1
+ import {getEditorRange} from "./selection";
2
+ import {hasClosestByAttribute, hasClosestByClassName, hasClosestByMatchTag} from "./hasClosest";
3
+
4
+ interface IMarkdownNode {
5
+ Type: string;
6
+ Data?: string;
7
+ Children?: IMarkdownNode[];
8
+ }
9
+
10
+ const containsPlainText = (node: IMarkdownNode, marker: string): boolean => {
11
+ if (node.Type === "NodeLink" || node.Type === "NodeImage") {
12
+ return false;
13
+ }
14
+ return (node.Type === "NodeText" && !!node.Data?.includes(marker)) ||
15
+ !!node.Children?.some(child => containsPlainText(child, marker));
16
+ };
17
+
18
+ export const getPastedLink = (vditor: IVditor, text: string): string => {
19
+ if (!vditor.lute.IsValidLinkDest(text)) {
20
+ return text;
21
+ }
22
+ let selectedText: string;
23
+ if (vditor.currentMode === "sv") {
24
+ const element = vditor.sv.element;
25
+ const start = element.selectionStart;
26
+ const end = element.selectionEnd;
27
+ const marker = "vditorlink" + Lute.NewNodeID();
28
+ // 使用解析后的节点判断插入位置,避免在链接地址、代码和公式等语法内生成链接。
29
+ const tree: IMarkdownNode = JSON.parse(vditor.lute.RenderJSON(
30
+ element.value.substring(0, start) + marker + element.value.substring(end)));
31
+ if (!containsPlainText(tree, marker)) {
32
+ return text;
33
+ }
34
+ selectedText = element.value.substring(start, end);
35
+ } else {
36
+ const range = getEditorRange(vditor);
37
+ if (hasClosestByMatchTag(range.startContainer, "A") || hasClosestByMatchTag(range.startContainer, "CODE") ||
38
+ hasClosestByAttribute(range.startContainer, "data-type", "a") ||
39
+ hasClosestByClassName(range.startContainer, "vditor-ir__marker--link")) {
40
+ return text;
41
+ }
42
+ selectedText = range.toString();
43
+ }
44
+ const title = (selectedText || text).replace(/[\\`*_[\]!~^=$&<>|:]/g, "\\$&");
45
+ const encode = (character: string) => "%" + character.charCodeAt(0).toString(16).toUpperCase();
46
+ // 百分号编码语法字符和实体中的非保留字符,保持查询参数分隔符和 Markdown 往返语义。
47
+ const destination = text.replace(/[\\()<>|]/g, encode).replace(
48
+ /&(?:#[xX]?)?([a-zA-Z0-9])(?=[a-zA-Z0-9]*;)/g,
49
+ (match, character: string) => match.slice(0, -1) + encode(character));
50
+ return `[${title}](${destination})`;
51
+ };
@@ -12,29 +12,54 @@ import {plantumlRender} from "../markdown/plantumlRender";
12
12
  import {SMILESRender} from "../markdown/SMILESRender";
13
13
  import {wavedromRender} from "../markdown/wavedromRender";
14
14
 
15
+ export const isPlainTextPaste = (html: string, editorData: string) => {
16
+ if (editorData) {
17
+ try {
18
+ if (JSON.parse(editorData).mode === "markdown") {
19
+ return true;
20
+ }
21
+ } catch {
22
+ // 剪贴板中的第三方元数据可能损坏,仍按 HTML 结构处理。
23
+ }
24
+ }
25
+ const tempElement = document.createElement("div");
26
+ tempElement.innerHTML = html;
27
+ const pre = tempElement.firstElementChild as HTMLElement;
28
+ // 浏览器为纯文本生成的 pre-wrap 包装不表示代码语义。
29
+ return tempElement.childNodes.length === 1 && pre?.tagName === "PRE" &&
30
+ pre.style.whiteSpace === "pre-wrap" && pre.childElementCount === 0;
31
+ };
32
+
15
33
  export const processPasteCode = (html: string, text: string, type = "sv") => {
16
34
  const tempElement = document.createElement("div");
17
35
  tempElement.innerHTML = html;
36
+ const preElement = tempElement.querySelector("pre");
37
+ if (preElement) {
38
+ let element: Element = preElement;
39
+ while (element !== tempElement) {
40
+ const parent = element.parentElement;
41
+ // 混合内容需要交给 HTML 转换,以保留段落、表格和独立代码块。
42
+ if (Array.from(parent.childNodes).some(node => node !== element &&
43
+ (node.nodeType === Node.ELEMENT_NODE ||
44
+ node.nodeType === Node.TEXT_NODE && node.textContent.trim() !== ""))) {
45
+ return false;
46
+ }
47
+ element = parent;
48
+ }
49
+ }
18
50
  let isCode = false;
19
51
  if (tempElement.childElementCount === 1 &&
20
52
  (tempElement.lastElementChild as HTMLElement).style.fontFamily.indexOf("monospace") > -1) {
21
- // VS Code
22
53
  isCode = true;
23
54
  }
24
55
  const pres = tempElement.querySelectorAll("pre");
25
56
  if (tempElement.childElementCount === 1 && pres.length === 1
26
57
  && pres[0].className !== "vditor-wysiwyg"
27
58
  && pres[0].className !== "vditor-sv") {
28
- // IDE
29
- isCode = true;
30
- }
31
- if (html.indexOf('\n<p class="p1">') === 0) {
32
- // Xcode
33
59
  isCode = true;
34
60
  }
35
61
  if (tempElement.childElementCount === 1 && tempElement.firstElementChild.tagName === "TABLE" &&
36
62
  tempElement.querySelector(".line-number") && tempElement.querySelector(".line-content")) {
37
- // 网页源码
38
63
  isCode = true;
39
64
  }
40
65
 
@@ -92,7 +117,7 @@ export const processCodeRender = (previewPanel: HTMLElement, vditor: IVditor) =>
92
117
  } else if (language === "mindmap") {
93
118
  mindmapRender(previewPanel, vditor.options.cdn, vditor.options.theme);
94
119
  } else if (language === "plantuml") {
95
- plantumlRender(previewPanel, vditor.options.cdn);
120
+ plantumlRender(previewPanel, vditor.options.cdn, vditor.options.plantuml);
96
121
  } else if (language === "graphviz") {
97
122
  graphvizRender(previewPanel, vditor.options.cdn);
98
123
  } else if (language === "wavedrom") {