vditor 4.0.2-alpha.0 → 4.0.2-alpha.10

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 (134) hide show
  1. package/README.md +75 -5
  2. package/dist/index.css +108 -29
  3. package/dist/index.d.ts +5 -0
  4. package/dist/index.js +7338 -5352
  5. package/dist/index.min.js +1 -1
  6. package/dist/index.mjs +18244 -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/i18n/de_DE.js +6 -0
  13. package/dist/js/i18n/en_US.js +6 -0
  14. package/dist/js/i18n/es_ES.js +6 -0
  15. package/dist/js/i18n/fr_FR.js +6 -0
  16. package/dist/js/i18n/ja_JP.js +6 -0
  17. package/dist/js/i18n/ko_KR.js +6 -0
  18. package/dist/js/i18n/pt_BR.js +6 -0
  19. package/dist/js/i18n/ru_RU.js +6 -0
  20. package/dist/js/i18n/sv_SE.js +6 -0
  21. package/dist/js/i18n/vi_VN.js +6 -0
  22. package/dist/js/i18n/zh_CN.js +6 -0
  23. package/dist/js/i18n/zh_TW.js +6 -0
  24. package/dist/js/icons/LICENSE-lucide.txt +46 -0
  25. package/dist/js/icons/ant.js +6 -0
  26. package/dist/js/icons/material.js +6 -0
  27. package/dist/js/lute/lute.min.js +21 -19
  28. package/dist/method.d.ts +3 -3
  29. package/dist/method.js +2125 -1847
  30. package/dist/method.min.js +1 -1
  31. package/dist/method.mjs +3243 -0
  32. package/dist/ts/constants.d.ts +2 -0
  33. package/dist/ts/find/index.d.ts +40 -0
  34. package/dist/ts/find/text.d.ts +4 -0
  35. package/dist/ts/hint/index.d.ts +4 -0
  36. package/dist/ts/ir/index.d.ts +1 -0
  37. package/dist/ts/markdown/codeCopy.d.ts +1 -0
  38. package/dist/ts/markdown/highlightRender.d.ts +1 -1
  39. package/dist/ts/markdown/mathRender.d.ts +24 -1
  40. package/dist/ts/markdown/outlineRender.d.ts +2 -1
  41. package/dist/ts/markdown/plantumlRender.d.ts +1 -1
  42. package/dist/ts/outline/index.d.ts +2 -0
  43. package/dist/ts/sv/index.d.ts +1 -0
  44. package/dist/ts/tip/index.d.ts +6 -1
  45. package/dist/ts/toolbar/Find.d.ts +5 -0
  46. package/dist/ts/undo/index.d.ts +1 -0
  47. package/dist/ts/upload/linkToImg.d.ts +1 -0
  48. package/dist/ts/util/addScript.d.ts +1 -2
  49. package/dist/ts/util/codeDOM.d.ts +2 -0
  50. package/dist/ts/util/codeSelection.d.ts +1 -0
  51. package/dist/ts/util/compatibility.d.ts +1 -1
  52. package/dist/ts/util/expandHTMLTags.d.ts +1 -0
  53. package/dist/ts/util/fixBrowserBehavior.d.ts +1 -0
  54. package/dist/ts/util/imageDrag.d.ts +1 -0
  55. package/dist/ts/util/notifyConfigChange.d.ts +1 -0
  56. package/dist/ts/util/pairedSymbols.d.ts +5 -0
  57. package/dist/ts/util/pasteIntoTable.d.ts +6 -0
  58. package/dist/ts/util/pasteLink.d.ts +1 -0
  59. package/dist/ts/util/processCode.d.ts +2 -0
  60. package/dist/ts/util/tableWheel.d.ts +1 -0
  61. package/dist/ts/util/taskNavigation.d.ts +1 -0
  62. package/dist/ts/wysiwyg/index.d.ts +1 -0
  63. package/dist/types/index.d.ts +84 -2
  64. package/package.json +4 -2
  65. package/src/assets/less/_find.less +84 -0
  66. package/src/assets/less/_hint.less +6 -0
  67. package/src/assets/less/_reset.less +29 -0
  68. package/src/assets/less/_tooltipped.less +2 -2
  69. package/src/assets/less/_wysiwyg.less +4 -0
  70. package/src/assets/less/index.less +3 -0
  71. package/src/index.ts +49 -6
  72. package/src/ts/constants.ts +4 -0
  73. package/src/ts/find/index.ts +310 -0
  74. package/src/ts/find/text.ts +208 -0
  75. package/src/ts/hint/index.ts +31 -8
  76. package/src/ts/ir/expandMarker.ts +3 -0
  77. package/src/ts/ir/index.ts +16 -3
  78. package/src/ts/ir/process.ts +7 -1
  79. package/src/ts/ir/processKeydown.ts +5 -0
  80. package/src/ts/markdown/chartRender.ts +28 -2
  81. package/src/ts/markdown/codeCopy.ts +41 -0
  82. package/src/ts/markdown/codeRender.ts +19 -8
  83. package/src/ts/markdown/graphvizRender.ts +51 -39
  84. package/src/ts/markdown/highlightRender.ts +25 -12
  85. package/src/ts/markdown/mathRender.ts +26 -38
  86. package/src/ts/markdown/mediaRender.ts +1 -1
  87. package/src/ts/markdown/mermaidRender.ts +4 -3
  88. package/src/ts/markdown/outlineRender.ts +44 -15
  89. package/src/ts/markdown/plantumlRender.ts +24 -5
  90. package/src/ts/markdown/previewRender.ts +5 -1
  91. package/src/ts/markdown/setLute.ts +10 -0
  92. package/src/ts/outline/index.ts +72 -0
  93. package/src/ts/preview/index.ts +1 -1
  94. package/src/ts/sv/index.ts +1 -0
  95. package/src/ts/sv/process.ts +7 -1
  96. package/src/ts/tip/index.ts +25 -9
  97. package/src/ts/toolbar/CodeTheme.ts +2 -0
  98. package/src/ts/toolbar/ContentTheme.ts +2 -0
  99. package/src/ts/toolbar/EditMode.ts +5 -0
  100. package/src/ts/toolbar/Find.ts +12 -0
  101. package/src/ts/toolbar/Headings.ts +4 -6
  102. package/src/ts/toolbar/Outline.ts +2 -0
  103. package/src/ts/toolbar/Record.ts +5 -0
  104. package/src/ts/toolbar/index.ts +5 -1
  105. package/src/ts/toolbar/setToolbar.ts +1 -1
  106. package/src/ts/ui/initUI.ts +10 -1
  107. package/src/ts/ui/setPreviewMode.ts +2 -0
  108. package/src/ts/undo/index.ts +41 -9
  109. package/src/ts/upload/index.ts +1 -1
  110. package/src/ts/upload/linkToImg.ts +91 -0
  111. package/src/ts/util/Options.ts +9 -0
  112. package/src/ts/util/addScript.ts +15 -24
  113. package/src/ts/util/codeDOM.ts +21 -0
  114. package/src/ts/util/codeSelection.ts +37 -0
  115. package/src/ts/util/compatibility.ts +2 -2
  116. package/src/ts/util/editorCommonEvent.ts +48 -5
  117. package/src/ts/util/expandHTMLTags.ts +36 -0
  118. package/src/ts/util/fixBrowserBehavior.ts +124 -61
  119. package/src/ts/util/imageDrag.ts +108 -0
  120. package/src/ts/util/notifyConfigChange.ts +16 -0
  121. package/src/ts/util/pairedSymbols.ts +109 -0
  122. package/src/ts/util/pasteIntoTable.ts +136 -0
  123. package/src/ts/util/pasteLink.ts +51 -0
  124. package/src/ts/util/processCode.ts +46 -9
  125. package/src/ts/util/selection.ts +11 -2
  126. package/src/ts/util/tableWheel.ts +31 -0
  127. package/src/ts/util/taskNavigation.ts +113 -0
  128. package/src/ts/util/toc.ts +9 -3
  129. package/src/ts/wysiwyg/afterRenderEvent.ts +7 -1
  130. package/src/ts/wysiwyg/highlightToolbarWYSIWYG.ts +6 -5
  131. package/src/ts/wysiwyg/index.ts +20 -6
  132. package/src/ts/wysiwyg/processKeydown.ts +5 -0
  133. package/src/ts/wysiwyg/setHeading.ts +4 -0
  134. package/dist/js/graphviz/full.render.js +0 -90
