vditor 4.0.2-alpha.2 → 4.0.2-alpha.3

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.
@@ -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,9 +1,10 @@
1
1
  import {Constants} from "../constants";
2
2
  import {addScript} from "../util/addScript";
3
3
  import {addStyle} from "../util/addStyle";
4
+ import {setCodeHighlight} from "../util/codeSelection";
4
5
 
5
6
  export const highlightRender = (hljsOption?: IHljs, element: HTMLElement | Document = document,
6
- cdn = Constants.CDN) => {
7
+ cdn = Constants.CDN, canRenderEditable?: () => boolean) => {
7
8
  let style = hljsOption.style;
8
9
  if (!Constants.CODE_THEME.includes(style)) {
9
10
  style = "github";
@@ -27,9 +28,11 @@ export const highlightRender = (hljsOption?: IHljs, element: HTMLElement | Docum
27
28
  addScript(`${cdn}/dist/js/highlight.js/highlight.min.js?v=11.7.0`, "vditorHljsScript").then(() => {
28
29
  addScript(`${cdn}/dist/js/highlight.js/third-languages.js?v=1.0.1`, "vditorHljsThirdScript").then(() => {
29
30
  element.querySelectorAll("pre > code").forEach((block) => {
30
- // ir & wysiwyg 区域不渲染
31
- if (block.parentElement.classList.contains("vditor-ir__marker--pre") ||
32
- block.parentElement.classList.contains("vditor-wysiwyg__pre")) {
31
+ if (canRenderEditable && (!canRenderEditable() || block.querySelector("wbr"))) {
32
+ return;
33
+ }
34
+ if (!canRenderEditable && (block.parentElement.classList.contains("vditor-ir__marker--pre") ||
35
+ block.parentElement.classList.contains("vditor-wysiwyg__pre"))) {
33
36
  return;
34
37
  }
35
38
 
@@ -41,23 +44,29 @@ export const highlightRender = (hljsOption?: IHljs, element: HTMLElement | Docum
41
44
  return;
42
45
  }
43
46
 
44
- if (hljsOption.defaultLang !== "" && block.className.indexOf("language-") === -1) {
45
- block.classList.add("language-" + hljsOption.defaultLang)
47
+ if (!canRenderEditable && hljsOption.defaultLang !== "" && block.className.indexOf("language-") === -1) {
48
+ block.classList.add("language-" + hljsOption.defaultLang);
46
49
  }
47
-
48
- let language = block.className.replace("language-", "");
50
+ let language = Array.from(block.classList).find(name => name.startsWith("language-"))?.slice(9) ||
51
+ hljsOption.defaultLang;
49
52
  if (!window.hljs.getLanguage(language)) {
50
53
  language = "plaintext";
51
54
  }
52
- block.innerHTML = window.hljs.highlight(
55
+ const html = window.hljs.highlight(
53
56
  block.textContent,
54
57
  {
55
58
  language,
56
59
  ignoreIllegals: true
57
60
  }).value;
61
+ if (canRenderEditable) {
62
+ block.setAttribute("data-code-highlight", "true");
63
+ setCodeHighlight(block, html);
64
+ } else {
65
+ block.innerHTML = html;
66
+ }
58
67
 
59
68
  block.classList.add("hljs");
60
- if (!hljsOption.lineNumber) {
69
+ if (canRenderEditable || !hljsOption.lineNumber) {
61
70
  return;
62
71
  }
63
72
 
@@ -1,3 +1,5 @@
1
+ import {normalizeCodeHTML} from "../util/codeDOM";
2
+
1
3
  export const setLute = (options: ILuteOptions) => {
2
4
  const lute: Lute = Lute.New();
3
5
  lute.PutEmojis(options.emojis);
@@ -24,5 +26,12 @@ export const setLute = (options: ILuteOptions) => {
24
26
  }
25
27
  lute.SetSup(options.sup);
26
28
  lute.SetSub(options.sub);
29
+ // 编辑区的高亮是临时展示,传入 Lute 的代码正文需保留纯文本和光标标记。
30
+ const conversions = ["SpinVditorDOM", "SpinVditorIRDOM", "VditorDOM2Md", "VditorIRDOM2Md",
31
+ "VditorDOM2HTML", "VditorIRDOM2HTML"] as const;
32
+ conversions.forEach(name => {
33
+ const convert = lute[name].bind(lute);
34
+ lute[name] = (html: string) => convert(normalizeCodeHTML(html));
35
+ });
27
36
  return lute;
28
37
  };
@@ -85,7 +85,7 @@ export const hidePanel = (vditor: IVditor, panels: string[], exceptElement?: HTM
85
85
  }
86
86
  }
87
87
  if (panels.includes("hint")) {
88
- vditor.hint.element.style.display = "none";
88
+ vditor.hint.hide();
89
89
  }
90
90
  if (vditor.wysiwyg.popover && panels.includes("popover")) {
91
91
  vditor.wysiwyg.popover.style.display = "none";
@@ -4,7 +4,8 @@ import {isFirefox, isSafari} from "../util/compatibility";
4
4
  import {scrollCenter} from "../util/editorCommonEvent";
5
5
  import {execAfterRender} from "../util/fixBrowserBehavior";
6
6
  import {highlightToolbar} from "../util/highlightToolbar";
7
- import {processCodeRender} from "../util/processCode";
7
+ import {highlightEditableCode, processCodeRender} from "../util/processCode";
8
+ import {normalizeCodeDOM} from "../util/codeDOM";
8
9
  import {setRangeByWbr, setSelectionFocus} from "../util/selection";
9
10
  import {renderToc} from "../util/toc";
10
11
 
@@ -205,6 +206,8 @@ class Undo {
205
206
  .forEach((item: HTMLElement) => {
206
207
  processCodeRender(item, vditor);
207
208
  });
209
+ vditor[vditor.currentMode].element.querySelectorAll(".vditor-code__preview")
210
+ .forEach((item: HTMLElement) => highlightEditableCode(item, vditor));
208
211
 
209
212
  if (this[vditor.currentMode].undoStack.length > 1) {
210
213
  enableToolbar(vditor.toolbar.elements, ["undo"]);
@@ -258,6 +261,7 @@ class Undo {
258
261
  }
259
262
  // 移除数学公式、echart 渲染 https://github.com/Vanessa219/vditor/issues/1738
260
263
  const cloneElement = vditor[vditor.currentMode].element.cloneNode(true) as HTMLElement;
264
+ normalizeCodeDOM(cloneElement);
261
265
  cloneElement.querySelectorAll(`.vditor-${vditor.currentMode}__preview[data-render='1']`)
262
266
  .forEach((item: HTMLElement) => {
263
267
  if (!item.firstElementChild) {
@@ -0,0 +1,21 @@
1
+ export const normalizeCodeDOM = (element: HTMLElement) => {
2
+ element.querySelectorAll("code[data-code-highlight]").forEach(code => {
3
+ code.removeAttribute("data-code-highlight");
4
+ code.classList.remove("hljs");
5
+ code.querySelectorAll("span").forEach(span => {
6
+ if (!span.classList.contains("vditor-wbr")) {
7
+ span.replaceWith(...Array.from(span.childNodes));
8
+ }
9
+ });
10
+ });
11
+ };
12
+
13
+ export const normalizeCodeHTML = (html: string) => {
14
+ if (!html.includes("data-code-highlight")) {
15
+ return html;
16
+ }
17
+ const element = document.createElement("div");
18
+ element.innerHTML = html;
19
+ normalizeCodeDOM(element);
20
+ return element.innerHTML;
21
+ };
@@ -0,0 +1,37 @@
1
+ export const setCodeHighlight = (code: Element, html: string) => {
2
+ const selection = getSelection();
3
+ const endpoints = [selection.anchorNode, selection.focusNode].map((node, index) => {
4
+ const offset = index === 0 ? selection.anchorOffset : selection.focusOffset;
5
+ if (!node || !code.contains(node)) {
6
+ return {node, offset, inside: false};
7
+ }
8
+ const range = document.createRange();
9
+ range.selectNodeContents(code);
10
+ range.setEnd(node, offset);
11
+ return {node, offset: range.toString().length, inside: true};
12
+ });
13
+ code.innerHTML = html;
14
+ if (!endpoints.some(endpoint => endpoint.inside)) {
15
+ return;
16
+ }
17
+
18
+ // 高亮会重建嵌套文本节点,按正文偏移恢复正向、反向及跨代码块选区。
19
+ endpoints.forEach(endpoint => {
20
+ if (!endpoint.inside) {
21
+ return;
22
+ }
23
+ const walker = document.createTreeWalker(code, NodeFilter.SHOW_TEXT);
24
+ let node = walker.nextNode();
25
+ while (node) {
26
+ if (endpoint.offset <= node.textContent.length) {
27
+ endpoint.node = node;
28
+ return;
29
+ }
30
+ endpoint.offset -= node.textContent.length;
31
+ node = walker.nextNode();
32
+ }
33
+ endpoint.node = code;
34
+ endpoint.offset = code.childNodes.length;
35
+ });
36
+ selection.setBaseAndExtent(endpoints[0].node, endpoints[0].offset, endpoints[1].node, endpoints[1].offset);
37
+ };
@@ -175,7 +175,7 @@ export const hotkeyEvent = (vditor: IVditor, editorElement: HTMLElement) => {
175
175
  // esc
176
176
  if (event.key === "Escape") {
177
177
  if (vditor.hint.element.style.display === "block") {
178
- vditor.hint.element.style.display = "none";
178
+ vditor.hint.hide();
179
179
  } else if (vditor.options.esc && !event.isComposing) {
180
180
  vditor.options.esc(getMarkdown(vditor));
181
181
  }
@@ -56,6 +56,16 @@ export const processPasteCode = (html: string, text: string, type = "sv") => {
56
56
  return false;
57
57
  };
58
58
 
59
+ export const highlightEditableCode = (previewPanel: HTMLElement, vditor: IVditor) => {
60
+ const source = previewPanel.previousElementSibling as HTMLElement;
61
+ const mode = vditor.currentMode;
62
+ if (source?.tagName === "PRE" && mode !== "sv") {
63
+ highlightRender(vditor.options.preview.hljs, source, vditor.options.cdn, () =>
64
+ vditor.currentMode === mode && !vditor[mode].composingLock &&
65
+ vditor[mode].element.contains(source));
66
+ }
67
+ };
68
+
59
69
  export const processCodeRender = (previewPanel: HTMLElement, vditor: IVditor) => {
60
70
  if (!previewPanel) {
61
71
  return;
@@ -65,7 +75,8 @@ export const processCodeRender = (previewPanel: HTMLElement, vditor: IVditor) =>
65
75
  previewPanel.setAttribute("data-render", "1");
66
76
  return;
67
77
  }
68
- const language = previewPanel.firstElementChild.className.replace("language-", "");
78
+ const language = previewPanel.firstElementChild.className.split(/\s+/)
79
+ .find(name => name.startsWith("language-"))?.slice(9) || "";
69
80
  if (language === "abc") {
70
81
  abcRender(previewPanel, vditor.options.cdn);
71
82
  } else if (language === "mermaid") {
@@ -97,6 +108,7 @@ export const processCodeRender = (previewPanel: HTMLElement, vditor: IVditor) =>
97
108
  })
98
109
  if (!cRender) {
99
110
  previewPanel.classList.add("vditor-code__preview");
111
+ highlightEditableCode(previewPanel, vditor);
100
112
  highlightRender(Object.assign({}, vditor.options.preview.hljs), previewPanel, vditor.options.cdn);
101
113
  codeRender(previewPanel, vditor.options.preview.hljs);
102
114
  }
@@ -671,7 +671,7 @@ export const highlightToolbarWYSIWYG = (vditor: IVditor) => {
671
671
  event.key === "Escape" &&
672
672
  vditor.hint.element.style.display === "block"
673
673
  ) {
674
- vditor.hint.element.style.display = "none";
674
+ vditor.hint.hide();
675
675
  event.preventDefault();
676
676
  return;
677
677
  }