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,208 @@
1
+ interface IFindText {
2
+ node: Text;
3
+ start: number;
4
+ end: number;
5
+ }
6
+
7
+ interface IFindUnit {
8
+ text: string;
9
+ nodes: IFindText[];
10
+ }
11
+
12
+ const findPattern = (query: string, caseSensitive: boolean) =>
13
+ new RegExp(query.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), caseSensitive ? "gu" : "giu");
14
+
15
+ export const countMatches = (text: string, query: string, caseSensitive: boolean) => {
16
+ if (!query) return 0;
17
+ const pattern = findPattern(query, caseSensitive);
18
+ let count = 0;
19
+ while (pattern.exec(text)) count++;
20
+ return count;
21
+ };
22
+
23
+ const findUnits = (root: HTMLElement): IFindUnit[] => {
24
+ const units: IFindUnit[] = [];
25
+ let unit: IFindUnit = {text: "", nodes: []};
26
+ const flush = () => {
27
+ if (unit.text) units.push(unit);
28
+ unit = {text: "", nodes: []};
29
+ };
30
+ const walk = (node: Node) => {
31
+ if (node.nodeType === Node.TEXT_NODE) {
32
+ const text = node.textContent.replace(/\u200b/g, "");
33
+ if (text) {
34
+ unit.nodes.push({node: node as Text, start: unit.text.length, end: unit.text.length + text.length});
35
+ unit.text += text;
36
+ }
37
+ return;
38
+ }
39
+ if (!(node instanceof Element)) return;
40
+ if (node.matches(".vditor-ir__preview, .vditor-wysiwyg__preview, .vditor-wbr, " +
41
+ '.vditor-ir__marker:not(pre), [data-type="code-block-open-marker"], [data-type="code-block-close-marker"], ' +
42
+ '[data-type="code-block-info"], [data-type="backslash"] > span, input, button, script, style')) return;
43
+ if (node.matches('img, br, hr, [data-type="img"], [data-type="math-inline"], [data-type="math-block"], ' +
44
+ '[data-type="html-inline"], [data-type="html-block"], [data-type="toc-block"]')) {
45
+ flush();
46
+ return;
47
+ }
48
+ const block = node.matches("p, h1, h2, h3, h4, h5, h6, li, td, th, pre");
49
+ if (block) flush();
50
+ node.childNodes.forEach(walk);
51
+ if (block) flush();
52
+ };
53
+ root.childNodes.forEach(walk);
54
+ flush();
55
+ return units;
56
+ };
57
+
58
+ const findOffset = (node: Text, offset: number, end = false) => {
59
+ let count = 0;
60
+ for (let index = 0; index < node.length; index++) {
61
+ if (node.data[index] === "\u200b") continue;
62
+ if (count === offset) return index;
63
+ count++;
64
+ if (end && count === offset) return index + 1;
65
+ }
66
+ return node.length;
67
+ };
68
+
69
+ const findRange = (unit: IFindUnit, start: number, end: number) => {
70
+ const first = unit.nodes.find(item => item.end > start);
71
+ const last = unit.nodes.find(item => item.end >= end);
72
+ const range = first.node.ownerDocument.createRange();
73
+ range.setStart(first.node, findOffset(first.node, start - first.start));
74
+ range.setEnd(last.node, findOffset(last.node, end - last.start, true));
75
+ return range;
76
+ };
77
+
78
+ export const findText = (element: HTMLElement, query: string, caseSensitive: boolean, index = 0): IFindResult => {
79
+ if (!query) return {total: 0, index: -1};
80
+ const source = element instanceof HTMLTextAreaElement;
81
+ const units = source ? [{text: element.value, nodes: []}] : findUnits(element);
82
+ const pattern = findPattern(query, caseSensitive);
83
+ let total = 0;
84
+ let chosen: IFindResult["match"];
85
+ let first: IFindResult["match"];
86
+ for (const unit of units) {
87
+ pattern.lastIndex = 0;
88
+ let match: RegExpExecArray;
89
+ while ((match = pattern.exec(unit.text))) {
90
+ if (!first || total === index) {
91
+ const result = {start: match.index, end: match.index + match[0].length,
92
+ range: source ? undefined : findRange(unit, match.index, match.index + match[0].length)};
93
+ first = first || result;
94
+ if (total === index) chosen = result;
95
+ }
96
+ total++;
97
+ }
98
+ }
99
+ return {total, index: total ? chosen ? index : 0 : -1, match: chosen || first};
100
+ };
101
+
102
+ const normalizeCodeMarker = (code: HTMLElement) => {
103
+ const block = code.closest('[data-type="code-block"]');
104
+ const inline = code.parentElement.closest('[data-type="code"]');
105
+ const open = block ? block.querySelector('[data-type="code-block-open-marker"]') :
106
+ inline?.querySelector(".vditor-ir__marker");
107
+ const close = block ? block.querySelector('[data-type="code-block-close-marker"]') :
108
+ inline?.lastElementChild;
109
+ const container = block || code;
110
+ const original = container.getAttribute("data-marker") || open?.textContent.trim() || (block ? "```" : "`");
111
+ const runs: string[] = code.textContent.match(original[0] === "~" ? /~+/g : /`+/g) || [];
112
+ const width = runs.reduce((size, run) => Math.max(size, run.length + 1), original.length);
113
+ const marker = original[0].repeat(width);
114
+ const content = code.textContent.replace(/\u200b/g, "");
115
+ const padding = !block && (content.startsWith("`") || content.endsWith("`") ||
116
+ content.startsWith(" ") && content.endsWith(" ") && !/^ +$/.test(content)) ? " " : "";
117
+ // 替换内容中的分隔符必须短于代码边界,保存后才能按原内容读回。
118
+ if (open && close) {
119
+ open.textContent = marker + padding;
120
+ close.textContent = padding + marker;
121
+ } else {
122
+ container.setAttribute("data-marker", marker);
123
+ }
124
+ };
125
+
126
+ export const replaceText = (element: HTMLElement, query: string, replacement: string, caseSensitive: boolean,
127
+ index?: number): number => {
128
+ if (!query) return 0;
129
+ const pattern = findPattern(query, caseSensitive);
130
+ let count = 0;
131
+ let ordinal = 0;
132
+ const escapedReplacement = replacement.replace(/[\x21-\x2f\x3a-\x40\x5b-\x60\x7b-\x7e]/g, "\\$&");
133
+ if (element instanceof HTMLTextAreaElement) {
134
+ element.value = element.value.replace(pattern, value => {
135
+ const replace = index === undefined || ordinal === index;
136
+ ordinal++;
137
+ if (!replace) return value;
138
+ count++;
139
+ return replacement;
140
+ });
141
+ return count;
142
+ }
143
+ const codeNodes = new Set<HTMLElement>();
144
+ for (const unit of findUnits(element)) {
145
+ pattern.lastIndex = 0;
146
+ const edits = new Map<Text, Array<{start: number; end: number; text: string}>>();
147
+ let match: RegExpExecArray;
148
+ let cursor = 0;
149
+ while ((match = pattern.exec(unit.text))) {
150
+ const replace = index === undefined || ordinal === index;
151
+ ordinal++;
152
+ if (!replace) continue;
153
+ count++;
154
+ const start = match.index;
155
+ const end = start + match[0].length;
156
+ while (unit.nodes[cursor].end <= start) cursor++;
157
+ // 正文标点转为 Markdown 转义,代码内容由代码节点保留字面语义。
158
+ const text = unit.nodes[cursor].node.parentElement.closest("code") ? replacement : escapedReplacement;
159
+ for (let position = cursor; position < unit.nodes.length && unit.nodes[position].start < end; position++) {
160
+ const part = unit.nodes[position];
161
+ const list = edits.get(part.node) || [];
162
+ list.push({start: findOffset(part.node, Math.max(0, start - part.start)),
163
+ end: findOffset(part.node, Math.min(part.end, end) - part.start, true),
164
+ text: position === cursor ? text : ""});
165
+ edits.set(part.node, list);
166
+ }
167
+ }
168
+ edits.forEach((changes, node) => {
169
+ let offset = 0;
170
+ const fragments: string[] = [];
171
+ for (const change of changes) {
172
+ fragments.push(node.data.slice(offset, change.start), change.text);
173
+ offset = change.end;
174
+ }
175
+ fragments.push(node.data.slice(offset));
176
+ node.data = fragments.join("");
177
+ const code = node.parentElement.closest("code");
178
+ if (code) codeNodes.add(code);
179
+ const escaped = node.parentElement.closest('[data-type="backslash"]');
180
+ if (escaped) {
181
+ escaped.querySelector("span")?.remove();
182
+ escaped.replaceWith(...Array.from(escaped.childNodes));
183
+ }
184
+ });
185
+ }
186
+ codeNodes.forEach(normalizeCodeMarker);
187
+ return count;
188
+ };
189
+
190
+ export const displayRange = (range: Range): Range => {
191
+ const pre = range.startContainer.parentElement?.closest("pre");
192
+ const preview = pre?.nextElementSibling;
193
+ if (!preview?.matches(".vditor-code__preview")) return range;
194
+ const prefix = range.cloneRange();
195
+ prefix.selectNodeContents(pre);
196
+ prefix.setEnd(range.startContainer, range.startOffset);
197
+ const start = prefix.toString().length;
198
+ const unit: IFindUnit = {text: "", nodes: []};
199
+ const code = preview.querySelector("code");
200
+ if (!code) return range;
201
+ const walker = range.startContainer.ownerDocument.createTreeWalker(code, NodeFilter.SHOW_TEXT);
202
+ let node: Node;
203
+ while ((node = walker.nextNode())) {
204
+ unit.nodes.push({node: node as Text, start: unit.text.length, end: unit.text.length + node.textContent.length});
205
+ unit.text += node.textContent;
206
+ }
207
+ return unit.text.length >= start + range.toString().length ? findRange(unit, start, start + range.toString().length) : range;
208
+ };
@@ -13,6 +13,12 @@ export class Hint {
13
13
  public recentLanguage: string;
14
14
  private splitChar = "";
15
15
  private lastIndex = -1;
16
+ private requestId = 0;
17
+ private dismiss = (event: Event) => {
18
+ if (!this.element.contains(event.target as Node)) {
19
+ this.hide();
20
+ }
21
+ };
16
22
 
17
23
  constructor(hintExtends: IHintExtend[]) {
18
24
  this.timeId = -1;
@@ -20,25 +26,38 @@ export class Hint {
20
26
  this.element.className = "vditor-hint";
21
27
  this.recentLanguage = "";
22
28
  hintExtends.push({key: ":"});
29
+ document.addEventListener("pointerdown", this.dismiss, true);
30
+ document.addEventListener("focusin", this.dismiss, true);
31
+ this.element.addEventListener("pointerdown", event => event.preventDefault());
32
+ }
33
+
34
+ public hide() {
35
+ this.requestId++;
36
+ clearTimeout(this.timeId);
37
+ this.element.style.display = "none";
38
+ }
39
+
40
+ public destroy() {
41
+ this.hide();
42
+ document.removeEventListener("pointerdown", this.dismiss, true);
43
+ document.removeEventListener("focusin", this.dismiss, true);
23
44
  }
24
45
 
25
46
  public render(vditor: IVditor) {
47
+ this.hide();
26
48
  if (vditor.currentMode === "sv") {
27
- this.element.style.display = "none";
28
49
  return;
29
50
  }
30
51
  if (!window.getSelection().focusNode) {
31
52
  return;
32
53
  }
33
- let currentLineValue: string;
34
54
  const range = getSelection().getRangeAt(0);
35
- currentLineValue = range.startContainer.textContent.substring(0, range.startOffset) || "";
55
+ const currentLineValue = range.startContainer.textContent.substring(0, range.startOffset) || "";
36
56
 
37
57
  const key = this.getKey(currentLineValue, vditor.options.hint.extend);
38
58
 
39
59
  if (typeof key === "undefined") {
40
- this.element.style.display = "none";
41
- clearTimeout(this.timeId);
60
+ return;
42
61
  } else {
43
62
  if (this.splitChar === ":") {
44
63
  const emojiHint = key === "" ? vditor.options.hint.emoji : vditor.lute.GetEmojis();
@@ -63,8 +82,12 @@ export class Hint {
63
82
  vditor.options.hint.extend.forEach((item) => {
64
83
  if (item.key === this.splitChar) {
65
84
  clearTimeout(this.timeId);
85
+ const requestId = this.requestId;
66
86
  this.timeId = window.setTimeout(async () => {
67
- this.genHTML(await item.hint(key), key, vditor);
87
+ const data = await item.hint(key);
88
+ if (requestId === this.requestId) {
89
+ this.genHTML(data, key, vditor);
90
+ }
68
91
  }, vditor.options.hint.delay);
69
92
  }
70
93
  });
@@ -74,7 +97,7 @@ export class Hint {
74
97
 
75
98
  public genHTML(data: IHintData[], key: string, vditor: IVditor) {
76
99
  if (data.length === 0) {
77
- this.element.style.display = "none";
100
+ this.hide();
78
101
  return;
79
102
  }
80
103
 
@@ -131,7 +154,7 @@ ${i === 0 ? "class='vditor-hint--current'" : ""}> ${html}</button>`;
131
154
  }
132
155
 
133
156
  public fillEmoji = (element: HTMLElement, vditor: IVditor) => {
134
- this.element.style.display = "none";
157
+ this.hide();
135
158
  if (vditor.currentMode === "sv") {
136
159
  return;
137
160
  }
@@ -1,5 +1,6 @@
1
1
  import {hasClosestByClassName, hasTopClosestByClassName} from "../util/hasClosest";
2
2
  import {setSelectionFocus} from "../util/selection";
3
+ import {expandHTMLTags} from "../util/expandHTMLTags";
3
4
 
4
5
  const nextIsNode = (range: Range) => {
5
6
  const startContainer = range.startContainer;
@@ -63,6 +64,8 @@ export const expandMarker = (range: Range, vditor: IVditor) => {
63
64
  setSelectionFocus(range);
64
65
  }
65
66
 
67
+ expandHTMLTags(vditor.ir.element, range, "vditor-ir__node--expand");
68
+
66
69
  const nextNode = nextIsNode(range);
67
70
  if (nextNode) {
68
71
  nextNode.classList.add("vditor-ir__node--expand");
@@ -1,5 +1,6 @@
1
1
  import {Constants} from "../constants";
2
2
  import {isCtrl, isFirefox} from "../util/compatibility";
3
+ import {buildTableSelectionClipboard} from "../util/pasteIntoTable";
3
4
  import {
4
5
  blurEvent,
5
6
  copyEvent, cutEvent, dblclickEvent,
@@ -49,6 +50,7 @@ class IR {
49
50
  public range: Range;
50
51
  public element: HTMLPreElement;
51
52
  public processTimeoutId: number;
53
+ public pendingUndoStack = false;
52
54
  public hlToolbarTimeoutId: number;
53
55
  public composingLock: boolean = false;
54
56
  public preventInput: boolean;
@@ -82,6 +84,13 @@ class IR {
82
84
  event.stopPropagation();
83
85
  event.preventDefault();
84
86
 
87
+ const tableClip = buildTableSelectionClipboard(vditor, range);
88
+ if (tableClip) {
89
+ event.clipboardData.setData("text/html", tableClip.html);
90
+ event.clipboardData.setData("text/plain", tableClip.plain);
91
+ return;
92
+ }
93
+
85
94
  const tempElement = document.createElement("div");
86
95
  tempElement.appendChild(range.cloneContents());
87
96
  const copiedHeadings = tempElement.querySelectorAll<HTMLElement>("h1, h2, h3, h4, h5, h6");
@@ -105,15 +114,18 @@ class IR {
105
114
  hidePanel(vditor, ["hint"]);
106
115
  });
107
116
 
108
- this.element.addEventListener("compositionstart", (event: InputEvent) => {
117
+ this.element.addEventListener("compositionstart", () => {
109
118
  this.composingLock = true;
110
119
  });
111
120
 
112
- this.element.addEventListener("compositionend", (event: InputEvent) => {
121
+ this.element.addEventListener("compositionend", () => {
113
122
  if (!isFirefox()) {
114
123
  input(vditor, getSelection().getRangeAt(0).cloneRange());
115
124
  }
116
125
  this.composingLock = false;
126
+ if (vditor.options.undoDelay === 0 && !isFirefox()) {
127
+ vditor.undo.addToUndoStack(vditor);
128
+ }
117
129
  });
118
130
 
119
131
  this.element.addEventListener("input", (event: InputEvent) => {
@@ -179,7 +191,8 @@ class IR {
179
191
  }
180
192
  // 打开链接
181
193
  const aElement = hasClosestByAttribute(event.target, "data-type", "a");
182
- if (aElement && (!aElement.classList.contains("vditor-ir__node--expand"))) {
194
+ if (aElement && (vditor.options.link.ctrlClick ? isCtrl(event) :
195
+ !aElement.classList.contains("vditor-ir__node--expand"))) {
183
196
  if (vditor.options.link.click) {
184
197
  vditor.options.link.click(aElement.querySelector(":scope > .vditor-ir__marker--link"));
185
198
  } else if (vditor.options.link.isOpen) {
@@ -42,13 +42,19 @@ export const processAfterRender = (vditor: IVditor, options = {
42
42
  enableHint: false,
43
43
  enableInput: true,
44
44
  }) => {
45
+ vditor.ir.pendingUndoStack = options.enableAddUndoStack && vditor.options.undoDelay !== 0;
45
46
  renderImageCaptions(vditor.ir.element, "ir", vditor.options.preview.markdown.imageCaption);
47
+ if (options.enableAddUndoStack && vditor.options.undoDelay === 0) {
48
+ vditor.undo.addToUndoStack(vditor);
49
+ }
46
50
  if (options.enableHint) {
47
51
  processHint(vditor);
48
52
  }
49
53
 
50
54
  clearTimeout(vditor.ir.processTimeoutId);
51
55
  vditor.ir.processTimeoutId = window.setTimeout(() => {
56
+ vditor.ir.processTimeoutId = 0;
57
+ vditor.ir.pendingUndoStack = false;
52
58
  if (vditor.ir.composingLock) {
53
59
  return;
54
60
  }
@@ -72,7 +78,7 @@ export const processAfterRender = (vditor: IVditor, options = {
72
78
  vditor.devtools.renderEchart(vditor);
73
79
  }
74
80
 
75
- if (options.enableAddUndoStack) {
81
+ if (options.enableAddUndoStack && vditor.options.undoDelay !== 0) {
76
82
  vditor.undo.addToUndoStack(vditor);
77
83
  }
78
84
  }, vditor.options.undoDelay);
@@ -2,6 +2,7 @@ import {Constants} from "../constants";
2
2
  import {hidePanel} from "../toolbar/setToolbar";
3
3
  import {isCtrl} from "../util/compatibility";
4
4
  import {
5
+ backspaceEmptyHeading,
5
6
  fixBlockquote, fixCJKPosition,
6
7
  fixCodeBlock, fixCursorDownInlineMath,
7
8
  fixDelete, fixFirefoxArrowUpTable, fixGSKeyBackspace, fixHR,
@@ -40,6 +41,10 @@ export const processKeydown = (vditor: IVditor, event: KeyboardEvent) => {
40
41
  const range = getEditorRange(vditor);
41
42
  const startContainer = range.startContainer;
42
43
 
44
+ if (backspaceEmptyHeading(event, vditor, range)) {
45
+ return true;
46
+ }
47
+
43
48
  if (!fixGSKeyBackspace(event, vditor, startContainer)) {
44
49
  return false;
45
50
  }
@@ -4,9 +4,14 @@ import {chartRenderAdapter} from "./adapterRender";
4
4
  import {looseJsonParse} from "../util/function";
5
5
 
6
6
  declare const echarts: {
7
- init(element: HTMLElement, theme?: string): IEChart;
7
+ init(element: HTMLElement, theme?: string): IEChart & {dispose(): void};
8
8
  };
9
9
 
10
+ const charts = new WeakMap<HTMLElement, {
11
+ instance: IEChart & {dispose(): void},
12
+ observer?: ResizeObserver,
13
+ }>();
14
+
10
15
  export const chartRender = (element: (HTMLElement | Document) = document, cdn = Constants.CDN, theme: string) => {
11
16
  const echartsElements = chartRenderAdapter.getElements(element);
12
17
  if (echartsElements.length > 0) {
@@ -26,7 +31,28 @@ export const chartRender = (element: (HTMLElement | Document) = document, cdn =
26
31
  return;
27
32
  }
28
33
  const option = await looseJsonParse(text);
29
- echarts.init(e, theme === "dark" ? "dark" : undefined).setOption(option);
34
+ const previous = charts.get(e);
35
+ previous?.observer?.disconnect();
36
+ previous?.instance.dispose();
37
+ const instance = echarts.init(e, theme === "dark" ? "dark" : undefined);
38
+ instance.setOption(option);
39
+ const state: {instance: typeof instance, observer?: ResizeObserver} = {instance};
40
+ if (typeof ResizeObserver !== "undefined") {
41
+ state.observer = new ResizeObserver(() => {
42
+ if (!e.isConnected) {
43
+ state.observer.disconnect();
44
+ instance.dispose();
45
+ charts.delete(e);
46
+ e.removeAttribute("data-processed");
47
+ return;
48
+ }
49
+ if (e.clientWidth > 0 && e.clientHeight > 0) {
50
+ instance.resize();
51
+ }
52
+ });
53
+ state.observer.observe(e);
54
+ }
55
+ charts.set(e, state);
30
56
  e.setAttribute("data-processed", "true");
31
57
  } catch (error) {
32
58
  e.className = "vditor-reset--error";
@@ -0,0 +1,41 @@
1
+ // Bind outside HTML attributes so strict CSP and restored undo snapshots work alike.
2
+ export const bindCodeCopy = (menu: HTMLElement, textarea: HTMLTextAreaElement, button: HTMLElement) => {
3
+ const doc = menu.ownerDocument;
4
+ const label = window.VditorI18n?.copy || "复制";
5
+ button.setAttribute("aria-label", label);
6
+ button.setAttribute("role", "button");
7
+ button.tabIndex = 0;
8
+ button.addEventListener("mouseover", () => button.setAttribute("aria-label", label));
9
+ const copy = (event: Event) => {
10
+ event.preventDefault();
11
+ event.stopPropagation();
12
+ const active = doc.activeElement;
13
+ const input = active instanceof HTMLInputElement || active instanceof HTMLTextAreaElement ? active : undefined;
14
+ const inputSelection = input && input.selectionStart !== null ?
15
+ {start: input.selectionStart, end: input.selectionEnd, direction: input.selectionDirection} : undefined;
16
+ const selection = doc.getSelection();
17
+ const ranges = Array.from({length: selection?.rangeCount || 0}, (_, index) => selection.getRangeAt(index).cloneRange());
18
+ button.setAttribute("aria-label", label);
19
+ let copied = false;
20
+ try {
21
+ textarea.select();
22
+ copied = doc.execCommand("copy");
23
+ } finally {
24
+ textarea.blur();
25
+ if (active instanceof HTMLElement && active.isConnected) active.focus({preventScroll: true});
26
+ selection?.removeAllRanges();
27
+ ranges.forEach(range => selection?.addRange(range));
28
+ if (inputSelection && input.isConnected) {
29
+ input.setSelectionRange(inputSelection.start, inputSelection.end, inputSelection.direction);
30
+ }
31
+ }
32
+ if (copied) {
33
+ button.setAttribute("aria-label", window.VditorI18n?.copied || "已复制");
34
+ button.dispatchEvent(new CustomEvent("vditor-copy-success", {bubbles: true, detail: {label}}));
35
+ }
36
+ };
37
+ button.addEventListener("click", copy);
38
+ button.addEventListener("keydown", event => {
39
+ if (event.key === "Enter" || event.key === " ") copy(event);
40
+ });
41
+ };
@@ -1,6 +1,10 @@
1
1
  import {code160to32} from "../util/code160to32";
2
+ import {bindCodeCopy} from "./codeCopy";
3
+
2
4
  import {Constants} from "../constants";
3
5
 
6
+ const initializedMenus = new WeakSet<HTMLElement>();
7
+
4
8
  export const codeRender = (element: HTMLElement, option?: IHljs) => {
5
9
  Array.from<HTMLElement>(element.querySelectorAll("pre > code")).filter((e, index) => {
6
10
  if (e.parentElement.classList.contains("vditor-wysiwyg__pre") ||
@@ -15,9 +19,6 @@ export const codeRender = (element: HTMLElement, option?: IHljs) => {
15
19
  return false;
16
20
  }
17
21
 
18
- if (e.style.maxHeight.indexOf("px") > -1) {
19
- return false;
20
- }
21
22
 
22
23
  // 避免预览区在渲染后由于代码块过多产生性能问题 https://github.com/b3log/vditor/issues/67
23
24
  if (element.classList.contains("vditor-preview") && index > 5) {
@@ -25,6 +26,11 @@ export const codeRender = (element: HTMLElement, option?: IHljs) => {
25
26
  }
26
27
  return true;
27
28
  }).forEach((e) => {
29
+ const previous = e.previousElementSibling as HTMLElement;
30
+ if (previous?.classList.contains("vditor-copy")) {
31
+ if (initializedMenus.has(previous)) return;
32
+ previous.remove();
33
+ }
28
34
  let codeText = e.innerText;
29
35
  if (e.classList.contains("highlight-chroma")) {
30
36
  const codeElement = e.cloneNode(true) as HTMLElement;
@@ -42,19 +48,24 @@ export const codeRender = (element: HTMLElement, option?: IHljs) => {
42
48
 
43
49
  const divElement = document.createElement("div");
44
50
  divElement.className = "vditor-copy";
45
- divElement.innerHTML = `<span aria-label="${window.VditorI18n?.copy || "复制"}"
46
- onmouseover="this.setAttribute('aria-label', '${window.VditorI18n?.copy || "复制"}')"
47
- class="vditor-tooltipped vditor-tooltipped__w"
48
- onclick="event.stopPropagation();this.previousElementSibling.select();document.execCommand('copy');this.setAttribute('aria-label', '${window.VditorI18n?.copied || "已复制"}');this.previousElementSibling.blur()">${iconHTML}</span>`;
51
+ const button = document.createElement("span");
52
+ button.className = "vditor-tooltipped vditor-tooltipped__w";
53
+ button.innerHTML = iconHTML;
54
+ divElement.appendChild(button);
49
55
  const textarea = document.createElement("textarea");
50
56
  textarea.value = code160to32(codeText);
51
57
  divElement.insertAdjacentElement("afterbegin", textarea);
58
+ bindCodeCopy(divElement, textarea, button);
59
+ initializedMenus.add(divElement);
52
60
  if (option && option.renderMenu) {
53
61
  option.renderMenu(e, divElement);
54
62
  }
55
63
  e.before(divElement);
56
64
  e.style.maxHeight = (window.outerHeight - 40) + "px";
57
65
  // https://github.com/Vanessa219/vditor/issues/1356
58
- e.insertAdjacentHTML("afterend", `<span style="position: absolute">${Constants.ZWSP}</span>`)
66
+ if (!(e.nextElementSibling?.textContent === Constants.ZWSP &&
67
+ (e.nextElementSibling as HTMLElement).style.position === "absolute")) {
68
+ e.insertAdjacentHTML("afterend", `<span style="position: absolute">${Constants.ZWSP}</span>`);
69
+ }
59
70
  });
60
71
  };