@@ -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
 
@@ -56,6 +81,16 @@ export const processPasteCode = (html: string, text: string, type = "sv") => {
56
81
  return false;
57
82
  };
58
83
 
84
+ export const highlightEditableCode = (previewPanel: HTMLElement, vditor: IVditor) => {
85
+ const source = previewPanel.previousElementSibling as HTMLElement;
86
+ const mode = vditor.currentMode;
87
+ if (source?.tagName === "PRE" && mode !== "sv") {
88
+ highlightRender(vditor.options.preview.hljs, source, vditor.options.cdn, () =>
89
+ vditor.currentMode === mode && !vditor[mode].composingLock &&
90
+ vditor[mode].element.contains(source));
91
+ }
92
+ };
93
+
59
94
  export const processCodeRender = (previewPanel: HTMLElement, vditor: IVditor) => {
60
95
  if (!previewPanel) {
61
96
  return;
@@ -65,7 +100,8 @@ export const processCodeRender = (previewPanel: HTMLElement, vditor: IVditor) =>
65
100
  previewPanel.setAttribute("data-render", "1");
66
101
  return;
67
102
  }
68
- const language = previewPanel.firstElementChild.className.replace("language-", "");
103
+ const language = previewPanel.firstElementChild.className.split(/\s+/)
104
+ .find(name => name.startsWith("language-"))?.slice(9) || "";
69
105
  if (language === "abc") {
70
106
  abcRender(previewPanel, vditor.options.cdn);
71
107
  } else if (language === "mermaid") {
@@ -81,7 +117,7 @@ export const processCodeRender = (previewPanel: HTMLElement, vditor: IVditor) =>
81
117
  } else if (language === "mindmap") {
82
118
  mindmapRender(previewPanel, vditor.options.cdn, vditor.options.theme);
83
119
  } else if (language === "plantuml") {
84
- plantumlRender(previewPanel, vditor.options.cdn);
120
+ plantumlRender(previewPanel, vditor.options.cdn, vditor.options.plantuml);
85
121
  } else if (language === "graphviz") {
86
122
  graphvizRender(previewPanel, vditor.options.cdn);
87
123
  } else if (language === "wavedrom") {
@@ -97,6 +133,7 @@ export const processCodeRender = (previewPanel: HTMLElement, vditor: IVditor) =>
97
133
  })
98
134
  if (!cRender) {
99
135
  previewPanel.classList.add("vditor-code__preview");
136
+ highlightEditableCode(previewPanel, vditor);
100
137
  highlightRender(Object.assign({}, vditor.options.preview.hljs), previewPanel, vditor.options.cdn);
101
138
  codeRender(previewPanel, vditor.options.preview.hljs);
102
139
  }
@@ -271,8 +271,17 @@ export const insertHTML = (html: string, vditor: IVditor) => {
271
271
  vditor[vditor.currentMode].element.insertAdjacentHTML("beforeend", pasteElement.innerHTML);
272
272
  } else {
273
273
  const liElement = hasClosestByMatchTag(range.startContainer, "LI");
274
- if (liElement && pasteElement.firstElementChild.tagName === "UL") {
275
- liElement.insertAdjacentHTML("afterend", pasteElement.firstElementChild.innerHTML);
274
+ if (liElement && pasteElement.childElementCount === 1 && (pasteElement.firstElementChild.tagName === "UL" ||
275
+ pasteElement.firstElementChild.tagName === "OL")) {
276
+ const before = range.cloneRange();
277
+ before.selectNodeContents(liElement);
278
+ before.setEnd(range.startContainer, range.startOffset);
279
+ const prefix = document.createElement("div");
280
+ prefix.appendChild(before.cloneContents());
281
+ prefix.querySelectorAll(".vditor-ir__marker, input").forEach(item => item.remove());
282
+ const atStart = prefix.textContent.replace(/\u200b/g, "").trim() === "" &&
283
+ !prefix.querySelector("img, video, audio, iframe, ul, ol, table, pre");
284
+ liElement.insertAdjacentHTML(atStart ? "beforebegin" : "afterend", pasteElement.firstElementChild.innerHTML);
276
285
  } else {
277
286
  blockElement.insertAdjacentHTML("afterend", pasteElement.innerHTML);
278
287
  }
@@ -0,0 +1,31 @@
1
+ const boundElements = new WeakSet<HTMLElement>();
2
+
3
+ export const bindTableWheel = (element: HTMLElement) => {
4
+ if (boundElements.has(element)) {
5
+ return;
6
+ }
7
+ boundElements.add(element);
8
+ element.addEventListener("wheel", (event: WheelEvent) => {
9
+ if (!event.cancelable || event.defaultPrevented || event.ctrlKey || event.metaKey || event.altKey || event.shiftKey ||
10
+ event.deltaX !== 0 || event.deltaY === 0) {
11
+ return;
12
+ }
13
+ const target = event.target instanceof Element ? event.target : (event.target as Node).parentElement;
14
+ const table = target?.closest("table");
15
+ if (!table || !element.contains(table) || table.scrollWidth <= table.clientWidth) {
16
+ return;
17
+ }
18
+ const style = getComputedStyle(table);
19
+ if (!/auto|scroll/.test(style.overflowX)) {
20
+ return;
21
+ }
22
+ const scale = event.deltaMode === WheelEvent.DOM_DELTA_LINE ? (parseFloat(style.lineHeight) || 20) :
23
+ event.deltaMode === WheelEvent.DOM_DELTA_PAGE ? table.clientWidth : 1;
24
+ const before = table.scrollLeft;
25
+ table.scrollLeft += event.deltaY * scale * (style.direction === "rtl" ? -1 : 1);
26
+ // 到达横向边界后交给页面滚动,避免滚轮被表格持续截留。
27
+ if (table.scrollLeft !== before) {
28
+ event.preventDefault();
29
+ }
30
+ }, {passive: false});
31
+ };
@@ -0,0 +1,113 @@
1
+ const getTaskPrefix = (root: HTMLElement, range: Range) => {
2
+ const element = range.startContainer.nodeType === Node.ELEMENT_NODE ?
3
+ range.startContainer as Element : range.startContainer.parentElement;
4
+ const item = element?.closest("li.vditor-task");
5
+ const firstElement = item?.firstElementChild;
6
+ const checkbox = firstElement?.tagName === "P" ? firstElement.firstElementChild : firstElement;
7
+ if (!item || !root.contains(item) || checkbox?.tagName !== "INPUT" ||
8
+ checkbox.getAttribute("type") !== "checkbox") {
9
+ return;
10
+ }
11
+ const body = document.createRange();
12
+ let text = checkbox.nextSibling;
13
+ while (text?.nodeType === Node.TEXT_NODE && text.textContent === "") {
14
+ text = text.nextSibling;
15
+ }
16
+ if (text?.nodeType === Node.TEXT_NODE && text.textContent === " " && text.nextSibling &&
17
+ !(text.nextSibling instanceof Element && text.nextSibling.matches("ul, ol"))) {
18
+ body.selectNodeContents(text.nextSibling);
19
+ } else if (text?.nodeType === Node.TEXT_NODE) {
20
+ body.setStart(text, text.textContent.startsWith(" ") ? 1 : 0);
21
+ } else if (text) {
22
+ body.selectNodeContents(text);
23
+ } else {
24
+ body.setStartAfter(checkbox);
25
+ }
26
+ body.collapse(true);
27
+ if (range.compareBoundaryPoints(Range.START_TO_START, body) < 0) {
28
+ return {item, body};
29
+ }
30
+ };
31
+
32
+ const skipTaskPrefix = (root: HTMLElement, event: KeyboardEvent) => {
33
+ const selection = window.getSelection();
34
+ if (document.activeElement !== root || root.getAttribute("contenteditable") !== "true" ||
35
+ !selection?.isCollapsed || !selection.rangeCount || !root.contains(selection.anchorNode)) {
36
+ return;
37
+ }
38
+ let prefix = getTaskPrefix(root, selection.getRangeAt(0));
39
+ if (!prefix) {
40
+ return;
41
+ }
42
+ const body = prefix.body;
43
+ const item = prefix.item;
44
+ const backwardKey = getComputedStyle(prefix.item).direction === "rtl" ? "ArrowRight" : "ArrowLeft";
45
+ if (event.key !== backwardKey || typeof selection.modify !== "function") {
46
+ selection.removeAllRanges();
47
+ selection.addRange(body);
48
+ return;
49
+ }
50
+
51
+ // 复选框附近可能有多个等价的 DOM 边界,继续沿浏览器原生方向移动到正文。
52
+ const visited = new Map<Node, Set<number>>();
53
+ while (prefix) {
54
+ const node = selection.anchorNode;
55
+ const offset = selection.anchorOffset;
56
+ const offsets = visited.get(node) || new Set<number>();
57
+ if (offsets.has(offset)) {
58
+ selection.removeAllRanges();
59
+ selection.addRange(body);
60
+ return;
61
+ }
62
+ offsets.add(offset);
63
+ visited.set(node, offsets);
64
+ selection.modify("move", event.key === "ArrowLeft" ? "left" : "right", "character");
65
+ if (!selection.rangeCount || !root.contains(selection.anchorNode)) {
66
+ selection.removeAllRanges();
67
+ selection.addRange(body);
68
+ return;
69
+ }
70
+ prefix = getTaskPrefix(root, selection.getRangeAt(0));
71
+ if (prefix && prefix.item !== item) {
72
+ selection.removeAllRanges();
73
+ selection.addRange(prefix.body);
74
+ return;
75
+ }
76
+ }
77
+ };
78
+
79
+ export const bindTaskNavigation = (vditor: IVditor, root: HTMLElement) => {
80
+ let navigation: KeyboardEvent;
81
+ let timeout: number;
82
+ root.addEventListener("compositionstart", () => {
83
+ clearTimeout(timeout);
84
+ navigation = undefined;
85
+ });
86
+ root.addEventListener("keydown", event => {
87
+ clearTimeout(timeout);
88
+ navigation = undefined;
89
+ if (vditor.currentMode === "sv" || vditor[vditor.currentMode].composingLock || event.isComposing ||
90
+ event.shiftKey || event.ctrlKey || event.metaKey ||
91
+ event.altKey || (event.key !== "ArrowLeft" && event.key !== "ArrowRight") ||
92
+ !window.getSelection()?.isCollapsed) {
93
+ return;
94
+ }
95
+ navigation = event;
96
+ // 等待默认光标移动,按住方向键时每次重复也会跳过任务标记。
97
+ timeout = window.setTimeout(() => {
98
+ if (navigation === event && !event.defaultPrevented) {
99
+ skipTaskPrefix(root, event);
100
+ }
101
+ });
102
+ }, true);
103
+ root.addEventListener("keyup", event => {
104
+ if (navigation?.key === event.key) {
105
+ clearTimeout(timeout);
106
+ if (!navigation.defaultPrevented && !event.isComposing && !event.shiftKey && !event.ctrlKey &&
107
+ !event.metaKey && !event.altKey) {
108
+ skipTaskPrefix(root, event);
109
+ }
110
+ navigation = undefined;
111
+ }
112
+ }, true);
113
+ };
@@ -1,7 +1,7 @@
1
1
  import {mathRender} from "../markdown/mathRender";
2
2
  import {execAfterRender, insertAfterBlock, insertBeforeBlock} from "./fixBrowserBehavior";
3
- import {hasClosestByClassName, hasClosestByMatchTag} from "./hasClosest";
4
- import {getSelectPosition} from "./selection";
3
+ import {hasClosestByClassName} from "./hasClosest";
4
+ import {getSelectPosition, setSelectionFocus} from "./selection";
5
5
 
6
6
  export const renderToc = (vditor: IVditor) => {
7
7
  if (vditor.currentMode === "sv") {
@@ -22,10 +22,16 @@ export const renderToc = (vditor: IVditor) => {
22
22
  };
23
23
 
24
24
  export const clickToc = (event: MouseEvent & { target: HTMLElement }, vditor: IVditor) => {
25
- const spanElement = hasClosestByMatchTag(event.target, "SPAN");
25
+ const spanElement = event.target.closest<HTMLElement>("[data-target-id]");
26
26
  if (spanElement && hasClosestByClassName(spanElement, "vditor-toc")) {
27
27
  const headingElement = vditor[vditor.currentMode].element.querySelector("#" + spanElement.getAttribute("data-target-id")) as HTMLElement;
28
28
  if (headingElement) {
29
+ const editorElement = vditor[vditor.currentMode].element;
30
+ const range = editorElement.ownerDocument.createRange();
31
+ range.selectNodeContents(headingElement);
32
+ range.collapse(true);
33
+ editorElement.focus({preventScroll: true});
34
+ setSelectionFocus(range);
29
35
  if (vditor.options.height === "auto") {
30
36
  let windowScrollY = headingElement.offsetTop + vditor.element.offsetTop;
31
37
  if (!vditor.options.toolbarConfig.pin) {
@@ -7,12 +7,18 @@ export const afterRenderEvent = (vditor: IVditor, options = {
7
7
  enableHint: false,
8
8
  enableInput: true,
9
9
  }) => {
10
+ vditor.wysiwyg.pendingUndoStack = options.enableAddUndoStack && vditor.options.undoDelay !== 0;
10
11
  renderImageCaptions(vditor.wysiwyg.element, "wysiwyg", vditor.options.preview.markdown.imageCaption);
12
+ if (options.enableAddUndoStack && vditor.options.undoDelay === 0) {
13
+ vditor.undo.addToUndoStack(vditor);
14
+ }
11
15
  if (options.enableHint) {
12
16
  vditor.hint.render(vditor);
13
17
  }
14
18
  clearTimeout(vditor.wysiwyg.afterRenderTimeoutId);
15
19
  vditor.wysiwyg.afterRenderTimeoutId = window.setTimeout(() => {
20
+ vditor.wysiwyg.afterRenderTimeoutId = 0;
21
+ vditor.wysiwyg.pendingUndoStack = false;
16
22
  if (vditor.wysiwyg.composingLock) {
17
23
  return;
18
24
  }
@@ -36,7 +42,7 @@ export const afterRenderEvent = (vditor: IVditor, options = {
36
42
  vditor.devtools.renderEchart(vditor);
37
43
  }
38
44
 
39
- if (options.enableAddUndoStack) {
45
+ if (options.enableAddUndoStack && vditor.options.undoDelay !== 0) {
40
46
  vditor.undo.addToUndoStack(vditor);
41
47
  }
42
48
  }, vditor.options.undoDelay);
@@ -34,6 +34,7 @@ import {removeBlockElement} from "./processKeydown";
34
34
  import {renderToc} from "../util/toc";
35
35
  import {getMarkdown} from "../markdown/getMarkdown";
36
36
  import {renderImageCaptions} from "../markdown/imageCaptionRender";
37
+ import {expandHTMLTags} from "../util/expandHTMLTags";
37
38
 
38
39
  export const highlightToolbarWYSIWYG = (vditor: IVditor) => {
39
40
  clearTimeout(vditor.wysiwyg.hlToolbarTimeoutId);
@@ -51,6 +52,10 @@ export const highlightToolbarWYSIWYG = (vditor: IVditor) => {
51
52
  enableToolbar(vditor.toolbar.elements, Constants.EDIT_TOOLBARS);
52
53
 
53
54
  const range = getSelection().getRangeAt(0);
55
+ vditor.wysiwyg.element.querySelectorAll(".vditor-wysiwyg__kbd-marker--expand").forEach(element => {
56
+ element.classList.remove("vditor-wysiwyg__kbd-marker--expand");
57
+ });
58
+ expandHTMLTags(vditor.wysiwyg.element, range, "vditor-wysiwyg__kbd-marker--expand");
54
59
  let typeElement = range.startContainer as HTMLElement;
55
60
  if (range.startContainer.nodeType === 3) {
56
61
  typeElement = range.startContainer.parentElement;
@@ -226,8 +231,6 @@ export const highlightToolbarWYSIWYG = (vditor: IVditor) => {
226
231
 
227
232
  // table popover
228
233
  if (tableElement) {
229
- const lang: keyof II18n | "" = vditor.options.lang;
230
- const options: IOptions = vditor.options;
231
234
  vditor.wysiwyg.popover.innerHTML = "";
232
235
  const updateTable = () => {
233
236
  const oldRow = tableElement.rows.length;
@@ -566,8 +569,6 @@ export const highlightToolbarWYSIWYG = (vditor: IVditor) => {
566
569
  // footnote popover
567
570
  const footnotesRefElement = hasClosestByAttribute(typeElement, "data-type", "footnotes-ref");
568
571
  if (footnotesRefElement) {
569
- const lang: keyof II18n | "" = vditor.options.lang;
570
- const options: IOptions = vditor.options;
571
572
  vditor.wysiwyg.popover.innerHTML = "";
572
573
 
573
574
  const inputWrap = document.createElement("span");
@@ -671,7 +672,7 @@ export const highlightToolbarWYSIWYG = (vditor: IVditor) => {
671
672
  event.key === "Escape" &&
672
673
  vditor.hint.element.style.display === "block"
673
674
  ) {
674
- vditor.hint.element.style.display = "none";
675
+ vditor.hint.hide();
675
676
  event.preventDefault();
676
677
  return;
677
678
  }