kyle-editor 1.0.6 → 1.0.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.
- package/README.md +232 -30
- package/dist/keditor-vue.cjs +3 -2
- package/dist/keditor-vue.es.js +3 -2
- package/dist/keditor-vue.umd.js +3 -2
- package/dist/keditor.cjs +2814 -521
- package/dist/keditor.es.js +2814 -521
- package/dist/keditor.umd.js +2812 -519
- package/dist/keditor.umd.min.js +109 -6
- package/docs/api.md +108 -15
- package/docs/integration.md +24 -14
- package/docs/upload-adapter.md +203 -94
- package/package.json +2 -3
- package/types/index.d.ts +273 -23
- package/types/vue.d.ts +2 -2
- package/docs/index.md +0 -8
- package/imgs/img.png +0 -0
- package/imgs/img_1.png +0 -0
- package/imgs/img_2.png +0 -0
- package/imgs/img_3.png +0 -0
package/dist/keditor.es.js
CHANGED
|
@@ -26,6 +26,9 @@ const CSS$1 = `
|
|
|
26
26
|
}
|
|
27
27
|
.ke[hidden] { display: none; }
|
|
28
28
|
.ke-is-fullscreen { position: fixed; inset: 0; z-index: 9998; border-radius: 0; }
|
|
29
|
+
/* 自适应高度(未配 height):整页滚动;overflow:clip 不建立滚动容器,
|
|
30
|
+
工具栏的 sticky 才能相对视口生效(旧浏览器忽略 clip,退回 hidden 行为) */
|
|
31
|
+
.ke.ke-is-auto { overflow: clip; }
|
|
29
32
|
|
|
30
33
|
/* ---------------- Toolbar ---------------- */
|
|
31
34
|
.ke-tb {
|
|
@@ -209,6 +212,56 @@ const CSS$1 = `
|
|
|
209
212
|
.ke-panel-icon + .ke-panel-note { margin-left: 8px; }
|
|
210
213
|
|
|
211
214
|
.ke-panel-select .ke-sel-search { margin-bottom: 8px; }
|
|
215
|
+
.ke-code-panel .ke-sel-search { margin-bottom: 8px; }
|
|
216
|
+
.ke-code-list { display: flex; flex-direction: column; max-height: 252px; overflow-y: auto; overscroll-behavior: contain; margin: 0 -4px; padding: 0 4px; }
|
|
217
|
+
.ke-code-panel .ke-panel-hint { margin-top: 10px; }
|
|
218
|
+
|
|
219
|
+
/* ---------------- Markdown 导入面板 ---------------- */
|
|
220
|
+
/* 固定宽度:预览里的表格 / 长链接不再把弹层撑宽 */
|
|
221
|
+
.ke-md-panel {
|
|
222
|
+
width: 372px; max-width: calc(100vw - 24px);
|
|
223
|
+
display: flex; flex-direction: column; padding-bottom: 0;
|
|
224
|
+
max-height: var(--ke-pop-max, 560px);
|
|
225
|
+
}
|
|
226
|
+
.ke-md-panel .ke-panel-head, .ke-md-panel .ke-tabs { flex: none; }
|
|
227
|
+
.ke-md-panel .ke-tabs { margin-bottom: 0; }
|
|
228
|
+
/* 中间区滚动、底部按钮常驻:窗口再矮也能点到「导入到正文」 */
|
|
229
|
+
.ke-md-body { flex: 1 1 auto; min-height: 0; overflow-y: auto; overscroll-behavior: contain; margin: 0 -14px; padding: 12px 14px 0; }
|
|
230
|
+
.ke-md-panel .ke-panel-foot { flex: none; margin: 10px 0 12px; }
|
|
231
|
+
.ke-md-text {
|
|
232
|
+
width: 100%; min-height: 118px; max-height: 190px; padding: 10px 11px; border: 1px solid var(--ke-line);
|
|
233
|
+
border-radius: 8px; background: #fbfcfd; color: #1f2329; font-size: 12.5px; line-height: 1.7; resize: vertical;
|
|
234
|
+
font-family: 'SFMono-Regular', Consolas, Menlo, Monaco, monospace; outline: none;
|
|
235
|
+
}
|
|
236
|
+
.ke-md-text:focus { border-color: var(--ke-primary); background: #fff; }
|
|
237
|
+
.ke-md-file { display: flex; align-items: center; gap: 8px; margin-top: 8px; font-size: 12px; color: var(--ke-muted); }
|
|
238
|
+
.ke-md-file b { flex: 1 1 auto; min-width: 0; color: #1f2329; font-weight: 600; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
|
239
|
+
.ke-md-file > span { flex: none; }
|
|
240
|
+
.ke-drop-title, .ke-drop-sub { overflow-wrap: anywhere; }
|
|
241
|
+
.ke-md-file[hidden] { display: none; }
|
|
242
|
+
.ke-md-error { color: #e53e3e; }
|
|
243
|
+
.ke-md-modes { display: flex; gap: 6px; }
|
|
244
|
+
.ke-md-mode { flex: 1; height: 28px; border: 1px solid var(--ke-line); border-radius: 7px; background: #fff; color: #4b5158; font-size: 12px; cursor: pointer; }
|
|
245
|
+
.ke-md-mode:hover { border-color: var(--ke-primary); color: var(--ke-primary); }
|
|
246
|
+
.ke-md-mode.ke-is-active { border-color: var(--ke-primary); background: var(--ke-primary-weak); color: var(--ke-primary); font-weight: 600; }
|
|
247
|
+
/* 预览复用正文样式(ke-content),只是尺寸更紧凑 */
|
|
248
|
+
.ke-md-preview {
|
|
249
|
+
max-height: 216px; overflow: auto; overscroll-behavior: contain;
|
|
250
|
+
padding: 10px 12px; border: 1px solid var(--ke-line-weak); border-radius: 8px; background: #fff;
|
|
251
|
+
font-size: 14px; line-height: 1.7; overflow-wrap: anywhere;
|
|
252
|
+
}
|
|
253
|
+
.ke-md-preview > *:last-child { margin-bottom: 0; }
|
|
254
|
+
.ke-md-preview h1, .ke-md-preview h2, .ke-md-preview h3, .ke-md-preview h4 { margin: 12px 0 8px; font-size: 16px; }
|
|
255
|
+
.ke-md-preview p { margin: 0 0 8px; }
|
|
256
|
+
.ke-md-preview ul, .ke-md-preview ol { margin: 0 0 8px; padding-left: 20px; }
|
|
257
|
+
.ke-md-preview blockquote { margin: 0 0 8px; padding: 1px 12px; }
|
|
258
|
+
.ke-md-preview pre { margin: 0 0 8px; padding: 9px 11px; font-size: 12px; }
|
|
259
|
+
.ke-md-preview table { font-size: 13px; }
|
|
260
|
+
.ke-md-preview th, .ke-md-preview td { padding: 4px 7px; }
|
|
261
|
+
.ke-md-empty { color: #b8bec7; font-size: 12.5px; }
|
|
262
|
+
.ke-md-stats { display: flex; flex-wrap: wrap; gap: 3px 10px; margin-top: 8px; font-size: 11.5px; color: #a2a8b3; }
|
|
263
|
+
.ke-md-stat b { color: #4b5158; font-weight: 600; }
|
|
264
|
+
.ke-md-panel .ke-panel-hint { margin-top: 0; }
|
|
212
265
|
.ke-sel-body { max-height: 268px; overflow-y: auto; overscroll-behavior: contain; margin: 0 -4px; padding: 0 4px; }
|
|
213
266
|
.ke-sel-row {
|
|
214
267
|
display: flex; align-items: center; gap: 8px; width: 100%;
|
|
@@ -310,10 +363,36 @@ const CSS$1 = `
|
|
|
310
363
|
.ke-content hr { border: 0; border-top: 1px solid var(--ke-line); margin: 24px 0; }
|
|
311
364
|
.ke-content code { background: #f2f3f5; border-radius: 4px; padding: 2px 6px; font-size: 14px; font-family: 'SFMono-Regular', Consolas, Menlo, monospace; color: #c7254e; }
|
|
312
365
|
.ke-content pre {
|
|
366
|
+
position: relative;
|
|
313
367
|
background: #282c34; color: #e6e6e6; padding: 14px 16px; border-radius: 8px; overflow-x: auto;
|
|
314
368
|
font-size: 13px; line-height: 1.7; margin: 0 0 16px; font-family: 'SFMono-Regular', Consolas, Menlo, monospace;
|
|
315
369
|
}
|
|
316
370
|
.ke-content pre code { background: none; color: inherit; padding: 0; font-size: inherit; }
|
|
371
|
+
/* 右上角语言角标:纯 CSS(::before)不进入正文 DOM,导出到公众号时自然消失 */
|
|
372
|
+
.ke-content pre[data-k-lang]:not([data-k-lang='plaintext'])::before {
|
|
373
|
+
content: attr(data-k-lang); position: absolute; top: 6px; right: 8px;
|
|
374
|
+
padding: 1px 6px; border-radius: 4px; background: rgba(255, 255, 255, .09); color: #8b93a1;
|
|
375
|
+
font-size: 10.5px; letter-spacing: .04em; text-transform: uppercase; pointer-events: none; user-select: none;
|
|
376
|
+
}
|
|
377
|
+
/* 代码高亮 token(One Dark 配色,与深色底一致) */
|
|
378
|
+
.ke-content .ke-tok-com { color: #7f848e; font-style: italic; }
|
|
379
|
+
.ke-content .ke-tok-str { color: #98c379; }
|
|
380
|
+
.ke-content .ke-tok-num { color: #d19a66; }
|
|
381
|
+
.ke-content .ke-tok-kw { color: #c678dd; }
|
|
382
|
+
.ke-content .ke-tok-typ { color: #e5c07b; }
|
|
383
|
+
.ke-content .ke-tok-fn { color: #61afef; }
|
|
384
|
+
.ke-content .ke-tok-var { color: #e06c75; }
|
|
385
|
+
.ke-content .ke-tok-op { color: #56b6c2; }
|
|
386
|
+
.ke-content .ke-tok-punc { color: #abb2bf; }
|
|
387
|
+
.ke-content .ke-tok-tag { color: #e06c75; }
|
|
388
|
+
.ke-content .ke-tok-attr { color: #d19a66; }
|
|
389
|
+
.ke-content .ke-tok-sel { color: #e06c75; }
|
|
390
|
+
.ke-content .ke-tok-prop { color: #61afef; }
|
|
391
|
+
.ke-content .ke-tok-key { color: #e06c75; }
|
|
392
|
+
.ke-content .ke-tok-bool { color: #d19a66; }
|
|
393
|
+
.ke-content .ke-tok-meta { color: #c678dd; }
|
|
394
|
+
.ke-content .ke-tok-ins { color: #98c379; }
|
|
395
|
+
.ke-content .ke-tok-del { color: #e06c75; text-decoration: line-through; }
|
|
317
396
|
.ke-content img, .ke-content video { max-width: 100%; height: auto; display: block; }
|
|
318
397
|
.ke-content figure { margin: 0 0 16px; }
|
|
319
398
|
.ke-content figcaption { font-size: 13px; color: var(--ke-muted); text-align: center; margin-top: 6px; }
|
|
@@ -580,6 +659,8 @@ const icons = {
|
|
|
580
659
|
video: `<svg class="ke-ico" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="5" width="18" height="14" rx="2.5"/><path d="m10.5 9 4.5 3-4.5 3z"/></svg>`,
|
|
581
660
|
table: `<svg class="ke-ico" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="5" width="18" height="14" rx="2"/><path d="M3 10h18M3 15h18M9 5v14M15 5v14"/></svg>`,
|
|
582
661
|
code: S("m9 7-5 5 5 5M15 7l5 5-5 5"),
|
|
662
|
+
// 导入托盘 + 下箭头:17px 下仍清晰,且不与相邻线性图标抢视线
|
|
663
|
+
markdown: `<svg class="ke-ico" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M12 3.8v10.4m0 0-4.2-4.2M12 14.2l4.2-4.2"/><path d="M4.2 15.4v2.4a2 2 0 0 0 2 2h11.6a2 2 0 0 0 2-2v-2.4"/></svg>`,
|
|
583
664
|
hr: `<svg class="ke-ico" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"><path d="M4 12h16" stroke-width="2.4"/><path d="M6 7h12M6 17h12" opacity=".45"/></svg>`,
|
|
584
665
|
clear: `<svg class="ke-ico" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M8 20 4 16l8-8 4 4-8 8z" /><path d="M12 8 16 4l4 4-4 4M6 20h12"/></svg>`,
|
|
585
666
|
source: S("m8 7-5 5 5 5M16 7l5 5-5 5M13.5 4l-3 16"),
|
|
@@ -601,124 +682,2125 @@ const icons = {
|
|
|
601
682
|
function icon(name) {
|
|
602
683
|
return icons[name] || "";
|
|
603
684
|
}
|
|
604
|
-
const
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
685
|
+
const ALLOWED_TAGS = /* @__PURE__ */ new Set([
|
|
686
|
+
"a",
|
|
687
|
+
"abbr",
|
|
688
|
+
"b",
|
|
689
|
+
"blockquote",
|
|
690
|
+
"br",
|
|
691
|
+
"code",
|
|
692
|
+
"col",
|
|
693
|
+
"colgroup",
|
|
694
|
+
"dd",
|
|
695
|
+
"del",
|
|
696
|
+
"div",
|
|
697
|
+
"dl",
|
|
698
|
+
"dt",
|
|
699
|
+
"em",
|
|
700
|
+
"figcaption",
|
|
701
|
+
"figure",
|
|
702
|
+
"font",
|
|
703
|
+
"h1",
|
|
704
|
+
"h2",
|
|
705
|
+
"h3",
|
|
706
|
+
"h4",
|
|
707
|
+
"h5",
|
|
708
|
+
"h6",
|
|
709
|
+
"hr",
|
|
710
|
+
"i",
|
|
711
|
+
"img",
|
|
712
|
+
"ins",
|
|
713
|
+
"kbd",
|
|
714
|
+
"li",
|
|
715
|
+
"mark",
|
|
716
|
+
"ol",
|
|
717
|
+
"p",
|
|
718
|
+
"pre",
|
|
719
|
+
"s",
|
|
720
|
+
"samp",
|
|
721
|
+
"section",
|
|
722
|
+
"small",
|
|
723
|
+
"span",
|
|
724
|
+
"strong",
|
|
725
|
+
"sub",
|
|
726
|
+
"sup",
|
|
727
|
+
"table",
|
|
728
|
+
"tbody",
|
|
729
|
+
"td",
|
|
730
|
+
"tfoot",
|
|
731
|
+
"th",
|
|
732
|
+
"thead",
|
|
733
|
+
"tr",
|
|
734
|
+
"u",
|
|
735
|
+
"ul",
|
|
736
|
+
"video",
|
|
737
|
+
"source"
|
|
738
|
+
]);
|
|
739
|
+
const GLOBAL_ATTRS = /* @__PURE__ */ new Set(["style", "class"]);
|
|
740
|
+
const TAG_ATTRS = {
|
|
741
|
+
A: ["href", "title", "target", "rel"],
|
|
742
|
+
IMG: ["src", "alt", "title", "width", "height"],
|
|
743
|
+
VIDEO: ["src", "poster", "controls", "loop", "muted", "playsinline", "preload", "width", "height"],
|
|
744
|
+
SOURCE: ["src", "type"],
|
|
745
|
+
FONT: ["size", "color"],
|
|
746
|
+
TD: ["colspan", "rowspan"],
|
|
747
|
+
TH: ["colspan", "rowspan"],
|
|
748
|
+
OL: ["start"],
|
|
749
|
+
LI: ["value"]
|
|
750
|
+
};
|
|
751
|
+
const DATA_PREFIX = ["data-k-", "data-keditor-"];
|
|
752
|
+
const SAFE_URL_RE = /^(?:https?:|mailto:|tel:|blob:|\/|#|\.{1,2}\/|[^:]*$)/i;
|
|
753
|
+
const SAFE_DATA_RE = /^data:image\/(?:png|jpe?g|gif|webp|svg\+xml);/i;
|
|
754
|
+
function isSafeUrl(url) {
|
|
755
|
+
if (!url) return false;
|
|
756
|
+
const value = String(url).trim().replace(/\s+/g, "");
|
|
757
|
+
if (/^(javascript|vbscript|file|about):/i.test(value)) return false;
|
|
758
|
+
if (value.startsWith("data:")) return SAFE_DATA_RE.test(value);
|
|
759
|
+
return SAFE_URL_RE.test(value);
|
|
760
|
+
}
|
|
761
|
+
function sanitizeStyle(value) {
|
|
762
|
+
const out = [];
|
|
763
|
+
for (const decl of String(value).split(";")) {
|
|
764
|
+
const idx = decl.indexOf(":");
|
|
765
|
+
if (idx < 0) continue;
|
|
766
|
+
const prop = decl.slice(0, idx).trim().toLowerCase();
|
|
767
|
+
const val = decl.slice(idx + 1).trim();
|
|
768
|
+
if (!prop || !val) continue;
|
|
769
|
+
if (!/^[a-z-]+$/.test(prop)) continue;
|
|
770
|
+
if (prop.startsWith("mso-") || prop.startsWith("-mso-")) continue;
|
|
771
|
+
if (/expression|javascript:|behavior:|url\(\s*['"]?\s*(javascript|data):/i.test(val)) continue;
|
|
772
|
+
out.push(`${prop}:${val}`);
|
|
663
773
|
}
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
774
|
+
return out.join(";");
|
|
775
|
+
}
|
|
776
|
+
function sanitizeClass(value) {
|
|
777
|
+
return String(value).split(/\s+/).filter((name) => /^[\w-]+$/.test(name) && !/^(script|javascript)/i.test(name)).join(" ");
|
|
778
|
+
}
|
|
779
|
+
function keepAttribute(tagName, attrName, attrValue) {
|
|
780
|
+
const name = attrName.toLowerCase();
|
|
781
|
+
if (name.startsWith("on")) return false;
|
|
782
|
+
if (GLOBAL_ATTRS.has(name)) return true;
|
|
783
|
+
if (DATA_PREFIX.some((prefix) => name.startsWith(prefix))) return true;
|
|
784
|
+
const list = TAG_ATTRS[tagName] || [];
|
|
785
|
+
return list.includes(name);
|
|
786
|
+
}
|
|
787
|
+
function sanitizeHtml(html, { allowEmpty = false } = {}) {
|
|
788
|
+
if (!html) return allowEmpty ? "" : "<p><br></p>";
|
|
789
|
+
const doc = new DOMParser().parseFromString(`<div>${html}</div>`, "text/html");
|
|
790
|
+
const root = doc.body.firstChild;
|
|
791
|
+
walk(root);
|
|
792
|
+
const result = root.innerHTML.trim();
|
|
793
|
+
if (!result && !allowEmpty) return "<p><br></p>";
|
|
794
|
+
return result;
|
|
795
|
+
}
|
|
796
|
+
function walk(node) {
|
|
797
|
+
const children = Array.from(node.childNodes);
|
|
798
|
+
for (const child of children) {
|
|
799
|
+
if (child.nodeType === 8) {
|
|
800
|
+
child.remove();
|
|
801
|
+
continue;
|
|
682
802
|
}
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
const
|
|
689
|
-
(
|
|
803
|
+
if (child.nodeType === 3) continue;
|
|
804
|
+
if (child.nodeType !== 1) {
|
|
805
|
+
child.remove();
|
|
806
|
+
continue;
|
|
807
|
+
}
|
|
808
|
+
const tagName = child.tagName;
|
|
809
|
+
if (!ALLOWED_TAGS.has(tagName.toLowerCase())) {
|
|
810
|
+
if (tagName === "SCRIPT" || tagName === "STYLE" || tagName === "IFRAME" || tagName === "OBJECT" || tagName === "EMBED" || tagName === "FORM" || tagName === "LINK" || tagName === "META") {
|
|
811
|
+
child.remove();
|
|
812
|
+
continue;
|
|
813
|
+
}
|
|
814
|
+
const parent = child.parentNode;
|
|
815
|
+
while (child.firstChild) parent.insertBefore(child.firstChild, child);
|
|
816
|
+
parent.removeChild(child);
|
|
817
|
+
continue;
|
|
818
|
+
}
|
|
819
|
+
for (const attr of Array.from(child.attributes)) {
|
|
820
|
+
if (!keepAttribute(tagName, attr.name, attr.value)) {
|
|
821
|
+
child.removeAttribute(attr.name);
|
|
822
|
+
continue;
|
|
823
|
+
}
|
|
824
|
+
const lower = attr.name.toLowerCase();
|
|
825
|
+
if (lower === "style") child.setAttribute("style", sanitizeStyle(attr.value));
|
|
826
|
+
else if (lower === "class") {
|
|
827
|
+
const cls = sanitizeClass(attr.value);
|
|
828
|
+
if (cls) child.setAttribute("class", cls);
|
|
829
|
+
else child.removeAttribute("class");
|
|
830
|
+
} else if (lower === "href" || lower === "src" || lower === "poster") {
|
|
831
|
+
if (!isSafeUrl(attr.value)) child.removeAttribute(attr.name);
|
|
832
|
+
}
|
|
833
|
+
}
|
|
834
|
+
if (tagName === "A" && child.getAttribute("target") === "_blank") child.setAttribute("rel", "noopener noreferrer");
|
|
835
|
+
if (child.getAttribute("href") === "" || !child.getAttribute("href")) {
|
|
836
|
+
if (tagName === "A") child.removeAttribute("href");
|
|
837
|
+
}
|
|
838
|
+
walk(child);
|
|
690
839
|
}
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
840
|
+
}
|
|
841
|
+
const WORD_FONT_SIZES = { 1: 10, 2: 13, 3: 16, 4: 18, 5: 24, 6: 32, 7: 48 };
|
|
842
|
+
function isWordHtml(html) {
|
|
843
|
+
return /urn:schemas-microsoft-com|class=["']?Mso|ProgID|w:val=/i.test(html);
|
|
844
|
+
}
|
|
845
|
+
function cleanWordHtml(html) {
|
|
846
|
+
const doc = new DOMParser().parseFromString(`<div>${html}</div>`, "text/html");
|
|
847
|
+
const root = doc.body.firstChild;
|
|
848
|
+
root.querySelectorAll("*").forEach((node) => {
|
|
849
|
+
const tag = node.tagName.toLowerCase();
|
|
850
|
+
if (tag.startsWith("o:") || tag.startsWith("w:") || tag === "style" || tag === "script" || tag === "link" || tag === "meta") {
|
|
851
|
+
node.remove();
|
|
852
|
+
return;
|
|
853
|
+
}
|
|
854
|
+
if (tag === "img") {
|
|
855
|
+
const width = Number(node.getAttribute("width") || 0);
|
|
856
|
+
const height = Number(node.getAttribute("height") || 0);
|
|
857
|
+
if (width && width <= 3 || height && height <= 3) node.remove();
|
|
858
|
+
return;
|
|
859
|
+
}
|
|
860
|
+
if (tag === "font") {
|
|
861
|
+
const size = WORD_FONT_SIZES[Number(node.getAttribute("size"))];
|
|
862
|
+
const span = doc.createElement("span");
|
|
863
|
+
const styles = [];
|
|
864
|
+
if (size) styles.push(`font-size:${size}px`);
|
|
865
|
+
if (node.color) styles.push(`color:${node.color}`);
|
|
866
|
+
if (styles.length) span.setAttribute("style", styles.join(";"));
|
|
867
|
+
while (node.firstChild) span.appendChild(node.firstChild);
|
|
868
|
+
node.replaceWith(span);
|
|
869
|
+
return;
|
|
870
|
+
}
|
|
871
|
+
for (const attr of Array.from(node.attributes)) {
|
|
872
|
+
const name = attr.name.toLowerCase();
|
|
873
|
+
if (name.startsWith("mso-") || name === "class" || name.startsWith("_") || name.startsWith("w:") || name.startsWith("o:") || name === "lang" || name === "dir") {
|
|
874
|
+
node.removeAttribute(attr.name);
|
|
875
|
+
}
|
|
876
|
+
}
|
|
877
|
+
});
|
|
878
|
+
return root.innerHTML;
|
|
879
|
+
}
|
|
880
|
+
function escapeHtml(text) {
|
|
881
|
+
return String(text).replace(/[&<>"']/g, (ch) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[ch]);
|
|
882
|
+
}
|
|
883
|
+
function toPlainText(html) {
|
|
884
|
+
const doc = new DOMParser().parseFromString(`<div>${html}</div>`, "text/html");
|
|
885
|
+
doc.body.querySelectorAll("style,script").forEach((n) => n.remove());
|
|
886
|
+
doc.body.innerHTML = doc.body.innerHTML.replace(/<\/(p|div|h[1-6]|li|blockquote|pre|tr)>/gi, "\n");
|
|
887
|
+
return doc.body.textContent.replace(/\u00a0/g, " ").replace(/\n{3,}/g, "\n\n").trim();
|
|
888
|
+
}
|
|
889
|
+
const MAX_HIGHLIGHT_LENGTH = 6e4;
|
|
890
|
+
const LANGUAGE_DEFS = [
|
|
891
|
+
["plaintext", "纯文本", ["text", "txt", "plain", "none"], "不做着色,保留原始排版"],
|
|
892
|
+
["javascript", "JavaScript", ["js", "jsx", "mjs", "cjs", "node"], "前端与 Node 脚本"],
|
|
893
|
+
["typescript", "TypeScript", ["ts", "tsx"], "带类型标注的 JS"],
|
|
894
|
+
["html", "HTML / XML", ["xml", "svg", "vue", "htm", "markup"], "标签结构,内嵌 script / style 一并着色"],
|
|
895
|
+
["css", "CSS", ["scss", "less", "sass", "styl"], "样式表,兼容 scss / less"],
|
|
896
|
+
["json", "JSON", ["jsonc"], "配置与接口数据"],
|
|
897
|
+
["python", "Python", ["py"], "脚本与数据处理"],
|
|
898
|
+
["java", "Java", ["kotlin"], "后端与安卓"],
|
|
899
|
+
["go", "Go", ["golang"], "服务端与云原生"],
|
|
900
|
+
["rust", "Rust", ["rs"], "系统级语言"],
|
|
901
|
+
["c", "C / C++", ["cpp", "c++", "h", "hpp", "cc", "objc"], "含预处理指令"],
|
|
902
|
+
["csharp", "C#", ["cs", "dotnet"], ".NET 体系"],
|
|
903
|
+
["php", "PHP", [], "含 <?php ?> 标记"],
|
|
904
|
+
["ruby", "Ruby", ["rb"], "含符号与实例变量"],
|
|
905
|
+
["sql", "SQL", ["mysql", "postgres", "postgresql", "sqlite", "pg"], "建表与查询语句"],
|
|
906
|
+
["bash", "Shell / Bash", ["sh", "shell", "zsh", "console", "terminal"], "命令行与脚本"],
|
|
907
|
+
["yaml", "YAML", ["yml"], "CI 与部署配置"],
|
|
908
|
+
["ini", "INI / TOML", ["toml", "conf", "env", "properties"], "键值配置"],
|
|
909
|
+
["markdown", "Markdown", ["md"], "文档与说明"],
|
|
910
|
+
["diff", "Diff / Patch", ["patch"], "代码差异"]
|
|
911
|
+
];
|
|
912
|
+
const LANGUAGES = LANGUAGE_DEFS.map(([value, label, aliases, hint]) => ({ value, label, aliases, hint }));
|
|
913
|
+
const LANGUAGE_LABELS = new Map(LANGUAGES.map((item) => [item.value, item.label]));
|
|
914
|
+
const LANGUAGE_ALIASES = /* @__PURE__ */ new Map();
|
|
915
|
+
for (const { value, aliases } of LANGUAGES) {
|
|
916
|
+
LANGUAGE_ALIASES.set(value, value);
|
|
917
|
+
for (const alias of aliases) LANGUAGE_ALIASES.set(alias, value);
|
|
918
|
+
}
|
|
919
|
+
function normalizeLang(lang) {
|
|
920
|
+
const key = String(lang || "").trim().toLowerCase();
|
|
921
|
+
return LANGUAGE_ALIASES.get(key) || "plaintext";
|
|
922
|
+
}
|
|
923
|
+
function languageLabel(lang) {
|
|
924
|
+
return LANGUAGE_LABELS.get(normalizeLang(lang)) || LANGUAGE_LABELS.get("plaintext");
|
|
925
|
+
}
|
|
926
|
+
function listLanguages(only) {
|
|
927
|
+
const pick2 = Array.isArray(only) && only.length ? new Set(only.map(normalizeLang)) : null;
|
|
928
|
+
const list = LANGUAGES.filter((item) => !pick2 || pick2.has(item.value));
|
|
929
|
+
return (list.length ? list : [LANGUAGES[0]]).map(({ value, label, hint }) => ({ value, label, hint }));
|
|
930
|
+
}
|
|
931
|
+
const SPACE = { re: /[^\S\n]+/y, cls: null };
|
|
932
|
+
const NEWLINE = { re: /\n/y, cls: null };
|
|
933
|
+
const BLANK = [SPACE, NEWLINE];
|
|
934
|
+
const IDENT = { re: /[A-Za-z_$][\w$]*/y, cls: null };
|
|
935
|
+
const NUM = {
|
|
936
|
+
re: /(?:0[xX][\da-fA-F](?:_?[\da-fA-F])*|0[bB][01](?:_?[01])*|0[oO][0-7](?:_?[0-7])*|\d(?:_?\d)*(?:\.(?:\d(?:_?\d)*)?)?(?:[eE][+-]?\d+)?)[a-zA-Z]*/y,
|
|
937
|
+
cls: "num"
|
|
938
|
+
};
|
|
939
|
+
const C_TYPE = { re: /[A-Z][A-Za-z0-9_]*/y, cls: "typ" };
|
|
940
|
+
const CALL = { re: /[A-Za-z_$][\w$]*(?=\s*\()/y, cls: "fn" };
|
|
941
|
+
const PUNCT = { re: /[{}[\]();,.]+/y, cls: "op" };
|
|
942
|
+
const OP = { re: /[+\-*/%=!<>&|^~?:@]+/y, cls: "op" };
|
|
943
|
+
const BLOCK_COMMENT = { re: /\/\*[\s\S]*?(?:\*\/|$)/y, cls: "com" };
|
|
944
|
+
const LINE_COMMENT = { re: /\/\/[^\n]*/y, cls: "com" };
|
|
945
|
+
const DQ_STRING = { re: /"(?:\\[\s\S]|[^\\"\n])*"/y, cls: "str" };
|
|
946
|
+
const SQ_STRING = { re: /'(?:\\[\s\S]|[^\\'\n])*'/y, cls: "str" };
|
|
947
|
+
const C_STRING = [
|
|
948
|
+
DQ_STRING,
|
|
949
|
+
SQ_STRING,
|
|
950
|
+
{ re: /`(?:\\[\s\S]|[^\\`])*`/y, cls: "str" }
|
|
951
|
+
];
|
|
952
|
+
const kw = (words, flags = "y") => ({ re: new RegExp(`\\b(?:${words})\\b`, flags), cls: "kw" });
|
|
953
|
+
const typ = (words, flags = "y") => ({ re: new RegExp(`\\b(?:${words})\\b`, flags), cls: "typ" });
|
|
954
|
+
const bool = (words) => ({ re: new RegExp(`\\b(?:${words})\\b`, "y"), cls: "bool" });
|
|
955
|
+
const nameAfter = (words) => ({
|
|
956
|
+
re: /[A-Za-z_$][\w$]*/y,
|
|
957
|
+
cls: "fn",
|
|
958
|
+
when: (prev) => words.includes(prev)
|
|
959
|
+
});
|
|
960
|
+
const JS_BUILTINS = typ("Object|Array|String|Number|Boolean|Symbol|BigInt|Promise|Map|Set|WeakMap|WeakSet|RegExp|Date|Math|JSON|Error|AggregateError|TypeError|RangeError|SyntaxError|Function|Proxy|Reflect|Intl|console|window|document|globalThis|process|require|module|exports");
|
|
961
|
+
const RULES = {
|
|
962
|
+
plaintext: null,
|
|
963
|
+
javascript: [
|
|
964
|
+
...BLANK,
|
|
965
|
+
BLOCK_COMMENT,
|
|
966
|
+
LINE_COMMENT,
|
|
967
|
+
{ re: /`(?:\\[\s\S]|\$\{(?:[^{}]|\{[^{}]*\})*\}|[^\\`])*`/y, cls: "str" },
|
|
968
|
+
// 模板串(含简单插值)
|
|
969
|
+
DQ_STRING,
|
|
970
|
+
SQ_STRING,
|
|
971
|
+
{ re: /\/(?![/*\s])(?:\\.|\[(?:\\.|[^\]\n])*\]|[^\\/\n])*\/[a-z]*/y, cls: "str" },
|
|
972
|
+
// 正则字面量
|
|
973
|
+
bool("true|false|null|undefined|NaN|Infinity"),
|
|
974
|
+
kw("break|case|catch|class|const|continue|debugger|default|delete|do|else|export|extends|finally|for|function|if|import|in|instanceof|let|new|return|super|switch|this|throw|try|typeof|var|void|while|with|yield|async|await|of|static|get|set|as|from|delete"),
|
|
975
|
+
JS_BUILTINS,
|
|
976
|
+
C_TYPE,
|
|
977
|
+
CALL,
|
|
978
|
+
NUM,
|
|
979
|
+
IDENT,
|
|
980
|
+
OP,
|
|
981
|
+
PUNCT
|
|
982
|
+
],
|
|
983
|
+
typescript: [
|
|
984
|
+
...BLANK,
|
|
985
|
+
BLOCK_COMMENT,
|
|
986
|
+
LINE_COMMENT,
|
|
987
|
+
{ re: /`(?:\\[\s\S]|\$\{(?:[^{}]|\{[^{}]*\})*\}|[^\\`])*`/y, cls: "str" },
|
|
988
|
+
DQ_STRING,
|
|
989
|
+
SQ_STRING,
|
|
990
|
+
bool("true|false|null|undefined|NaN|Infinity"),
|
|
991
|
+
kw("abstract|any|as|asserts|async|await|break|case|catch|class|const|constructor|continue|declare|default|delete|do|else|enum|export|extends|finally|for|from|function|get|if|implements|import|in|infer|instanceof|interface|is|keyof|let|namespace|new|of|private|protected|public|readonly|return|satisfies|set|static|super|switch|this|throw|try|type|typeof|unique|var|void|while|with|yield"),
|
|
992
|
+
JS_BUILTINS,
|
|
993
|
+
C_TYPE,
|
|
994
|
+
CALL,
|
|
995
|
+
NUM,
|
|
996
|
+
IDENT,
|
|
997
|
+
OP,
|
|
998
|
+
PUNCT
|
|
999
|
+
],
|
|
1000
|
+
json: [
|
|
1001
|
+
...BLANK,
|
|
1002
|
+
{ re: /"(?:\\.|[^\\"\n])*"(?=\s*:)/y, cls: "key" },
|
|
1003
|
+
{ re: /"(?:\\.|[^\\"\n])*"/y, cls: "str" },
|
|
1004
|
+
bool("true|false|null"),
|
|
1005
|
+
NUM,
|
|
1006
|
+
IDENT,
|
|
1007
|
+
PUNCT
|
|
1008
|
+
],
|
|
1009
|
+
css: [
|
|
1010
|
+
...BLANK,
|
|
1011
|
+
BLOCK_COMMENT,
|
|
1012
|
+
LINE_COMMENT,
|
|
1013
|
+
{ re: /@[\w-]+/y, cls: "kw" },
|
|
1014
|
+
DQ_STRING,
|
|
1015
|
+
SQ_STRING,
|
|
1016
|
+
{ re: /#[0-9a-fA-F]{3,8}\b/y, cls: "num" },
|
|
1017
|
+
{ re: /[\w-]+(?=\s*\()/y, cls: "fn" },
|
|
1018
|
+
{ re: /!important\b/y, cls: "kw" },
|
|
1019
|
+
{ re: /[\w-]+(?=\s*:)/y, cls: "prop" },
|
|
1020
|
+
{ re: /\.[a-zA-Z_-][\w-]*|#[\w-]+|::?[\w-]+|\[[^\]]*\]|\*|&/y, cls: "sel" },
|
|
1021
|
+
{ re: /\b\d+(?:\.\d+)?(?:px|em|rem|ex|ch|vh|vw|vmin|vmax|%|s|ms|deg|turn|fr|pt|cm|mm|in|dpi)\b/y, cls: "num" },
|
|
1022
|
+
{ re: /\b(?:solid|dashed|dotted|double|none|auto|absolute|relative|fixed|sticky|static|block|inline|inline-block|flex|grid|hidden|visible|inherit|initial|unset|currentColor|bold|italic|uppercase|lowercase|center|left|right|top|bottom|middle|wrap|nowrap|pointer|cursor|scroll|contain|cover)\b/y, cls: "typ" },
|
|
1023
|
+
IDENT,
|
|
1024
|
+
NUM,
|
|
1025
|
+
OP,
|
|
1026
|
+
PUNCT
|
|
1027
|
+
],
|
|
1028
|
+
python: [
|
|
1029
|
+
...BLANK,
|
|
1030
|
+
{ re: /#[^\n]*/y, cls: "com" },
|
|
1031
|
+
{ re: /'''[\s\S]*?'''|"""[\s\S]*?"""/y, cls: "str" },
|
|
1032
|
+
{ re: /[rbfu]{0,2}'(?:\\.|[^\\'\n])*'|[rbfu]{0,2}"(?:\\.|[^\\"\n])*"/y, cls: "str" },
|
|
1033
|
+
{ re: /@[\w.]+/y, cls: "meta" },
|
|
1034
|
+
bool("True|False|None"),
|
|
1035
|
+
kw("and|as|assert|async|await|break|case|class|continue|def|del|elif|else|except|finally|for|from|global|if|import|in|is|lambda|match|nonlocal|not|or|pass|raise|return|try|while|with|yield"),
|
|
1036
|
+
typ("print|len|range|str|int|float|bool|list|dict|set|tuple|type|isinstance|enumerate|zip|map|filter|sorted|sum|min|max|abs|round|open|super|object|Exception|ValueError|TypeError|KeyError|IndexError|AttributeError|RuntimeError|StopIteration"),
|
|
1037
|
+
C_TYPE,
|
|
1038
|
+
CALL,
|
|
1039
|
+
NUM,
|
|
1040
|
+
IDENT,
|
|
1041
|
+
OP,
|
|
1042
|
+
PUNCT
|
|
1043
|
+
],
|
|
1044
|
+
java: [
|
|
1045
|
+
...BLANK,
|
|
1046
|
+
BLOCK_COMMENT,
|
|
1047
|
+
LINE_COMMENT,
|
|
1048
|
+
C_STRING[0],
|
|
1049
|
+
C_STRING[1],
|
|
1050
|
+
{ re: /@[\w.]+/y, cls: "meta" },
|
|
1051
|
+
bool("true|false|null"),
|
|
1052
|
+
kw("abstract|assert|break|case|catch|class|const|continue|default|do|else|enum|extends|final|finally|for|goto|if|implements|import|instanceof|interface|native|new|package|private|protected|public|record|return|sealed|static|strictfp|super|switch|synchronized|this|throw|throws|transient|try|var|volatile|while|yield"),
|
|
1053
|
+
typ("boolean|byte|char|double|float|int|long|short|void|String|Integer|Long|Double|Float|Boolean|Character|Object|List|Map|Set|ArrayList|HashMap|HashSet|Optional|Stream|Override|Deprecated|System|Math|Thread|Exception|RuntimeException"),
|
|
1054
|
+
nameAfter(["class", "interface", "enum", "record", "new"]),
|
|
1055
|
+
C_TYPE,
|
|
1056
|
+
CALL,
|
|
1057
|
+
NUM,
|
|
1058
|
+
IDENT,
|
|
1059
|
+
OP,
|
|
1060
|
+
PUNCT
|
|
1061
|
+
],
|
|
1062
|
+
go: [
|
|
1063
|
+
...BLANK,
|
|
1064
|
+
BLOCK_COMMENT,
|
|
1065
|
+
LINE_COMMENT,
|
|
1066
|
+
{ re: /`[^`]*`/y, cls: "str" },
|
|
1067
|
+
DQ_STRING,
|
|
1068
|
+
SQ_STRING,
|
|
1069
|
+
bool("true|false|nil|iota"),
|
|
1070
|
+
kw("break|case|chan|const|continue|default|defer|else|fallthrough|for|func|go|goto|if|import|interface|map|package|range|return|select|struct|switch|type|var"),
|
|
1071
|
+
typ("any|bool|byte|comparable|complex64|complex128|error|float32|float64|int|int8|int16|int32|int64|rune|string|uint|uint8|uint16|uint32|uint64|uintptr"),
|
|
1072
|
+
nameAfter(["func", "type", "struct", "interface"]),
|
|
1073
|
+
C_TYPE,
|
|
1074
|
+
CALL,
|
|
1075
|
+
NUM,
|
|
1076
|
+
IDENT,
|
|
1077
|
+
OP,
|
|
1078
|
+
PUNCT
|
|
1079
|
+
],
|
|
1080
|
+
rust: [
|
|
1081
|
+
...BLANK,
|
|
1082
|
+
BLOCK_COMMENT,
|
|
1083
|
+
LINE_COMMENT,
|
|
1084
|
+
DQ_STRING,
|
|
1085
|
+
{ re: /'(?:\\.|[^\\'])'/y, cls: "str" },
|
|
1086
|
+
// 字符字面量(必须先于生命周期,否则 'a' 会被吃掉)
|
|
1087
|
+
{ re: /'[A-Za-z_]\w*/y, cls: "meta" },
|
|
1088
|
+
// 生命周期 'a
|
|
1089
|
+
{ re: /(?:r|b)?#*"(?:\\[\s\S]|[^\\"])*"#*/y, cls: "str" },
|
|
1090
|
+
{ re: /#!?\[[^\]]*\]/y, cls: "meta" },
|
|
1091
|
+
bool("true|false|None|Some|Ok|Err"),
|
|
1092
|
+
kw("as|async|await|break|const|continue|crate|dyn|else|enum|extern|fn|for|if|impl|in|let|loop|match|mod|move|mut|pub|ref|return|self|Self|static|struct|super|trait|type|unsafe|use|where|while"),
|
|
1093
|
+
typ("bool|char|f32|f64|i8|i16|i32|i64|i128|isize|str|u8|u16|u32|u64|u128|usize|String|Vec|Option|Result|Box|Rc|Arc|RefCell|HashMap|HashSet|BTreeMap|Self"),
|
|
1094
|
+
nameAfter(["fn", "struct", "enum", "trait", "impl", "mod"]),
|
|
1095
|
+
C_TYPE,
|
|
1096
|
+
CALL,
|
|
1097
|
+
NUM,
|
|
1098
|
+
IDENT,
|
|
1099
|
+
OP,
|
|
1100
|
+
PUNCT
|
|
1101
|
+
],
|
|
1102
|
+
c: [
|
|
1103
|
+
{ re: /^[ \t]*#[ \t]*\w+[^\n]*/my, cls: "meta" },
|
|
1104
|
+
...BLANK,
|
|
1105
|
+
BLOCK_COMMENT,
|
|
1106
|
+
LINE_COMMENT,
|
|
1107
|
+
C_STRING[0],
|
|
1108
|
+
C_STRING[1],
|
|
1109
|
+
bool("true|false|nullptr|NULL|stdin|stdout|stderr"),
|
|
1110
|
+
kw("alignas|alignof|asm|auto|break|case|catch|class|const|constexpr|continue|decltype|default|delete|do|dynamic_cast|else|enum|explicit|export|extern|final|for|friend|goto|if|inline|mutable|namespace|new|noexcept|operator|override|private|protected|public|register|return|sizeof|static|static_cast|struct|switch|template|this|throw|try|typedef|typename|union|using|virtual|volatile|while"),
|
|
1111
|
+
typ("bool|char|double|float|int|long|short|signed|unsigned|void|wchar_t|size_t|uint8_t|uint16_t|uint32_t|uint64_t|int8_t|int16_t|int32_t|int64_t|FILE|string|cout|cin|cerr|endl|std|vector|map|set"),
|
|
1112
|
+
nameAfter(["struct", "class", "enum", "union", "namespace"]),
|
|
1113
|
+
C_TYPE,
|
|
1114
|
+
CALL,
|
|
1115
|
+
NUM,
|
|
1116
|
+
IDENT,
|
|
1117
|
+
OP,
|
|
1118
|
+
PUNCT
|
|
1119
|
+
],
|
|
1120
|
+
csharp: [
|
|
1121
|
+
{ re: /^[ \t]*#[ \t]*\w+[^\n]*/my, cls: "meta" },
|
|
1122
|
+
...BLANK,
|
|
1123
|
+
BLOCK_COMMENT,
|
|
1124
|
+
LINE_COMMENT,
|
|
1125
|
+
{ re: /\$?"(?:""|\\.|[^\\"\n])*"/y, cls: "str" },
|
|
1126
|
+
C_STRING[1],
|
|
1127
|
+
bool("true|false|null"),
|
|
1128
|
+
kw("abstract|as|async|await|base|break|case|catch|checked|class|const|continue|default|delegate|do|else|enum|event|explicit|extern|finally|fixed|for|foreach|goto|if|implicit|in|interface|internal|is|lock|namespace|new|operator|out|override|params|private|protected|public|readonly|record|ref|return|sealed|sizeof|stackalloc|static|struct|switch|this|throw|try|typeof|unchecked|unsafe|using|var|virtual|volatile|when|where|while|yield"),
|
|
1129
|
+
typ("bool|byte|char|decimal|double|dynamic|float|int|long|object|sbyte|short|string|uint|ulong|ushort|void|Task|List|Dictionary|IEnumerable|Action|Func|Exception|Console|String|Int32|Enumerable"),
|
|
1130
|
+
nameAfter(["class", "struct", "interface", "enum", "namespace", "new"]),
|
|
1131
|
+
C_TYPE,
|
|
1132
|
+
CALL,
|
|
1133
|
+
NUM,
|
|
1134
|
+
IDENT,
|
|
1135
|
+
OP,
|
|
1136
|
+
PUNCT
|
|
1137
|
+
],
|
|
1138
|
+
php: [
|
|
1139
|
+
...BLANK,
|
|
1140
|
+
{ re: /<\?php|\?>|<\?=/y, cls: "meta" },
|
|
1141
|
+
BLOCK_COMMENT,
|
|
1142
|
+
LINE_COMMENT,
|
|
1143
|
+
{ re: /#[^\n]*/y, cls: "com" },
|
|
1144
|
+
DQ_STRING,
|
|
1145
|
+
SQ_STRING,
|
|
1146
|
+
{ re: /\$[A-Za-z_]\w*/y, cls: "var" },
|
|
1147
|
+
bool("true|false|null|TRUE|FALSE|NULL"),
|
|
1148
|
+
kw("abstract|and|array|as|break|callable|case|catch|class|clone|const|continue|declare|default|do|echo|else|elseif|empty|enddeclare|endfor|endforeach|endif|endswitch|endwhile|enum|extends|final|finally|fn|for|foreach|function|global|goto|if|implements|include|include_once|instanceof|insteadof|interface|isset|list|match|namespace|new|or|print|private|protected|public|readonly|require|require_once|return|static|switch|throw|trait|try|unset|use|var|while|xor|yield"),
|
|
1149
|
+
typ("int|float|string|bool|array|object|mixed|void|iterable|self|parent|Closure|Exception|DateTime|stdClass|Countable|JsonSerializable|strlen|count|implode|explode|array_map|array_filter|sprintf|printf|json_encode|json_decode"),
|
|
1150
|
+
CALL,
|
|
1151
|
+
NUM,
|
|
1152
|
+
IDENT,
|
|
1153
|
+
OP,
|
|
1154
|
+
PUNCT
|
|
1155
|
+
],
|
|
1156
|
+
ruby: [
|
|
1157
|
+
{ re: /^=begin[\s\S]*?^=end[^\n]*/my, cls: "com" },
|
|
1158
|
+
...BLANK,
|
|
1159
|
+
{ re: /#[^\n]*/y, cls: "com" },
|
|
1160
|
+
DQ_STRING,
|
|
1161
|
+
SQ_STRING,
|
|
1162
|
+
{ re: /%[wWiI][([{][^)\]}]*[)\]}]/y, cls: "str" },
|
|
1163
|
+
{ re: /@@?[A-Za-z_]\w*|\$[A-Za-z_]\w*/y, cls: "var" },
|
|
1164
|
+
{ re: /:[A-Za-z_]\w*[?!]?/y, cls: "typ" },
|
|
1165
|
+
bool("true|false|nil|__FILE__|__LINE__"),
|
|
1166
|
+
kw("alias|and|begin|break|case|class|def|defined|do|else|elsif|end|ensure|for|if|in|module|next|not|or|raise|redo|rescue|retry|return|self|super|then|undef|unless|until|when|while|yield|lambda|proc|new|attr_accessor|attr_reader|attr_writer|require|require_relative|include|extend|puts|print|p|loop|freeze|respond_to|instance_variable_get|send|tap|each|map|select|reject|reduce|inject|push|pop|shift|unshift|join|split|to_s|to_i|to_a|to_h|nil?|empty?"),
|
|
1167
|
+
C_TYPE,
|
|
1168
|
+
nameAfter(["def", "class", "module"]),
|
|
1169
|
+
CALL,
|
|
1170
|
+
NUM,
|
|
1171
|
+
IDENT,
|
|
1172
|
+
OP,
|
|
1173
|
+
PUNCT
|
|
1174
|
+
],
|
|
1175
|
+
sql: [
|
|
1176
|
+
...BLANK,
|
|
1177
|
+
{ re: /--[^\n]*/y, cls: "com" },
|
|
1178
|
+
BLOCK_COMMENT,
|
|
1179
|
+
{ re: /'[^']*(?:''[^']*)*'/y, cls: "str" },
|
|
1180
|
+
{ re: /"[^"]*"|`[^`]*`/y, cls: "var" },
|
|
1181
|
+
{ re: /\$\$[\s\S]*?\$\$/y, cls: "str" },
|
|
1182
|
+
bool("true|false|null"),
|
|
1183
|
+
kw("add|all|alter|and|as|asc|begin|between|by|case|cast|column|commit|constraint|create|cross|database|default|delete|desc|distinct|drop|else|end|except|exists|foreign|from|full|group|having|if|in|index|inner|insert|intersect|into|is|join|key|left|like|limit|not|null|offset|on|or|order|outer|primary|references|right|rollback|select|set|table|then|top|transaction|truncate|union|unique|update|values|view|when|where|with", "iy"),
|
|
1184
|
+
typ("bigint|bit|blob|boolean|char|date|datetime|decimal|double|enum|float|int|integer|json|jsonb|longtext|numeric|real|serial|smallint|text|time|timestamp|tinyint|uuid|varchar|count|sum|avg|min|max|coalesce|nullif|now|current_date|current_timestamp|concat|substring|trim|upper|lower|length|round|abs|group_concat|string_agg|row_number|rank", "iy"),
|
|
1185
|
+
CALL,
|
|
1186
|
+
NUM,
|
|
1187
|
+
IDENT,
|
|
1188
|
+
OP,
|
|
1189
|
+
PUNCT
|
|
1190
|
+
],
|
|
1191
|
+
bash: [
|
|
1192
|
+
{ re: /^#![^\n]*/my, cls: "meta" },
|
|
1193
|
+
...BLANK,
|
|
1194
|
+
{ re: /#[^\n]*/y, cls: "com" },
|
|
1195
|
+
{ re: /'[^']*'/y, cls: "str" },
|
|
1196
|
+
{ re: /\$?"(?:\\[\s\S]|[^\\"\n])*"/y, cls: "str" },
|
|
1197
|
+
{ re: /\$\{[^}\n]*\}|\$\(|\$[A-Za-z_]\w*|\$[0-9@*#?$!-]/y, cls: "var" },
|
|
1198
|
+
kw("if|then|else|elif|fi|for|in|do|done|while|until|case|esac|function|select|time|return|local|export|declare|readonly|unset|shift|source|exit|trap|set|eval|exec|alias|break|continue"),
|
|
1199
|
+
typ("echo|printf|read|cd|pwd|test|cat|ls|cp|mv|rm|mkdir|rmdir|touch|chmod|chown|grep|egrep|sed|awk|sort|uniq|head|tail|wc|cut|tr|xargs|find|which|curl|wget|git|npm|npx|yarn|pnpm|node|python|pip|docker|kubectl|ssh|scp|tar|zip|unzip|make|sudo|apt|brew|systemctl|journalctl|ps|kill|df|du|env|sleep|date|basename|dirname|realpath|mktemp"),
|
|
1200
|
+
{ re: /\{\d+(?:,\d*)?\}/y, cls: "num" },
|
|
1201
|
+
NUM,
|
|
1202
|
+
{ re: /--?[A-Za-z][\w-]*/y, cls: "attr" },
|
|
1203
|
+
IDENT,
|
|
1204
|
+
OP,
|
|
1205
|
+
PUNCT
|
|
1206
|
+
],
|
|
1207
|
+
yaml: [
|
|
1208
|
+
{ re: /^---[^\n]*|^\.\.\.[^\n]*/my, cls: "meta" },
|
|
1209
|
+
{ re: /^[ \t]*-[ \t]/my, cls: "kw" },
|
|
1210
|
+
...BLANK,
|
|
1211
|
+
{ re: /#[^\n]*/y, cls: "com" },
|
|
1212
|
+
{ re: /[|>][-+]?\d*\s*(?=\n|$)/y, cls: "meta" },
|
|
1213
|
+
{ re: new RegExp("(?<![\\w$])&[\\w.-]+|\\*[\\w.-]+", "y"), cls: "var" },
|
|
1214
|
+
{ re: /!!?[\w:.-]+/y, cls: "meta" },
|
|
1215
|
+
bool("true|false|null|yes|no|on|off|True|False|Null|~"),
|
|
1216
|
+
{ re: /[\w$.-]+(?=\s*:(?:\s|$))/y, cls: "key" },
|
|
1217
|
+
DQ_STRING,
|
|
1218
|
+
SQ_STRING,
|
|
1219
|
+
NUM,
|
|
1220
|
+
IDENT,
|
|
1221
|
+
OP,
|
|
1222
|
+
PUNCT
|
|
1223
|
+
],
|
|
1224
|
+
ini: [
|
|
1225
|
+
...BLANK,
|
|
1226
|
+
{ re: /[#;][^\n]*/y, cls: "com" },
|
|
1227
|
+
{ re: /\[[^\]\n]*\]/y, cls: "kw" },
|
|
1228
|
+
{ re: /"""[\s\S]*?"""|'''[\s\S]*?'''/y, cls: "str" },
|
|
1229
|
+
DQ_STRING,
|
|
1230
|
+
SQ_STRING,
|
|
1231
|
+
bool("true|false|yes|no|on|off"),
|
|
1232
|
+
{ re: /[\w$.-]+(?=\s*=(?!=))/y, cls: "key" },
|
|
1233
|
+
{ re: /\d{4}-\d{2}-\d{2}(?:[T ]\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})?)?/y, cls: "num" },
|
|
1234
|
+
NUM,
|
|
1235
|
+
IDENT,
|
|
1236
|
+
OP,
|
|
1237
|
+
PUNCT
|
|
1238
|
+
],
|
|
1239
|
+
markdown: [
|
|
1240
|
+
{ re: /^[ \t]*```[^\n]*\n[\s\S]*?^[ \t]*```[ \t]*$/my, cls: "str" },
|
|
1241
|
+
{ re: /^[ \t]*```[^\n]*/my, cls: "str" },
|
|
1242
|
+
{ re: /^#{1,6}[ \t][^\n]*/my, cls: "kw" },
|
|
1243
|
+
{ re: /^[ \t]*>[^\n]*/my, cls: "com" },
|
|
1244
|
+
{ re: /^[ \t]*(?:-{3,}|\*{3,}|_{3,})[ \t]*$/my, cls: "com" },
|
|
1245
|
+
{ re: /^[ \t]*(?:[-*+][ \t]|\d+\.[ \t])/my, cls: "kw" },
|
|
1246
|
+
...BLANK,
|
|
1247
|
+
{ re: /!?\[[^\]\n]*\]\([^)\n]*\)/y, cls: "str" },
|
|
1248
|
+
{ re: /`[^`\n]+`/y, cls: "str" },
|
|
1249
|
+
{ re: /\*\*[^*\n]+\*\*|__[^_\n]+__/y, cls: "typ" },
|
|
1250
|
+
{ re: /\*[^*\n]+\*/y, cls: "var" },
|
|
1251
|
+
{ re: /https?:\/\/[^\s)]+/y, cls: "fn" },
|
|
1252
|
+
{ re: /<\/?[A-Za-z][^>\n]*>/y, cls: "tag" },
|
|
1253
|
+
PUNCT
|
|
1254
|
+
],
|
|
1255
|
+
diff: [
|
|
1256
|
+
{ re: /^(?:diff|index|new file|deleted file|similarity|rename|Binary files)[^\n]*/my, cls: "meta" },
|
|
1257
|
+
{ re: /^(?:---|\+\+\+)[^\n]*/my, cls: "meta" },
|
|
1258
|
+
{ re: /^@@[^\n]*/my, cls: "kw" },
|
|
1259
|
+
{ re: /^\+[^\n]*/my, cls: "ins" },
|
|
1260
|
+
{ re: /^-[^\n]*/my, cls: "del" },
|
|
1261
|
+
{ re: /^\\[^\n]*/my, cls: "com" },
|
|
1262
|
+
...BLANK,
|
|
1263
|
+
IDENT,
|
|
1264
|
+
PUNCT
|
|
1265
|
+
]
|
|
1266
|
+
};
|
|
1267
|
+
function scan(code, rules) {
|
|
1268
|
+
let out = "";
|
|
1269
|
+
let plain = "";
|
|
1270
|
+
let prev = "";
|
|
1271
|
+
let index = 0;
|
|
1272
|
+
const flush = () => {
|
|
1273
|
+
if (plain) {
|
|
1274
|
+
out += escapeHtml(plain);
|
|
1275
|
+
plain = "";
|
|
1276
|
+
}
|
|
1277
|
+
};
|
|
1278
|
+
while (index < code.length) {
|
|
1279
|
+
let hit = null;
|
|
1280
|
+
let match = null;
|
|
1281
|
+
for (const rule of rules) {
|
|
1282
|
+
if (rule.when && !rule.when(prev)) continue;
|
|
1283
|
+
rule.re.lastIndex = index;
|
|
1284
|
+
const found = rule.re.exec(code);
|
|
1285
|
+
if (found && found[0]) {
|
|
1286
|
+
hit = rule;
|
|
1287
|
+
match = found;
|
|
1288
|
+
break;
|
|
1289
|
+
}
|
|
1290
|
+
}
|
|
1291
|
+
if (!match) {
|
|
1292
|
+
plain += code[index];
|
|
1293
|
+
index += 1;
|
|
1294
|
+
continue;
|
|
1295
|
+
}
|
|
1296
|
+
const text = match[0];
|
|
1297
|
+
if (hit.cls) {
|
|
1298
|
+
flush();
|
|
1299
|
+
out += `<span class="ke-tok-${hit.cls}">${escapeHtml(text)}</span>`;
|
|
1300
|
+
} else {
|
|
1301
|
+
plain += text;
|
|
1302
|
+
}
|
|
1303
|
+
const trimmed = text.trim();
|
|
1304
|
+
if (trimmed) prev = trimmed;
|
|
1305
|
+
index += text.length;
|
|
1306
|
+
}
|
|
1307
|
+
flush();
|
|
1308
|
+
return out;
|
|
1309
|
+
}
|
|
1310
|
+
const HTML_TAG_START = /<\/?([A-Za-z][\w:.-]*)/y;
|
|
1311
|
+
function scanTag(code, start, out, emit) {
|
|
1312
|
+
let index = start;
|
|
1313
|
+
let closed = false;
|
|
1314
|
+
while (index < code.length) {
|
|
1315
|
+
const rest = code.slice(index);
|
|
1316
|
+
let found = /^[\s]+/.exec(rest);
|
|
1317
|
+
if (found) {
|
|
1318
|
+
emit(null, found[0]);
|
|
1319
|
+
index += found[0].length;
|
|
1320
|
+
continue;
|
|
1321
|
+
}
|
|
1322
|
+
found = /^\/?>/.exec(rest);
|
|
1323
|
+
if (found) {
|
|
1324
|
+
emit("tag", found[0]);
|
|
1325
|
+
index += found[0].length;
|
|
1326
|
+
closed = true;
|
|
1327
|
+
break;
|
|
1328
|
+
}
|
|
1329
|
+
found = /^[^\s=/>]+/.exec(rest);
|
|
1330
|
+
if (found) {
|
|
1331
|
+
emit("attr", found[0]);
|
|
1332
|
+
index += found[0].length;
|
|
1333
|
+
continue;
|
|
1334
|
+
}
|
|
1335
|
+
found = /^=/.exec(rest);
|
|
1336
|
+
if (found) {
|
|
1337
|
+
emit("op", found[0]);
|
|
1338
|
+
index += found[0].length;
|
|
1339
|
+
continue;
|
|
1340
|
+
}
|
|
1341
|
+
emit(null, code[index]);
|
|
1342
|
+
index += 1;
|
|
1343
|
+
}
|
|
1344
|
+
return { index, closed };
|
|
1345
|
+
}
|
|
1346
|
+
function highlightHtml(code) {
|
|
1347
|
+
let out = "";
|
|
1348
|
+
let plain = "";
|
|
1349
|
+
let index = 0;
|
|
1350
|
+
const flush = () => {
|
|
1351
|
+
if (plain) {
|
|
1352
|
+
out += escapeHtml(plain);
|
|
1353
|
+
plain = "";
|
|
1354
|
+
}
|
|
1355
|
+
};
|
|
1356
|
+
const emit = (cls, text, raw = false) => {
|
|
1357
|
+
if (cls) {
|
|
1358
|
+
flush();
|
|
1359
|
+
out += raw ? text : `<span class="ke-tok-${cls}">${escapeHtml(text)}</span>`;
|
|
1360
|
+
} else {
|
|
1361
|
+
plain += text;
|
|
1362
|
+
}
|
|
1363
|
+
};
|
|
1364
|
+
while (index < code.length) {
|
|
1365
|
+
const rest = code.slice(index);
|
|
1366
|
+
let found = /^<!--[\s\S]*?(?:-->|$)/.exec(rest);
|
|
1367
|
+
if (found) {
|
|
1368
|
+
emit("com", found[0]);
|
|
1369
|
+
index += found[0].length;
|
|
1370
|
+
continue;
|
|
1371
|
+
}
|
|
1372
|
+
found = /^<!\[CDATA\[[\s\S]*?(?:\]\]>|$)/.exec(rest);
|
|
1373
|
+
if (found) {
|
|
1374
|
+
emit("str", found[0]);
|
|
1375
|
+
index += found[0].length;
|
|
1376
|
+
continue;
|
|
1377
|
+
}
|
|
1378
|
+
found = /^<[!?][^>]*/.exec(rest);
|
|
1379
|
+
if (found) {
|
|
1380
|
+
emit("meta", found[0]);
|
|
1381
|
+
index += found[0].length;
|
|
1382
|
+
continue;
|
|
1383
|
+
}
|
|
1384
|
+
HTML_TAG_START.lastIndex = index;
|
|
1385
|
+
found = HTML_TAG_START.exec(code);
|
|
1386
|
+
if (found) {
|
|
1387
|
+
emit("tag", found[0]);
|
|
1388
|
+
index += found[0].length;
|
|
1389
|
+
const tagName = found[1].toLowerCase();
|
|
1390
|
+
const tag = scanTag(code, index, out, emit);
|
|
1391
|
+
index = tag.index;
|
|
1392
|
+
if (tag.closed && (tagName === "script" || tagName === "style")) {
|
|
1393
|
+
const closeAt = code.toLowerCase().indexOf(`</${tagName}`, index);
|
|
1394
|
+
if (closeAt > index) {
|
|
1395
|
+
emit("raw", highlightCode(code.slice(index, closeAt), tagName === "script" ? "javascript" : "css"), true);
|
|
1396
|
+
index = closeAt;
|
|
1397
|
+
}
|
|
1398
|
+
}
|
|
1399
|
+
continue;
|
|
1400
|
+
}
|
|
1401
|
+
found = /^&[#\w]+;/.exec(rest);
|
|
1402
|
+
if (found) {
|
|
1403
|
+
emit("num", found[0]);
|
|
1404
|
+
index += found[0].length;
|
|
1405
|
+
continue;
|
|
1406
|
+
}
|
|
1407
|
+
plain += code[index];
|
|
1408
|
+
index += 1;
|
|
1409
|
+
}
|
|
1410
|
+
flush();
|
|
1411
|
+
return out;
|
|
1412
|
+
}
|
|
1413
|
+
function highlightCode(code, lang) {
|
|
1414
|
+
const text = String(code == null ? "" : code);
|
|
1415
|
+
const name = normalizeLang(lang);
|
|
1416
|
+
if (name === "plaintext") return escapeHtml(text);
|
|
1417
|
+
if (text.length > MAX_HIGHLIGHT_LENGTH) return escapeHtml(text);
|
|
1418
|
+
if (name === "html") return highlightHtml(text);
|
|
1419
|
+
const rules = RULES[name];
|
|
1420
|
+
return rules ? scan(text, rules) : escapeHtml(text);
|
|
1421
|
+
}
|
|
1422
|
+
function isCodeBlock(node) {
|
|
1423
|
+
if (!node || node.nodeType !== 1 || node.tagName !== "PRE") return false;
|
|
1424
|
+
if (node.hasAttribute("data-k-lang")) return true;
|
|
1425
|
+
return Array.from(node.children).some((child) => child.tagName === "CODE");
|
|
1426
|
+
}
|
|
1427
|
+
function codeBlockAt(root, container) {
|
|
1428
|
+
var _a;
|
|
1429
|
+
let node = container || (((_a = window.getSelection()) == null ? void 0 : _a.rangeCount) ? window.getSelection().getRangeAt(0).startContainer : null);
|
|
1430
|
+
if (!node || !root || !root.contains(node)) return null;
|
|
1431
|
+
while (node && node !== root) {
|
|
1432
|
+
if (node.nodeType === 1 && node.tagName === "PRE") return isCodeBlock(node) ? node : null;
|
|
1433
|
+
node = node.parentNode;
|
|
1434
|
+
}
|
|
1435
|
+
return null;
|
|
1436
|
+
}
|
|
1437
|
+
function codeElementOf(pre) {
|
|
1438
|
+
const exist = Array.from(pre.children).find((child) => child.tagName === "CODE");
|
|
1439
|
+
if (exist) return exist;
|
|
1440
|
+
const code = document.createElement("code");
|
|
1441
|
+
while (pre.firstChild) code.appendChild(pre.firstChild);
|
|
1442
|
+
pre.appendChild(code);
|
|
1443
|
+
return code;
|
|
1444
|
+
}
|
|
1445
|
+
function languageOf(pre) {
|
|
1446
|
+
if (!pre) return "";
|
|
1447
|
+
const marked = pre.getAttribute("data-k-lang");
|
|
1448
|
+
if (marked) return normalizeLang(marked);
|
|
1449
|
+
const code = Array.from(pre.children).find((child) => child.tagName === "CODE");
|
|
1450
|
+
const matched = /(?:^|\s)language-([\w+#-]+)/.exec((code == null ? void 0 : code.className) || "");
|
|
1451
|
+
return matched ? normalizeLang(matched[1]) : "";
|
|
1452
|
+
}
|
|
1453
|
+
function applyLanguage(pre, lang) {
|
|
1454
|
+
const value = normalizeLang(lang);
|
|
1455
|
+
const code = codeElementOf(pre);
|
|
1456
|
+
pre.setAttribute("data-k-lang", value);
|
|
1457
|
+
const classes = (code.className || "").split(/\s+/).filter((name) => name && !/^language-/.test(name));
|
|
1458
|
+
if (value !== "plaintext") classes.push(`language-${value}`);
|
|
1459
|
+
code.className = classes.join(" ");
|
|
1460
|
+
if (!code.className) code.removeAttribute("class");
|
|
1461
|
+
return value;
|
|
1462
|
+
}
|
|
1463
|
+
function codeTextOf(codeEl) {
|
|
1464
|
+
const clone = codeEl.cloneNode(true);
|
|
1465
|
+
clone.querySelectorAll("br").forEach((br) => br.replaceWith("\n"));
|
|
1466
|
+
clone.querySelectorAll("div, p").forEach((node) => node.replaceWith(document.createTextNode(`
|
|
1467
|
+
${node.textContent}`)));
|
|
1468
|
+
return clone.textContent.replace(/\u00a0/g, " ");
|
|
1469
|
+
}
|
|
1470
|
+
function caretOffsetIn(el) {
|
|
1471
|
+
const sel = window.getSelection();
|
|
1472
|
+
if (!sel || !sel.rangeCount) return null;
|
|
1473
|
+
const range = sel.getRangeAt(0);
|
|
1474
|
+
if (!el.contains(range.startContainer)) return null;
|
|
1475
|
+
const before = document.createRange();
|
|
1476
|
+
before.selectNodeContents(el);
|
|
1477
|
+
before.setEnd(range.startContainer, range.startOffset);
|
|
1478
|
+
return codeTextOf(before.cloneContents());
|
|
1479
|
+
}
|
|
1480
|
+
function setCaretOffsetIn(el, offset) {
|
|
1481
|
+
const sel = window.getSelection();
|
|
1482
|
+
if (!sel) return;
|
|
1483
|
+
const apply = (node, pos) => {
|
|
1484
|
+
if (!node) return;
|
|
1485
|
+
const range = document.createRange();
|
|
1486
|
+
if (node.nodeType === 3) range.setStart(node, Math.max(0, Math.min(node.data.length, pos)));
|
|
1487
|
+
else range.setStartAfter(node);
|
|
1488
|
+
range.collapse(true);
|
|
1489
|
+
sel.removeAllRanges();
|
|
1490
|
+
sel.addRange(range);
|
|
1491
|
+
};
|
|
1492
|
+
let seen = 0;
|
|
1493
|
+
let done = false;
|
|
1494
|
+
const walk2 = (node) => {
|
|
1495
|
+
const children = Array.from(node.childNodes);
|
|
1496
|
+
for (const child of children) {
|
|
1497
|
+
if (child.nodeType === 3) {
|
|
1498
|
+
const len = child.data.length;
|
|
1499
|
+
if (seen + len >= offset) {
|
|
1500
|
+
apply(child, offset - seen);
|
|
1501
|
+
return true;
|
|
1502
|
+
}
|
|
1503
|
+
seen += len;
|
|
1504
|
+
} else if (child.nodeType === 1) {
|
|
1505
|
+
if (child.tagName === "BR") {
|
|
1506
|
+
if (seen + 1 >= offset) {
|
|
1507
|
+
apply(child);
|
|
1508
|
+
return true;
|
|
1509
|
+
}
|
|
1510
|
+
seen += 1;
|
|
1511
|
+
} else if (child.tagName === "DIV" || child.tagName === "P") {
|
|
1512
|
+
seen += 1;
|
|
1513
|
+
if (walk2(child)) return true;
|
|
1514
|
+
} else if (walk2(child)) {
|
|
1515
|
+
return true;
|
|
1516
|
+
}
|
|
1517
|
+
}
|
|
1518
|
+
}
|
|
1519
|
+
return false;
|
|
1520
|
+
};
|
|
1521
|
+
done = walk2(el);
|
|
1522
|
+
if (!done) {
|
|
1523
|
+
const range = document.createRange();
|
|
1524
|
+
range.selectNodeContents(el);
|
|
1525
|
+
range.collapse(false);
|
|
1526
|
+
sel.removeAllRanges();
|
|
1527
|
+
sel.addRange(range);
|
|
1528
|
+
}
|
|
1529
|
+
}
|
|
1530
|
+
function refreshCodeBlock(pre, { caret = false } = {}) {
|
|
1531
|
+
if (!isCodeBlock(pre)) return false;
|
|
1532
|
+
const codeEl = codeElementOf(pre);
|
|
1533
|
+
if (!pre.hasAttribute("data-k-lang")) applyLanguage(pre, languageOf(pre) || "plaintext");
|
|
1534
|
+
const text = codeTextOf(codeEl);
|
|
1535
|
+
const html = highlightCode(text, languageOf(pre));
|
|
1536
|
+
if (codeEl.innerHTML === html) return false;
|
|
1537
|
+
const offset = caret ? caretOffsetIn(codeEl) : null;
|
|
1538
|
+
codeEl.innerHTML = html;
|
|
1539
|
+
if (offset !== null) setCaretOffsetIn(codeEl, offset);
|
|
1540
|
+
return true;
|
|
1541
|
+
}
|
|
1542
|
+
function highlightCodeBlocks(root, { highlight = true } = {}) {
|
|
1543
|
+
if (!root) return 0;
|
|
1544
|
+
let count = 0;
|
|
1545
|
+
root.querySelectorAll("pre").forEach((pre) => {
|
|
1546
|
+
if (!isCodeBlock(pre)) return;
|
|
1547
|
+
const codeEl = codeElementOf(pre);
|
|
1548
|
+
if (!pre.hasAttribute("data-k-lang")) pre.setAttribute("data-k-lang", languageOf(pre) || "plaintext");
|
|
1549
|
+
const text = codeTextOf(codeEl);
|
|
1550
|
+
const html = highlight ? highlightCode(text, languageOf(pre)) : escapeHtml(text);
|
|
1551
|
+
if (codeEl.innerHTML !== html) codeEl.innerHTML = html;
|
|
1552
|
+
count += 1;
|
|
1553
|
+
});
|
|
1554
|
+
return count;
|
|
1555
|
+
}
|
|
1556
|
+
function stripHighlight(root) {
|
|
1557
|
+
if (!root) return 0;
|
|
1558
|
+
const tokens = root.querySelectorAll('span[class*="ke-tok-"]');
|
|
1559
|
+
tokens.forEach((span) => span.replaceWith(document.createTextNode(span.textContent)));
|
|
1560
|
+
if (tokens.length) root.normalize();
|
|
1561
|
+
return tokens.length;
|
|
1562
|
+
}
|
|
1563
|
+
const MD_NAME_RE = /\.(md|markdown|mdown|mkd|mkdn|mdx|txt)$/i;
|
|
1564
|
+
const MD_TYPE_RE = /^text\/(markdown|x-markdown)$|^application\/(x-)?markdown$/i;
|
|
1565
|
+
function isMarkdownFile(file) {
|
|
1566
|
+
if (!file) return false;
|
|
1567
|
+
const name = String(file.name || "");
|
|
1568
|
+
const type = String(file.type || "");
|
|
1569
|
+
if (MD_TYPE_RE.test(type)) return true;
|
|
1570
|
+
if (type && !/^text\//i.test(type)) return false;
|
|
1571
|
+
return MD_NAME_RE.test(name);
|
|
1572
|
+
}
|
|
1573
|
+
const MARKDOWN_ACCEPT = ".md,.markdown,.mdown,.mkd,.mkdn,.mdx,.txt,text/markdown,text/plain";
|
|
1574
|
+
function normalizeInsertMode(value) {
|
|
1575
|
+
return value === "append" || value === "cursor" ? value : "replace";
|
|
1576
|
+
}
|
|
1577
|
+
async function readMarkdownFile(file) {
|
|
1578
|
+
if (!file) return "";
|
|
1579
|
+
if (typeof file.arrayBuffer !== "function") return String(await file.text());
|
|
1580
|
+
const buffer = await file.arrayBuffer();
|
|
1581
|
+
try {
|
|
1582
|
+
return decode(buffer, "utf-8", true);
|
|
1583
|
+
} catch {
|
|
1584
|
+
for (const charset of ["gb18030", "gbk", "big5"]) {
|
|
1585
|
+
try {
|
|
1586
|
+
return decode(buffer, charset, true);
|
|
1587
|
+
} catch {
|
|
1588
|
+
}
|
|
1589
|
+
}
|
|
1590
|
+
return decode(buffer, "utf-8", false);
|
|
1591
|
+
}
|
|
1592
|
+
}
|
|
1593
|
+
function decode(buffer, charset, fatal) {
|
|
1594
|
+
return new TextDecoder(charset, { fatal }).decode(buffer);
|
|
1595
|
+
}
|
|
1596
|
+
const ATX_RE = /^ {0,3}(#{1,6})(?:[ \t]+(.*?))?[ \t]*#*[ \t]*$/;
|
|
1597
|
+
const SETEXT_RE = /^ {0,3}(=+|-+)[ \t]*$/;
|
|
1598
|
+
const HR_RE = /^ {0,3}(?:(?:\*[ \t]*){3,}|(?:-[ \t]*){3,}|(?:_[ \t]*){3,})$/;
|
|
1599
|
+
const FENCE_RE = /^( {0,3})(`{3,}|~{3,})[ \t]*([^`\n]*)$/;
|
|
1600
|
+
const QUOTE_RE = /^ {0,3}>/;
|
|
1601
|
+
const REF_DEF_RE = /^ {0,3}\[([^\]]+)\]:[ \t]*<?([^\s>]+)>?(?:[ \t]+(?:"([^"]*)"|'([^']*)'|\(([^)]*)\)))?[ \t]*$/;
|
|
1602
|
+
const TABLE_DELIM_RE = /^ {0,3}\|?[ \t]*:?-+:?[ \t]*(?:\|[ \t]*:?-+:?[ \t]*)*\|?[ \t]*$/;
|
|
1603
|
+
const HTML_BLOCK_RE = /^ {0,3}<(\/?)([A-Za-z][\w-]*)(\s|\/?>|$)/;
|
|
1604
|
+
const HTML_BLOCK_TAGS = /* @__PURE__ */ new Set([
|
|
1605
|
+
"div",
|
|
1606
|
+
"section",
|
|
1607
|
+
"article",
|
|
1608
|
+
"aside",
|
|
1609
|
+
"header",
|
|
1610
|
+
"footer",
|
|
1611
|
+
"main",
|
|
1612
|
+
"nav",
|
|
1613
|
+
"center",
|
|
1614
|
+
"font",
|
|
1615
|
+
"span",
|
|
1616
|
+
"table",
|
|
1617
|
+
"thead",
|
|
1618
|
+
"tbody",
|
|
1619
|
+
"tfoot",
|
|
1620
|
+
"tr",
|
|
1621
|
+
"td",
|
|
1622
|
+
"th",
|
|
1623
|
+
"caption",
|
|
1624
|
+
"colgroup",
|
|
1625
|
+
"col",
|
|
1626
|
+
"dl",
|
|
1627
|
+
"dt",
|
|
1628
|
+
"dd",
|
|
1629
|
+
"figure",
|
|
1630
|
+
"figcaption",
|
|
1631
|
+
"details",
|
|
1632
|
+
"summary",
|
|
1633
|
+
"pre",
|
|
1634
|
+
"hr",
|
|
1635
|
+
"br",
|
|
1636
|
+
"img",
|
|
1637
|
+
"a",
|
|
1638
|
+
"video",
|
|
1639
|
+
"source",
|
|
1640
|
+
"p",
|
|
1641
|
+
"ul",
|
|
1642
|
+
"ol",
|
|
1643
|
+
"li",
|
|
1644
|
+
"blockquote",
|
|
1645
|
+
"h1",
|
|
1646
|
+
"h2",
|
|
1647
|
+
"h3",
|
|
1648
|
+
"h4",
|
|
1649
|
+
"h5",
|
|
1650
|
+
"h6",
|
|
1651
|
+
"strong",
|
|
1652
|
+
"em",
|
|
1653
|
+
"b",
|
|
1654
|
+
"i",
|
|
1655
|
+
"u",
|
|
1656
|
+
"s",
|
|
1657
|
+
"del",
|
|
1658
|
+
"ins",
|
|
1659
|
+
"mark",
|
|
1660
|
+
"code",
|
|
1661
|
+
"kbd",
|
|
1662
|
+
"samp",
|
|
1663
|
+
"small",
|
|
1664
|
+
"sub",
|
|
1665
|
+
"sup",
|
|
1666
|
+
"abbr",
|
|
1667
|
+
"time"
|
|
1668
|
+
]);
|
|
1669
|
+
const INLINE_HTML_TAGS = /* @__PURE__ */ new Set([
|
|
1670
|
+
"a",
|
|
1671
|
+
"img",
|
|
1672
|
+
"br",
|
|
1673
|
+
"wbr",
|
|
1674
|
+
"em",
|
|
1675
|
+
"i",
|
|
1676
|
+
"strong",
|
|
1677
|
+
"b",
|
|
1678
|
+
"u",
|
|
1679
|
+
"s",
|
|
1680
|
+
"del",
|
|
1681
|
+
"ins",
|
|
1682
|
+
"mark",
|
|
1683
|
+
"sub",
|
|
1684
|
+
"sup",
|
|
1685
|
+
"kbd",
|
|
1686
|
+
"code",
|
|
1687
|
+
"samp",
|
|
1688
|
+
"var",
|
|
1689
|
+
"span",
|
|
1690
|
+
"small",
|
|
1691
|
+
"abbr",
|
|
1692
|
+
"cite",
|
|
1693
|
+
"q",
|
|
1694
|
+
"time",
|
|
1695
|
+
"font",
|
|
1696
|
+
"sup"
|
|
1697
|
+
]);
|
|
1698
|
+
const INLINE_TAG_RE = /^<(\/?)([A-Za-z][A-Za-z0-9-]*)((?:\s+[^<>]*?)?)(\/?)>/;
|
|
1699
|
+
const AUTOLINK_RE = /^<([A-Za-z][A-Za-z0-9+.-]{1,31}:[^<>\s]*)>/;
|
|
1700
|
+
const EMAIL_RE = /^<([^\s<>@]+@[^\s<>@]+\.[^\s<>@]+)>/;
|
|
1701
|
+
const ESCAPABLE_RE = /[!-/:-@[-`{-~]/;
|
|
1702
|
+
const ASCII_PUNCT_RE = /[!-/:-@[-`{-~]/;
|
|
1703
|
+
const URL_RE = /(^|[\s(([【>])((?:https?:\/\/|www\.)[^\s<>()"']*[^\s<>()"'.,;:!?、。,;:!?])/g;
|
|
1704
|
+
function normalizeOptions(options) {
|
|
1705
|
+
return {
|
|
1706
|
+
gfm: options.gfm !== false,
|
|
1707
|
+
breaks: !!options.breaks,
|
|
1708
|
+
linkTarget: options.linkTarget || false,
|
|
1709
|
+
frontMatter: options.frontMatter !== false,
|
|
1710
|
+
sanitize: options.sanitize !== false
|
|
1711
|
+
};
|
|
1712
|
+
}
|
|
1713
|
+
function markdownToHtml(input, options = {}) {
|
|
1714
|
+
if (input === null || input === void 0) return "";
|
|
1715
|
+
const opts = normalizeOptions(options);
|
|
1716
|
+
let text = String(input).replace(/^\uFEFF/, "").replace(/\r\n?/g, "\n").replace(/\u0000/g, "");
|
|
1717
|
+
text = text.replace(/\t/g, " ");
|
|
1718
|
+
if (opts.frontMatter) text = stripFrontMatter(text);
|
|
1719
|
+
const refs = /* @__PURE__ */ new Map();
|
|
1720
|
+
const nodes = parseBlocks(text.split("\n"), refs, opts);
|
|
1721
|
+
const html = nodes.map((node) => renderBlock(node, refs, opts)).join("\n");
|
|
1722
|
+
if (!opts.sanitize) return html;
|
|
1723
|
+
return sanitizeHtml(html, { allowEmpty: true });
|
|
1724
|
+
}
|
|
1725
|
+
function markdownSummary(html) {
|
|
1726
|
+
const count = (re) => (String(html || "").match(re) || []).length;
|
|
1727
|
+
return {
|
|
1728
|
+
headings: count(/<h[1-6][\s>]/g),
|
|
1729
|
+
paragraphs: count(/<p[\s>]/g),
|
|
1730
|
+
lists: count(/<[uo]l[\s>]/g),
|
|
1731
|
+
items: count(/<li[\s>]/g),
|
|
1732
|
+
codeBlocks: count(/<pre[\s>]/g),
|
|
1733
|
+
quotes: count(/<blockquote[\s>]/g),
|
|
1734
|
+
tables: count(/<table[\s>]/g),
|
|
1735
|
+
images: count(/<img[\s>]/g),
|
|
1736
|
+
links: count(/<a\s[^>]*href=/g)
|
|
1737
|
+
};
|
|
1738
|
+
}
|
|
1739
|
+
function stripFrontMatter(text) {
|
|
1740
|
+
const matched = /^---[ \t]*\n([\s\S]*?)\n(?:---|\.\.\.)[ \t]*(?:\n|$)/.exec(text);
|
|
1741
|
+
return matched ? text.slice(matched[0].length) : text;
|
|
1742
|
+
}
|
|
1743
|
+
const isBlank = (line) => !line || !line.trim();
|
|
1744
|
+
const indentOf = (line) => line.length - line.replace(/^ +/, "").length;
|
|
1745
|
+
function matchList(line) {
|
|
1746
|
+
const matched = /^( *)([-+*]|\d{1,9}[.)])([ \t]*)([\s\S]*)$/.exec(line);
|
|
1747
|
+
if (!matched) return null;
|
|
1748
|
+
const [, lead, marker, gap, rest] = matched;
|
|
1749
|
+
if (gap.length === 0 && rest.length) return null;
|
|
1750
|
+
if (rest.length === 0 && gap.length === 0 && !/^[-+*]$/.test(marker)) return null;
|
|
1751
|
+
const ordered = /^\d/.test(marker);
|
|
1752
|
+
const pad = gap.length || 1;
|
|
1753
|
+
return {
|
|
1754
|
+
indent: lead.length,
|
|
1755
|
+
marker,
|
|
1756
|
+
ordered,
|
|
1757
|
+
start: ordered ? parseInt(marker, 10) || 1 : 1,
|
|
1758
|
+
contentIndent: lead.length + marker.length + pad,
|
|
1759
|
+
text: rest
|
|
1760
|
+
};
|
|
1761
|
+
}
|
|
1762
|
+
function startsNewBlock(line, opts) {
|
|
1763
|
+
return ATX_RE.test(line) || FENCE_RE.test(line) || HR_RE.test(line) || QUOTE_RE.test(line) || HTML_BLOCK_RE.test(line) || !!matchList(line) || opts.gfm && TABLE_DELIM_RE.test(line);
|
|
1764
|
+
}
|
|
1765
|
+
function parseBlocks(lines, refs, opts, depth) {
|
|
1766
|
+
const nodes = [];
|
|
1767
|
+
let i = 0;
|
|
1768
|
+
while (i < lines.length) {
|
|
1769
|
+
const line = lines[i];
|
|
1770
|
+
if (isBlank(line)) {
|
|
1771
|
+
i += 1;
|
|
1772
|
+
continue;
|
|
1773
|
+
}
|
|
1774
|
+
const fence = FENCE_RE.exec(line);
|
|
1775
|
+
if (fence) {
|
|
1776
|
+
const indent = fence[1].length;
|
|
1777
|
+
const marker = fence[2];
|
|
1778
|
+
const info = fence[3].trim();
|
|
1779
|
+
const body = [];
|
|
1780
|
+
i += 1;
|
|
1781
|
+
while (i < lines.length) {
|
|
1782
|
+
const closing = FENCE_RE.exec(lines[i]);
|
|
1783
|
+
if (closing && closing[2][0] === marker[0] && closing[2].length >= marker.length && !closing[3].trim()) break;
|
|
1784
|
+
body.push(indent ? lines[i].slice(0, indent).trim() ? lines[i] : lines[i].slice(indent) : lines[i]);
|
|
1785
|
+
i += 1;
|
|
1786
|
+
}
|
|
1787
|
+
if (i < lines.length) i += 1;
|
|
1788
|
+
nodes.push({ t: "code", lang: firstWord(info), text: body.join("\n") });
|
|
1789
|
+
continue;
|
|
1790
|
+
}
|
|
1791
|
+
if (/^ {4}/.test(line) && !matchList(line.replace(/^ {4}/, ""))) {
|
|
1792
|
+
const body = [];
|
|
1793
|
+
while (i < lines.length && (isBlank(lines[i]) ? hasCodeAfterBlank(lines, i) : /^ {4}/.test(lines[i]))) {
|
|
1794
|
+
body.push(lines[i].slice(4));
|
|
1795
|
+
i += 1;
|
|
1796
|
+
}
|
|
1797
|
+
while (body.length && isBlank(body[body.length - 1])) body.pop();
|
|
1798
|
+
nodes.push({ t: "code", lang: "", text: body.join("\n") });
|
|
1799
|
+
continue;
|
|
1800
|
+
}
|
|
1801
|
+
const atx = ATX_RE.exec(line);
|
|
1802
|
+
if (atx) {
|
|
1803
|
+
nodes.push({ t: "h", level: atx[1].length, raw: (atx[2] || "").replace(/[ \t]+#+[ \t]*$/, "").trim() });
|
|
1804
|
+
i += 1;
|
|
1805
|
+
continue;
|
|
1806
|
+
}
|
|
1807
|
+
if (HR_RE.test(line)) {
|
|
1808
|
+
nodes.push({ t: "hr" });
|
|
1809
|
+
i += 1;
|
|
1810
|
+
continue;
|
|
1811
|
+
}
|
|
1812
|
+
if (QUOTE_RE.test(line)) {
|
|
1813
|
+
const inner = [];
|
|
1814
|
+
while (i < lines.length) {
|
|
1815
|
+
const current = lines[i];
|
|
1816
|
+
if (QUOTE_RE.test(current)) {
|
|
1817
|
+
inner.push(current.replace(/^ {0,3}> ?/, ""));
|
|
1818
|
+
i += 1;
|
|
1819
|
+
continue;
|
|
1820
|
+
}
|
|
1821
|
+
if (isBlank(current)) break;
|
|
1822
|
+
if (startsNewBlock(current, opts)) break;
|
|
1823
|
+
inner.push(current);
|
|
1824
|
+
i += 1;
|
|
1825
|
+
}
|
|
1826
|
+
nodes.push({ t: "quote", children: parseBlocks(inner, refs, opts) });
|
|
1827
|
+
continue;
|
|
1828
|
+
}
|
|
1829
|
+
const list = matchList(line);
|
|
1830
|
+
if (list) {
|
|
1831
|
+
const parsed = parseList(lines, i, list, refs, opts);
|
|
1832
|
+
nodes.push(parsed.node);
|
|
1833
|
+
i = parsed.next;
|
|
1834
|
+
continue;
|
|
1835
|
+
}
|
|
1836
|
+
if (opts.gfm && line.includes("|") && i + 1 < lines.length && TABLE_DELIM_RE.test(lines[i + 1]) && lines[i + 1].includes("-")) {
|
|
1837
|
+
const parsed = parseTable(lines, i, refs, opts);
|
|
1838
|
+
nodes.push(parsed.node);
|
|
1839
|
+
i = parsed.next;
|
|
1840
|
+
continue;
|
|
1841
|
+
}
|
|
1842
|
+
const htmlStart = HTML_BLOCK_RE.exec(line);
|
|
1843
|
+
if (htmlStart && HTML_BLOCK_TAGS.has(htmlStart[2].toLowerCase())) {
|
|
1844
|
+
const raw = [];
|
|
1845
|
+
while (i < lines.length && !isBlank(lines[i])) {
|
|
1846
|
+
raw.push(lines[i]);
|
|
1847
|
+
i += 1;
|
|
1848
|
+
}
|
|
1849
|
+
nodes.push({ t: "html", raw: raw.join("\n") });
|
|
1850
|
+
continue;
|
|
1851
|
+
}
|
|
1852
|
+
const paragraph = [];
|
|
1853
|
+
let setext = null;
|
|
1854
|
+
while (i < lines.length && !isBlank(lines[i])) {
|
|
1855
|
+
const current = lines[i];
|
|
1856
|
+
if (paragraph.length === 1 && SETEXT_RE.test(current)) {
|
|
1857
|
+
setext = current.trim()[0] === "=" ? 1 : 2;
|
|
1858
|
+
i += 1;
|
|
1859
|
+
break;
|
|
1860
|
+
}
|
|
1861
|
+
if (paragraph.length > 0 && startsNewBlock(current, opts)) break;
|
|
1862
|
+
if (paragraph.length === 0) {
|
|
1863
|
+
const def = REF_DEF_RE.exec(current);
|
|
1864
|
+
if (def) {
|
|
1865
|
+
registerRef(refs, def);
|
|
1866
|
+
i += 1;
|
|
1867
|
+
continue;
|
|
1868
|
+
}
|
|
1869
|
+
}
|
|
1870
|
+
const hard = /(?: {2,}|\\)$/.test(current);
|
|
1871
|
+
paragraph.push(hard ? current.replace(/(?: +|\\)$/, "") : current);
|
|
1872
|
+
if (hard) paragraph[paragraph.length - 1] += "";
|
|
1873
|
+
i += 1;
|
|
1874
|
+
}
|
|
1875
|
+
if (paragraph.length) {
|
|
1876
|
+
const raw = paragraph.join("\n").replace(/\u0001\n/g, "");
|
|
1877
|
+
if (setext) nodes.push({ t: "h", level: setext, raw: raw.trim() });
|
|
1878
|
+
else nodes.push({ t: "p", raw });
|
|
1879
|
+
}
|
|
1880
|
+
}
|
|
1881
|
+
return nodes;
|
|
1882
|
+
}
|
|
1883
|
+
function hasCodeAfterBlank(lines, i) {
|
|
1884
|
+
let j = i;
|
|
1885
|
+
while (j < lines.length && isBlank(lines[j])) j += 1;
|
|
1886
|
+
return j < lines.length && /^ {4}/.test(lines[j]);
|
|
1887
|
+
}
|
|
1888
|
+
function registerRef(refs, matched) {
|
|
1889
|
+
const key = normalizeLabel(matched[1]);
|
|
1890
|
+
if (!key || refs.has(key)) return;
|
|
1891
|
+
refs.set(key, { href: matched[2] || "", title: matched[3] ?? matched[4] ?? matched[5] ?? "" });
|
|
1892
|
+
}
|
|
1893
|
+
function normalizeLabel(label) {
|
|
1894
|
+
return String(label || "").trim().replace(/\s+/g, " ").toLowerCase();
|
|
1895
|
+
}
|
|
1896
|
+
function firstWord(info) {
|
|
1897
|
+
const value = String(info || "").trim();
|
|
1898
|
+
if (!value) return "";
|
|
1899
|
+
return value.split(/\s+/)[0];
|
|
1900
|
+
}
|
|
1901
|
+
function parseList(lines, start, first2, refs, opts, depth) {
|
|
1902
|
+
const type = first2.ordered ? "ol" : "ul";
|
|
1903
|
+
const baseIndent = first2.indent;
|
|
1904
|
+
const items = [];
|
|
1905
|
+
let loose = false;
|
|
1906
|
+
let i = start;
|
|
1907
|
+
while (i < lines.length) {
|
|
1908
|
+
const marker = matchList(lines[i]);
|
|
1909
|
+
if (!marker || marker.indent !== baseIndent || marker.ordered !== first2.ordered) break;
|
|
1910
|
+
const contentIndent = marker.contentIndent;
|
|
1911
|
+
const body = [marker.text];
|
|
1912
|
+
i += 1;
|
|
1913
|
+
let blanks = 0;
|
|
1914
|
+
while (i < lines.length) {
|
|
1915
|
+
const current = lines[i];
|
|
1916
|
+
if (isBlank(current)) {
|
|
1917
|
+
body.push("");
|
|
1918
|
+
blanks += 1;
|
|
1919
|
+
i += 1;
|
|
1920
|
+
continue;
|
|
1921
|
+
}
|
|
1922
|
+
const lead = indentOf(current);
|
|
1923
|
+
const next = matchList(current);
|
|
1924
|
+
if (next && lead <= baseIndent) break;
|
|
1925
|
+
if (lead >= contentIndent) {
|
|
1926
|
+
body.push(current.slice(contentIndent));
|
|
1927
|
+
if (blanks > 0) loose = true;
|
|
1928
|
+
blanks = 0;
|
|
1929
|
+
i += 1;
|
|
1930
|
+
continue;
|
|
1931
|
+
}
|
|
1932
|
+
if (blanks > 0) break;
|
|
1933
|
+
if (startsNewBlock(current, opts)) break;
|
|
1934
|
+
body.push(current.replace(/^ {0,3}/, ""));
|
|
1935
|
+
i += 1;
|
|
1936
|
+
}
|
|
1937
|
+
while (body.length && isBlank(body[body.length - 1])) body.pop();
|
|
1938
|
+
if (blanks > 0) {
|
|
1939
|
+
const nextItem = i < lines.length ? matchList(lines[i]) : null;
|
|
1940
|
+
if (nextItem && nextItem.indent === baseIndent && nextItem.ordered === first2.ordered) loose = true;
|
|
1941
|
+
}
|
|
1942
|
+
items.push(makeItem(body, type, refs, opts));
|
|
1943
|
+
}
|
|
1944
|
+
return { node: { t: type, start: first2.start, loose, items }, next: i };
|
|
1945
|
+
}
|
|
1946
|
+
function makeItem(body, type, refs, opts) {
|
|
1947
|
+
let checked = null;
|
|
1948
|
+
if (type === "ul" && body.length) {
|
|
1949
|
+
const task = /^\[([ xX])\][ \t]+/.exec(body[0]);
|
|
1950
|
+
if (task) {
|
|
1951
|
+
checked = task[1].toLowerCase() === "x";
|
|
1952
|
+
body[0] = body[0].slice(task[0].length);
|
|
1953
|
+
}
|
|
1954
|
+
}
|
|
1955
|
+
return { checked, children: parseBlocks(body, refs, opts) };
|
|
1956
|
+
}
|
|
1957
|
+
function parseTable(lines, start, refs, opts) {
|
|
1958
|
+
const header = splitRow(lines[start]);
|
|
1959
|
+
const delims = splitRow(lines[start + 1]).map((cell) => {
|
|
1960
|
+
const value = cell.trim();
|
|
1961
|
+
if (/^:-+:$/.test(value)) return "center";
|
|
1962
|
+
if (/^-+:$/.test(value)) return "right";
|
|
1963
|
+
return "left";
|
|
1964
|
+
});
|
|
1965
|
+
const rows = [];
|
|
1966
|
+
let i = start + 2;
|
|
1967
|
+
while (i < lines.length && !isBlank(lines[i]) && lines[i].includes("|") && !startsNewBlock(lines[i], opts)) {
|
|
1968
|
+
rows.push(splitRow(lines[i]));
|
|
1969
|
+
i += 1;
|
|
1970
|
+
}
|
|
1971
|
+
const width = Math.max(header.length, delims.length);
|
|
1972
|
+
const pad = (cells) => {
|
|
1973
|
+
const out = cells.slice(0, width);
|
|
1974
|
+
while (out.length < width) out.push("");
|
|
1975
|
+
return out;
|
|
1976
|
+
};
|
|
1977
|
+
return { node: { t: "table", align: pad(delims), head: pad(header), rows: rows.map(pad) }, next: i };
|
|
1978
|
+
}
|
|
1979
|
+
function splitRow(line) {
|
|
1980
|
+
let value = line.trim();
|
|
1981
|
+
if (value.startsWith("|")) value = value.slice(1);
|
|
1982
|
+
if (value.endsWith("|") && !value.endsWith("\\|")) value = value.slice(0, -1);
|
|
1983
|
+
const cells = [];
|
|
1984
|
+
let buffer = "";
|
|
1985
|
+
for (let i = 0; i < value.length; i += 1) {
|
|
1986
|
+
const ch = value[i];
|
|
1987
|
+
if (ch === "\\" && value[i + 1] === "|") {
|
|
1988
|
+
buffer += "\\|";
|
|
1989
|
+
i += 1;
|
|
1990
|
+
continue;
|
|
1991
|
+
}
|
|
1992
|
+
if (ch === "|") {
|
|
1993
|
+
cells.push(buffer);
|
|
1994
|
+
buffer = "";
|
|
1995
|
+
continue;
|
|
1996
|
+
}
|
|
1997
|
+
buffer += ch;
|
|
1998
|
+
}
|
|
1999
|
+
cells.push(buffer);
|
|
2000
|
+
return cells.map((cell) => cell.trim());
|
|
2001
|
+
}
|
|
2002
|
+
function inline(text, refs, opts) {
|
|
2003
|
+
return serialize(inlineNodes(String(text || ""), refs, opts), refs, opts);
|
|
2004
|
+
}
|
|
2005
|
+
function inlineNodes(text, refs, opts, inLink = false) {
|
|
2006
|
+
return processEmphasis(tokenize(text, refs, opts, inLink));
|
|
2007
|
+
}
|
|
2008
|
+
function tokenize(text, refs, opts, inLink = false) {
|
|
2009
|
+
const nodes = [];
|
|
2010
|
+
const pushText = (value) => {
|
|
2011
|
+
if (!value) return;
|
|
2012
|
+
const last = nodes[nodes.length - 1];
|
|
2013
|
+
if (last && last.type === "text" && last.bare) last.value += value;
|
|
2014
|
+
else nodes.push({ type: "text", value, bare: true });
|
|
2015
|
+
};
|
|
2016
|
+
let i = 0;
|
|
2017
|
+
while (i < text.length) {
|
|
2018
|
+
const ch = text[i];
|
|
2019
|
+
if (ch === "\\") {
|
|
2020
|
+
const next = text[i + 1];
|
|
2021
|
+
if (next === "\n") {
|
|
2022
|
+
nodes.push({ type: "br" });
|
|
2023
|
+
i += 2;
|
|
2024
|
+
continue;
|
|
2025
|
+
}
|
|
2026
|
+
if (next && ESCAPABLE_RE.test(next)) {
|
|
2027
|
+
pushText(next);
|
|
2028
|
+
i += 2;
|
|
2029
|
+
continue;
|
|
2030
|
+
}
|
|
2031
|
+
pushText("\\");
|
|
2032
|
+
i += 1;
|
|
2033
|
+
continue;
|
|
2034
|
+
}
|
|
2035
|
+
if (ch === "`") {
|
|
2036
|
+
const run = /^`+/.exec(text.slice(i))[0];
|
|
2037
|
+
const close = findCodeFence(text, i + run.length, run);
|
|
2038
|
+
if (close < 0) {
|
|
2039
|
+
pushText(run);
|
|
2040
|
+
i += run.length;
|
|
2041
|
+
continue;
|
|
2042
|
+
}
|
|
2043
|
+
let value2 = text.slice(i + run.length, close).replace(/\n/g, " ");
|
|
2044
|
+
if (value2.length > 2 && /^ .* $/.test(value2) && /[^ ]/.test(value2)) value2 = value2.slice(1, -1);
|
|
2045
|
+
nodes.push({ type: "code", value: value2 });
|
|
2046
|
+
i = close + run.length;
|
|
2047
|
+
continue;
|
|
2048
|
+
}
|
|
2049
|
+
if (ch === "[" || ch === "!" && text[i + 1] === "[") {
|
|
2050
|
+
const image = ch === "!";
|
|
2051
|
+
const parsed = parseLink(text, image ? i + 1 : i, refs, opts, image);
|
|
2052
|
+
if (parsed) {
|
|
2053
|
+
nodes.push(parsed.node);
|
|
2054
|
+
i = parsed.next;
|
|
2055
|
+
continue;
|
|
2056
|
+
}
|
|
2057
|
+
}
|
|
2058
|
+
if (ch === "<") {
|
|
2059
|
+
const auto = AUTOLINK_RE.exec(text.slice(i));
|
|
2060
|
+
if (auto) {
|
|
2061
|
+
nodes.push({ type: "link", href: auto[1], title: "", children: [{ type: "text", value: auto[1], bare: false }] });
|
|
2062
|
+
i += auto[0].length;
|
|
2063
|
+
continue;
|
|
2064
|
+
}
|
|
2065
|
+
const mail = EMAIL_RE.exec(text.slice(i));
|
|
2066
|
+
if (mail) {
|
|
2067
|
+
nodes.push({ type: "link", href: `mailto:${mail[1]}`, title: "", children: [{ type: "text", value: mail[1], bare: false }] });
|
|
2068
|
+
i += mail[0].length;
|
|
2069
|
+
continue;
|
|
2070
|
+
}
|
|
2071
|
+
const tag = INLINE_TAG_RE.exec(text.slice(i));
|
|
2072
|
+
if (tag && INLINE_HTML_TAGS.has(tag[2].toLowerCase())) {
|
|
2073
|
+
nodes.push({ type: "html", value: scrubUrls(tag[0]) });
|
|
2074
|
+
i += tag[0].length;
|
|
2075
|
+
continue;
|
|
2076
|
+
}
|
|
2077
|
+
pushText("<");
|
|
2078
|
+
i += 1;
|
|
2079
|
+
continue;
|
|
2080
|
+
}
|
|
2081
|
+
if (ch === "\n") {
|
|
2082
|
+
const prev = nodes[nodes.length - 1];
|
|
2083
|
+
const hard = opts.breaks || prev && prev.type === "text" && / {2,}$/.test(prev.value);
|
|
2084
|
+
if (prev && prev.type === "text") prev.value = prev.value.replace(/[ \t]+$/, "");
|
|
2085
|
+
if (hard) nodes.push({ type: "br" });
|
|
2086
|
+
else pushText("\n");
|
|
2087
|
+
i += 1;
|
|
2088
|
+
continue;
|
|
2089
|
+
}
|
|
2090
|
+
if (ch === "*" || ch === "_" || ch === "~" && opts.gfm) {
|
|
2091
|
+
const run = new RegExp(`^\\${ch}+`).exec(text.slice(i))[0];
|
|
2092
|
+
const prev = text[i - 1] || "";
|
|
2093
|
+
const next = text[i + run.length] || "";
|
|
2094
|
+
const nodes2 = computeFlanking(ch, run, prev, next);
|
|
2095
|
+
nodes.push({ type: "delim", char: ch, count: run.length, canOpen: nodes2.canOpen, canClose: nodes2.canClose });
|
|
2096
|
+
i += run.length;
|
|
2097
|
+
continue;
|
|
2098
|
+
}
|
|
2099
|
+
const plain = /^[^\\`[<!*_~\n]+/.exec(text.slice(i));
|
|
2100
|
+
const value = plain ? plain[0] : ch;
|
|
2101
|
+
if (opts.gfm && !inLink) pushAutolinks(nodes, value);
|
|
2102
|
+
else pushText(value);
|
|
2103
|
+
i += value.length;
|
|
2104
|
+
}
|
|
2105
|
+
return nodes;
|
|
2106
|
+
}
|
|
2107
|
+
function findCodeFence(text, from, run) {
|
|
2108
|
+
let at = text.indexOf(run, from);
|
|
2109
|
+
while (at >= 0) {
|
|
2110
|
+
const before = text[at - 1];
|
|
2111
|
+
const after = text[at + run.length];
|
|
2112
|
+
if (before !== "`" && after !== "`") return at;
|
|
2113
|
+
at = text.indexOf(run, at + 1);
|
|
2114
|
+
}
|
|
2115
|
+
return -1;
|
|
2116
|
+
}
|
|
2117
|
+
function computeFlanking(char, run, prev, next) {
|
|
2118
|
+
const prevChar = prev ? prev === "\n" ? "\n" : prev : "";
|
|
2119
|
+
const nextChar = next ? next : "";
|
|
2120
|
+
const prevWs = !prevChar || /\s/.test(prevChar);
|
|
2121
|
+
const nextWs = !nextChar || /\s/.test(nextChar);
|
|
2122
|
+
const prevPunct = !!prevChar && ASCII_PUNCT_RE.test(prevChar);
|
|
2123
|
+
const nextPunct = !!nextChar && ASCII_PUNCT_RE.test(nextChar);
|
|
2124
|
+
const leftFlanking = !nextWs && (!nextPunct || prevWs || prevPunct);
|
|
2125
|
+
const rightFlanking = !prevWs && (!prevPunct || nextWs || nextPunct);
|
|
2126
|
+
if (char === "_") {
|
|
2127
|
+
return {
|
|
2128
|
+
canOpen: leftFlanking && (!rightFlanking || prevPunct),
|
|
2129
|
+
canClose: rightFlanking && (!leftFlanking || nextPunct)
|
|
2130
|
+
};
|
|
2131
|
+
}
|
|
2132
|
+
return { canOpen: leftFlanking, canClose: rightFlanking };
|
|
2133
|
+
}
|
|
2134
|
+
function pushAutolinks(nodes, value) {
|
|
2135
|
+
let last = 0;
|
|
2136
|
+
URL_RE.lastIndex = 0;
|
|
2137
|
+
let matched;
|
|
2138
|
+
while (matched = URL_RE.exec(value)) {
|
|
2139
|
+
const start = matched.index + matched[1].length;
|
|
2140
|
+
if (start > last) pushTextNode(nodes, value.slice(last, start));
|
|
2141
|
+
const href = /^www\./i.test(matched[2]) ? `http://${matched[2]}` : matched[2];
|
|
2142
|
+
nodes.push({ type: "link", href, title: "", children: [{ type: "text", value: matched[2], bare: false }] });
|
|
2143
|
+
last = start + matched[2].length;
|
|
2144
|
+
}
|
|
2145
|
+
if (last < value.length) pushTextNode(nodes, value.slice(last));
|
|
2146
|
+
}
|
|
2147
|
+
function pushTextNode(nodes, value) {
|
|
2148
|
+
if (!value) return;
|
|
2149
|
+
const last = nodes[nodes.length - 1];
|
|
2150
|
+
if (last && last.type === "text" && last.bare) last.value += value;
|
|
2151
|
+
else nodes.push({ type: "text", value, bare: true });
|
|
2152
|
+
}
|
|
2153
|
+
function parseLink(text, bracketAt, refs, opts, image) {
|
|
2154
|
+
const label = findBracketEnd(text, bracketAt);
|
|
2155
|
+
if (label < 0) return null;
|
|
2156
|
+
const inner = text.slice(bracketAt + 1, label);
|
|
2157
|
+
let i = label + 1;
|
|
2158
|
+
let href = null;
|
|
2159
|
+
let title = "";
|
|
2160
|
+
if (text[i] === "(") {
|
|
2161
|
+
const dest = parseDestination(text, i);
|
|
2162
|
+
if (!dest) return null;
|
|
2163
|
+
href = dest.href;
|
|
2164
|
+
title = dest.title;
|
|
2165
|
+
i = dest.next;
|
|
2166
|
+
} else if (text[i] === "[") {
|
|
2167
|
+
const close = text.indexOf("]", i + 1);
|
|
2168
|
+
if (close < 0) return null;
|
|
2169
|
+
const key = normalizeLabel(text.slice(i + 1, close) || inner);
|
|
2170
|
+
const ref = refs.get(key);
|
|
2171
|
+
if (!ref) return null;
|
|
2172
|
+
href = ref.href;
|
|
2173
|
+
title = ref.title;
|
|
2174
|
+
i = close + 1;
|
|
2175
|
+
} else {
|
|
2176
|
+
const ref = refs.get(normalizeLabel(inner));
|
|
2177
|
+
if (!ref) return null;
|
|
2178
|
+
href = ref.href;
|
|
2179
|
+
title = ref.title;
|
|
2180
|
+
}
|
|
2181
|
+
if (image) {
|
|
2182
|
+
if (!isSafeUrl(href)) return { node: { type: "text", value: `![${inner}]` }, next: i };
|
|
2183
|
+
return { node: { type: "image", src: href, title, alt: plainOf(inner) }, next: i };
|
|
2184
|
+
}
|
|
2185
|
+
const children = inlineNodes(inner, refs, opts, true);
|
|
2186
|
+
return { node: { type: "link", href, title, children }, next: i };
|
|
2187
|
+
}
|
|
2188
|
+
function plainOf(nodes) {
|
|
2189
|
+
if (typeof nodes === "string") return nodes.replace(/[*_~`]/g, "");
|
|
2190
|
+
return "";
|
|
2191
|
+
}
|
|
2192
|
+
function findBracketEnd(text, open) {
|
|
2193
|
+
let depth = 0;
|
|
2194
|
+
for (let i = open; i < text.length; i += 1) {
|
|
2195
|
+
const ch = text[i];
|
|
2196
|
+
if (ch === "\\") {
|
|
2197
|
+
i += 1;
|
|
2198
|
+
continue;
|
|
2199
|
+
}
|
|
2200
|
+
if (ch === "`") {
|
|
2201
|
+
const run = /^`+/.exec(text.slice(i))[0];
|
|
2202
|
+
const close = findCodeFence(text, i + run.length, run);
|
|
2203
|
+
i = close < 0 ? i + run.length - 1 : close + run.length - 1;
|
|
2204
|
+
continue;
|
|
2205
|
+
}
|
|
2206
|
+
if (ch === "[") depth += 1;
|
|
2207
|
+
else if (ch === "]") {
|
|
2208
|
+
depth -= 1;
|
|
2209
|
+
if (depth === 0) return i;
|
|
2210
|
+
} else if (ch === "\n" && depth === 1 && text[i + 1] === "\n") return -1;
|
|
2211
|
+
}
|
|
2212
|
+
return -1;
|
|
2213
|
+
}
|
|
2214
|
+
function parseDestination(text, open) {
|
|
2215
|
+
let i = open + 1;
|
|
2216
|
+
while (text[i] === " " || text[i] === "\n") i += 1;
|
|
2217
|
+
let href = "";
|
|
2218
|
+
if (text[i] === "<") {
|
|
2219
|
+
const close = text.indexOf(">", i + 1);
|
|
2220
|
+
if (close < 0) return null;
|
|
2221
|
+
href = text.slice(i + 1, close).replace(/\\([\\<>])/g, "$1");
|
|
2222
|
+
i = close + 1;
|
|
2223
|
+
} else {
|
|
2224
|
+
let depth = 0;
|
|
2225
|
+
let buffer = "";
|
|
2226
|
+
while (i < text.length) {
|
|
2227
|
+
const ch = text[i];
|
|
2228
|
+
if (ch === "\\" && text[i + 1]) {
|
|
2229
|
+
buffer += text[i + 1];
|
|
2230
|
+
i += 2;
|
|
2231
|
+
continue;
|
|
2232
|
+
}
|
|
2233
|
+
if (ch === "(") depth += 1;
|
|
2234
|
+
if (ch === ")") {
|
|
2235
|
+
if (depth === 0) break;
|
|
2236
|
+
depth -= 1;
|
|
2237
|
+
}
|
|
2238
|
+
if (/\s/.test(ch) && depth === 0) break;
|
|
2239
|
+
buffer += ch;
|
|
2240
|
+
i += 1;
|
|
2241
|
+
}
|
|
2242
|
+
href = buffer;
|
|
2243
|
+
}
|
|
2244
|
+
while (text[i] === " " || text[i] === "\n") i += 1;
|
|
2245
|
+
let title = "";
|
|
2246
|
+
const quote = text[i];
|
|
2247
|
+
if (quote === '"' || quote === "'" || quote === "(") {
|
|
2248
|
+
const closing = quote === "(" ? ")" : quote;
|
|
2249
|
+
const close = text.indexOf(closing, i + 1);
|
|
2250
|
+
if (close < 0) return null;
|
|
2251
|
+
title = text.slice(i + 1, close);
|
|
2252
|
+
i = close + 1;
|
|
2253
|
+
while (text[i] === " " || text[i] === "\n") i += 1;
|
|
2254
|
+
}
|
|
2255
|
+
if (text[i] !== ")") return null;
|
|
2256
|
+
return { href: href.trim(), title, next: i + 1 };
|
|
2257
|
+
}
|
|
2258
|
+
function processEmphasis(nodes) {
|
|
2259
|
+
const out = [];
|
|
2260
|
+
const stack = [];
|
|
2261
|
+
for (const node of nodes) {
|
|
2262
|
+
if (node.type !== "delim") {
|
|
2263
|
+
out.push(node);
|
|
2264
|
+
continue;
|
|
2265
|
+
}
|
|
2266
|
+
const { char, canOpen, canClose } = node;
|
|
2267
|
+
const textNode = { type: "text", value: char.repeat(node.count), bare: false };
|
|
2268
|
+
out.push(textNode);
|
|
2269
|
+
if (char === "~" && node.count < 2) continue;
|
|
2270
|
+
const entry = { char, count: node.count, canOpen, canClose, node: textNode };
|
|
2271
|
+
if (!canClose) {
|
|
2272
|
+
if (canOpen) stack.push(entry);
|
|
2273
|
+
continue;
|
|
2274
|
+
}
|
|
2275
|
+
while (entry.count > 0) {
|
|
2276
|
+
const closerAt = out.indexOf(entry.node);
|
|
2277
|
+
if (closerAt < 0) break;
|
|
2278
|
+
let openAt = -1;
|
|
2279
|
+
for (let k = stack.length - 1; k >= 0; k -= 1) {
|
|
2280
|
+
const open2 = stack[k];
|
|
2281
|
+
if (open2 === entry || open2.char !== char || !open2.canOpen || open2.count <= 0) continue;
|
|
2282
|
+
if (char === "~" && open2.count < 2) continue;
|
|
2283
|
+
const at = out.indexOf(open2.node);
|
|
2284
|
+
if (at < 0 || at >= closerAt) continue;
|
|
2285
|
+
if (char !== "~" && (open2.canClose || entry.canOpen)) {
|
|
2286
|
+
const sum = open2.count + entry.count;
|
|
2287
|
+
if (sum % 3 === 0 && !(open2.count % 3 === 0 && entry.count % 3 === 0)) continue;
|
|
2288
|
+
}
|
|
2289
|
+
openAt = k;
|
|
2290
|
+
break;
|
|
2291
|
+
}
|
|
2292
|
+
if (openAt < 0) break;
|
|
2293
|
+
const open = stack[openAt];
|
|
2294
|
+
const use = char === "~" ? 2 : Math.min(open.count, entry.count) >= 3 ? 3 : Math.min(open.count, entry.count, 2);
|
|
2295
|
+
if (use <= 0) break;
|
|
2296
|
+
const inner = out.slice(out.indexOf(open.node) + 1, closerAt);
|
|
2297
|
+
open.count -= use;
|
|
2298
|
+
entry.count -= use;
|
|
2299
|
+
open.node.value = char.repeat(open.count);
|
|
2300
|
+
entry.node.value = char.repeat(entry.count);
|
|
2301
|
+
const wrapper = wrapEmphasis(char, use, inner);
|
|
2302
|
+
out.splice(closerAt, 1);
|
|
2303
|
+
const openIdx = out.indexOf(open.node);
|
|
2304
|
+
if (open.node.value) out.splice(openIdx + 1, closerAt - openIdx - 1, wrapper);
|
|
2305
|
+
else out.splice(openIdx, closerAt - openIdx, wrapper);
|
|
2306
|
+
for (let k = stack.length - 1; k >= 0; k -= 1) {
|
|
2307
|
+
if (stack[k] !== open && (!stack[k].count || out.indexOf(stack[k].node) < 0)) stack.splice(k, 1);
|
|
2308
|
+
}
|
|
2309
|
+
if (open.count <= 0) {
|
|
2310
|
+
const at = stack.indexOf(open);
|
|
2311
|
+
if (at >= 0) stack.splice(at, 1);
|
|
2312
|
+
}
|
|
2313
|
+
}
|
|
2314
|
+
if (entry.count > 0 && entry.canOpen && out.indexOf(entry.node) >= 0) stack.push(entry);
|
|
2315
|
+
}
|
|
2316
|
+
return out;
|
|
2317
|
+
}
|
|
2318
|
+
function wrapEmphasis(char, use, inner) {
|
|
2319
|
+
if (char === "~") return { type: "del", children: inner };
|
|
2320
|
+
if (use >= 3) return { type: "strong", children: [{ type: "em", children: inner }] };
|
|
2321
|
+
if (use === 2) return { type: "strong", children: inner };
|
|
2322
|
+
return { type: "em", children: inner };
|
|
2323
|
+
}
|
|
2324
|
+
function renderBlock(node, refs, opts) {
|
|
2325
|
+
switch (node.t) {
|
|
2326
|
+
case "p":
|
|
2327
|
+
return `<p>${inline(node.raw, refs, opts)}</p>`;
|
|
2328
|
+
case "h":
|
|
2329
|
+
return `<h${node.level}>${inline(node.raw, refs, opts)}</h${node.level}>`;
|
|
2330
|
+
case "hr":
|
|
2331
|
+
return "<hr>";
|
|
2332
|
+
case "code":
|
|
2333
|
+
return renderCode(node);
|
|
2334
|
+
case "html":
|
|
2335
|
+
return stripDangerousBlocks(scrubUrls(node.raw));
|
|
2336
|
+
case "quote":
|
|
2337
|
+
return `<blockquote>
|
|
2338
|
+
${node.children.map((child) => renderBlock(child, refs, opts)).join("\n")}
|
|
2339
|
+
</blockquote>`;
|
|
2340
|
+
case "ul":
|
|
2341
|
+
case "ol": {
|
|
2342
|
+
const start = node.t === "ol" && node.start !== 1 ? ` start="${node.start}"` : "";
|
|
2343
|
+
const items = node.items.map((item) => renderItem(item, node.loose, refs, opts)).join("\n");
|
|
2344
|
+
return `<${node.t}${start}>
|
|
2345
|
+
${items}
|
|
2346
|
+
</${node.t}>`;
|
|
2347
|
+
}
|
|
2348
|
+
case "table":
|
|
2349
|
+
return renderTable(node, refs, opts);
|
|
2350
|
+
default:
|
|
2351
|
+
return "";
|
|
2352
|
+
}
|
|
2353
|
+
}
|
|
2354
|
+
function renderCode(node) {
|
|
2355
|
+
const raw = firstWord(node.lang);
|
|
2356
|
+
const lang = raw ? normalizeLang(raw) : "plaintext";
|
|
2357
|
+
const attr = lang === "plaintext" ? "" : ` data-k-lang="${lang}"`;
|
|
2358
|
+
const cls = lang === "plaintext" ? "" : ` class="language-${lang}"`;
|
|
2359
|
+
return `<pre${attr}><code${cls}>${escapeMdText(node.text)}</code></pre>`;
|
|
2360
|
+
}
|
|
2361
|
+
function renderItem(item, loose, refs, opts) {
|
|
2362
|
+
let html;
|
|
2363
|
+
const children = item.children;
|
|
2364
|
+
if (!loose && children.length === 1 && children[0].t === "p") {
|
|
2365
|
+
html = inline(children[0].raw, refs, opts);
|
|
2366
|
+
} else {
|
|
2367
|
+
html = children.map((child) => renderBlock(child, refs, opts)).join("\n");
|
|
2368
|
+
if (!loose) html = html.replace(/^<p>([\s\S]*?)<\/p>/, "$1");
|
|
2369
|
+
}
|
|
2370
|
+
if (item.checked === null || item.checked === void 0) return `<li>${html}</li>`;
|
|
2371
|
+
return `<li>${item.checked ? "☑" : "☐"} ${html}</li>`;
|
|
2372
|
+
}
|
|
2373
|
+
function renderTable(node, refs, opts) {
|
|
2374
|
+
const cell = (tag, value, index) => {
|
|
2375
|
+
const align = node.align[index];
|
|
2376
|
+
const style = align && align !== "left" ? ` style="text-align:${align}"` : "";
|
|
2377
|
+
return `<${tag}${style}>${inline(value, refs, opts)}</${tag}>`;
|
|
2378
|
+
};
|
|
2379
|
+
const head = `<tr>${node.head.map((value, index) => cell("th", value, index)).join("")}</tr>`;
|
|
2380
|
+
const body = node.rows.map((row) => `<tr>${row.map((value, index) => cell("td", value, index)).join("")}</tr>`);
|
|
2381
|
+
if (!body.length) return `<table><thead>${head}</thead></table>`;
|
|
2382
|
+
return `<table><thead>${head}</thead><tbody>${body.join("")}</tbody></table>`;
|
|
2383
|
+
}
|
|
2384
|
+
function serialize(nodes, refs, opts) {
|
|
2385
|
+
return nodes.map((node) => serializeNode(node, refs, opts)).join("");
|
|
2386
|
+
}
|
|
2387
|
+
function serializeNode(node, refs, opts) {
|
|
2388
|
+
switch (node.type) {
|
|
2389
|
+
case "text":
|
|
2390
|
+
return escapeMdText(node.value).replace(/\u0001/g, "<br>");
|
|
2391
|
+
case "code":
|
|
2392
|
+
return `<code>${escapeMdText(node.value)}</code>`;
|
|
2393
|
+
case "br":
|
|
2394
|
+
return "<br>";
|
|
2395
|
+
case "html":
|
|
2396
|
+
return node.value;
|
|
2397
|
+
case "em":
|
|
2398
|
+
return `<em>${serialize(node.children, refs, opts)}</em>`;
|
|
2399
|
+
case "strong":
|
|
2400
|
+
return `<strong>${serialize(node.children, refs, opts)}</strong>`;
|
|
2401
|
+
case "del":
|
|
2402
|
+
return `<del>${serialize(node.children, refs, opts)}</del>`;
|
|
2403
|
+
case "image": {
|
|
2404
|
+
const title = node.title ? ` title="${escapeAttr(node.title)}"` : "";
|
|
2405
|
+
return `<img src="${escapeAttr(node.src)}" alt="${escapeAttr(node.alt)}"${title}>`;
|
|
2406
|
+
}
|
|
2407
|
+
case "link": {
|
|
2408
|
+
const href = isSafeUrl(node.href) ? node.href : "#";
|
|
2409
|
+
const title = node.title ? ` title="${escapeAttr(node.title)}"` : "";
|
|
2410
|
+
const target = opts.linkTarget ? ' target="_blank" rel="noopener noreferrer"' : "";
|
|
2411
|
+
return `<a href="${escapeAttr(href)}"${title}${target}>${serialize(node.children, refs, opts)}</a>`;
|
|
2412
|
+
}
|
|
2413
|
+
default:
|
|
2414
|
+
return "";
|
|
2415
|
+
}
|
|
2416
|
+
}
|
|
2417
|
+
const DANGEROUS_BLOCK_RE = /<(script|style|iframe|object|embed|form|link|meta|base)\b[^>]*>[\s\S]*?<\/\1\s*>/gi;
|
|
2418
|
+
const DANGEROUS_TAG_RE = /<\/?(?:script|style|iframe|object|embed|form|link|meta|base)\b[^>]*>/gi;
|
|
2419
|
+
function stripDangerousBlocks(html) {
|
|
2420
|
+
return String(html).replace(DANGEROUS_BLOCK_RE, "").replace(DANGEROUS_TAG_RE, "");
|
|
2421
|
+
}
|
|
2422
|
+
const URL_ATTR_RE = /\s(href|src)\s*=\s*("([^"]*)"|'([^']*)'|([^\s>]+))/gi;
|
|
2423
|
+
function scrubUrls(html) {
|
|
2424
|
+
return String(html).replace(URL_ATTR_RE, (all, _name, _raw, dq, sq, bare) => {
|
|
2425
|
+
const value = dq ?? sq ?? bare ?? "";
|
|
2426
|
+
return isSafeUrl(value) ? all : "";
|
|
2427
|
+
});
|
|
2428
|
+
}
|
|
2429
|
+
const ENTITY_RE = /&(?![a-zA-Z][a-zA-Z0-9]{1,31};|#\d{1,7};|#[xX][0-9a-fA-F]{1,6};)/g;
|
|
2430
|
+
function escapeMdText(value) {
|
|
2431
|
+
return String(value === null || value === void 0 ? "" : value).replace(ENTITY_RE, "&").replace(/</g, "<").replace(/>/g, ">");
|
|
2432
|
+
}
|
|
2433
|
+
function escapeAttr(value) {
|
|
2434
|
+
return String(value || "").replace(/&/g, "&").replace(/"/g, """).replace(/</g, "<").replace(/>/g, ">");
|
|
2435
|
+
}
|
|
2436
|
+
const THEME_COLORS = [
|
|
2437
|
+
["#07c160", "微信绿"],
|
|
2438
|
+
["#2f6fed", "科技蓝"],
|
|
2439
|
+
["#7c3aed", "极光紫"],
|
|
2440
|
+
["#d53880", "品红"],
|
|
2441
|
+
["#e53e3e", "中国红"],
|
|
2442
|
+
["#ed8936", "暮橙"],
|
|
2443
|
+
["#f6c344", "明黄"],
|
|
2444
|
+
["#0f766e", "松石绿"]
|
|
2445
|
+
];
|
|
2446
|
+
const STANDARD_COLORS = [
|
|
2447
|
+
["#1f2329", "墨黑"],
|
|
2448
|
+
["#6b7280", "深灰"],
|
|
2449
|
+
["#b8bec7", "浅灰"],
|
|
2450
|
+
["#f2f3f5", "云灰"],
|
|
2451
|
+
["#ffffff", "纯白"],
|
|
2452
|
+
["#c00000", "深红"],
|
|
2453
|
+
["#ff0000", "正红"],
|
|
2454
|
+
["#ffc000", "琥珀"],
|
|
2455
|
+
["#ffff00", "柠黄"],
|
|
2456
|
+
["#00b050", "草绿"],
|
|
2457
|
+
["#00b0f0", "天蓝"],
|
|
2458
|
+
["#0070c0", "海蓝"],
|
|
2459
|
+
["#7030a0", "葡萄紫"],
|
|
2460
|
+
["#ff69b4", "桃花粉"]
|
|
2461
|
+
];
|
|
2462
|
+
const BG_COLORS = [
|
|
2463
|
+
["#fef08a", "柠檬底"],
|
|
2464
|
+
["#dcfce7", "薄荷底"],
|
|
2465
|
+
["#e0f2fe", "天空底"],
|
|
2466
|
+
["#ede9fe", "薰衣底"],
|
|
2467
|
+
["#ffe4e6", "樱花底"],
|
|
2468
|
+
["#fff4e6", "奶茶底"],
|
|
2469
|
+
["#f2f3f5", "纸张灰"],
|
|
2470
|
+
["#1f2329", "夜墨"]
|
|
2471
|
+
];
|
|
2472
|
+
const HEX = /^#([0-9a-f]{3}|[0-9a-f]{6})$/i;
|
|
2473
|
+
class Popover {
|
|
2474
|
+
constructor(root) {
|
|
2475
|
+
this.root = root;
|
|
2476
|
+
this.el = h("div.ke-pop", { hidden: true });
|
|
2477
|
+
this.anchor = null;
|
|
2478
|
+
this.onClose = null;
|
|
2479
|
+
root.appendChild(this.el);
|
|
2480
|
+
this.el.addEventListener("mousedown", (event) => {
|
|
2481
|
+
if (!/^(input|textarea|select)$/i.test(event.target.tagName)) event.preventDefault();
|
|
2482
|
+
});
|
|
2483
|
+
this.docHandler = (event) => {
|
|
2484
|
+
var _a, _b;
|
|
2485
|
+
if (this.el.hidden) return;
|
|
2486
|
+
if (this.el.contains(event.target)) return;
|
|
2487
|
+
if ((_b = (_a = event.target).closest) == null ? void 0 : _b.call(_a, ".ke-btn[data-k-pop]")) return;
|
|
2488
|
+
this.close();
|
|
2489
|
+
};
|
|
2490
|
+
document.addEventListener("mousedown", this.docHandler, true);
|
|
2491
|
+
this.keyHandler = (event) => {
|
|
2492
|
+
if (event.key === "Escape") this.close();
|
|
2493
|
+
};
|
|
2494
|
+
document.addEventListener("keydown", this.keyHandler);
|
|
2495
|
+
this.resizeHandler = () => {
|
|
2496
|
+
if (!this.el.hidden) this.place();
|
|
2497
|
+
};
|
|
2498
|
+
window.addEventListener("resize", this.resizeHandler);
|
|
2499
|
+
}
|
|
2500
|
+
open(anchor, build, { align = "start", onClose } = {}) {
|
|
2501
|
+
var _a;
|
|
2502
|
+
this.el.textContent = "";
|
|
2503
|
+
const content = build((node) => this.el.appendChild(node));
|
|
2504
|
+
if (content) this.el.appendChild(content);
|
|
2505
|
+
this.el.hidden = false;
|
|
2506
|
+
this.anchor = anchor;
|
|
2507
|
+
this.align = align;
|
|
2508
|
+
this.onClose = onClose;
|
|
2509
|
+
this.place();
|
|
2510
|
+
this.el.classList.remove("ke-pop-in");
|
|
2511
|
+
void this.el.offsetWidth;
|
|
2512
|
+
this.el.classList.add("ke-pop-in");
|
|
2513
|
+
const first2 = [...this.el.querySelectorAll("[data-k-autofocus]")].find((node) => node.offsetParent !== null);
|
|
2514
|
+
(_a = first2 == null ? void 0 : first2.focus) == null ? void 0 : _a.call(first2);
|
|
2515
|
+
}
|
|
2516
|
+
/** 定位 + 高度夹紧:面板可以内部滚动,但底部按钮必须留在可视区内 */
|
|
2517
|
+
place() {
|
|
2518
|
+
const anchor = this.anchor;
|
|
2519
|
+
if (!anchor) return;
|
|
2520
|
+
this.el.style.removeProperty("--ke-pop-max");
|
|
2521
|
+
const align = this.align;
|
|
2522
|
+
const rootBox = this.root.getBoundingClientRect();
|
|
2523
|
+
const box = anchor.getBoundingClientRect();
|
|
2524
|
+
const visTop = Math.max(0, -rootBox.top);
|
|
2525
|
+
const visBottom = Math.min(rootBox.height, window.innerHeight - rootBox.top);
|
|
2526
|
+
const popBox = this.el.getBoundingClientRect();
|
|
2527
|
+
let left = box.left - rootBox.left;
|
|
2528
|
+
if (align === "center") left = box.left - rootBox.left + box.width / 2 - popBox.width / 2;
|
|
2529
|
+
if (align === "end") left = box.right - rootBox.left - popBox.width;
|
|
2530
|
+
left = Math.max(8, Math.min(left, rootBox.width - popBox.width - 8));
|
|
2531
|
+
const below = box.top - rootBox.top + box.height + 8;
|
|
2532
|
+
const aboveTop = box.top - rootBox.top - 8;
|
|
2533
|
+
const band = Math.max(0, visBottom - visTop - 16);
|
|
2534
|
+
const roomBelow = visBottom - 8 - below;
|
|
2535
|
+
const roomAbove = aboveTop - visTop;
|
|
2536
|
+
const room = roomBelow >= 320 ? Math.min(roomBelow, band) : band;
|
|
2537
|
+
const height = Math.max(180, Math.min(popBox.height, room));
|
|
2538
|
+
if (height < popBox.height) this.el.style.setProperty("--ke-pop-max", `${Math.round(height)}px`);
|
|
2539
|
+
let top;
|
|
2540
|
+
if (height <= roomBelow) top = below;
|
|
2541
|
+
else if (roomAbove > roomBelow && height <= roomAbove) top = aboveTop - height;
|
|
2542
|
+
else top = visBottom - 8 - height;
|
|
2543
|
+
top = Math.max(visTop, Math.min(top, Math.max(visTop, visBottom - 8 - height)));
|
|
2544
|
+
this.el.style.left = `${left}px`;
|
|
2545
|
+
this.el.style.top = `${top}px`;
|
|
2546
|
+
}
|
|
2547
|
+
close() {
|
|
2548
|
+
if (this.el.hidden) return;
|
|
2549
|
+
this.el.hidden = true;
|
|
2550
|
+
this.el.classList.remove("ke-pop-in");
|
|
2551
|
+
this.el.textContent = "";
|
|
2552
|
+
this.anchor = null;
|
|
2553
|
+
const cb = this.onClose;
|
|
2554
|
+
this.onClose = null;
|
|
2555
|
+
cb == null ? void 0 : cb();
|
|
2556
|
+
}
|
|
2557
|
+
get isOpen() {
|
|
2558
|
+
return !this.el.hidden;
|
|
2559
|
+
}
|
|
2560
|
+
destroy() {
|
|
2561
|
+
document.removeEventListener("mousedown", this.docHandler, true);
|
|
2562
|
+
document.removeEventListener("keydown", this.keyHandler);
|
|
2563
|
+
window.removeEventListener("resize", this.resizeHandler);
|
|
2564
|
+
this.el.remove();
|
|
2565
|
+
}
|
|
2566
|
+
}
|
|
2567
|
+
function panel(title, right) {
|
|
2568
|
+
const head = h("div.ke-panel-head", {}, [h("span.ke-panel-title", { text: title })]);
|
|
2569
|
+
if (right) head.appendChild(right);
|
|
2570
|
+
const wrap = h("div.ke-panel", {}, [head]);
|
|
2571
|
+
return wrap;
|
|
2572
|
+
}
|
|
2573
|
+
function section(label) {
|
|
2574
|
+
return h("div.ke-panel-sect", { text: label });
|
|
2575
|
+
}
|
|
2576
|
+
function divider() {
|
|
2577
|
+
return h("div.ke-panel-divider");
|
|
2578
|
+
}
|
|
2579
|
+
function codePanel({ languages, value, editing, onPick }) {
|
|
2580
|
+
const wrap = panel(editing ? "代码块语言" : "插入代码块");
|
|
2581
|
+
wrap.classList.add("ke-panel-wide", "ke-code-panel");
|
|
2582
|
+
const note = h("span.ke-panel-note");
|
|
2583
|
+
wrap.querySelector(".ke-panel-head").appendChild(note);
|
|
2584
|
+
const search = h("input.ke-input.ke-sel-search", {
|
|
2585
|
+
type: "search",
|
|
2586
|
+
placeholder: "搜索语言,如 js / python",
|
|
2587
|
+
"data-k-autofocus": ""
|
|
2588
|
+
});
|
|
2589
|
+
wrap.appendChild(search);
|
|
2590
|
+
const body = h("div.ke-code-list");
|
|
2591
|
+
wrap.appendChild(body);
|
|
2592
|
+
wrap.appendChild(h("div.ke-panel-hint", {
|
|
2593
|
+
text: editing ? "切换后会立即重新高亮当前代码块" : "插入后点「代码块」按钮可随时切换语言"
|
|
2594
|
+
}));
|
|
2595
|
+
let visible = languages;
|
|
2596
|
+
function render() {
|
|
2597
|
+
const keyword = search.value.trim().toLowerCase();
|
|
2598
|
+
visible = keyword ? languages.filter((item) => `${item.label} ${item.hint} ${item.value}`.toLowerCase().includes(keyword)) : languages;
|
|
2599
|
+
note.textContent = keyword ? `${visible.length} / ${languages.length} 种` : `${languages.length} 种语言`;
|
|
2600
|
+
body.textContent = "";
|
|
2601
|
+
if (!visible.length) {
|
|
2602
|
+
body.appendChild(h("div.ke-sel-tip", {}, [h("span.ke-sel-tip-text", { text: `没有匹配「${search.value.trim()}」的语言` })]));
|
|
2603
|
+
return;
|
|
2604
|
+
}
|
|
2605
|
+
visible.forEach((item) => {
|
|
2606
|
+
const row = h("button.ke-sel-row", {
|
|
2607
|
+
type: "button",
|
|
2608
|
+
dataset: { kLang: item.value },
|
|
2609
|
+
onclick: () => onPick(item.value)
|
|
2610
|
+
}, [
|
|
2611
|
+
h("span.ke-sel-main", {}, [
|
|
2612
|
+
h("span.ke-sel-label", { text: item.label }),
|
|
2613
|
+
h("span.ke-sel-desc", { text: item.hint })
|
|
2614
|
+
])
|
|
2615
|
+
]);
|
|
2616
|
+
if (item.value === value) {
|
|
2617
|
+
row.classList.add("ke-is-active");
|
|
2618
|
+
row.appendChild(h("span.ke-sel-check", { html: icon("check") }));
|
|
2619
|
+
}
|
|
2620
|
+
body.appendChild(row);
|
|
2621
|
+
});
|
|
2622
|
+
}
|
|
2623
|
+
search.addEventListener("input", render);
|
|
2624
|
+
search.addEventListener("keydown", (event) => {
|
|
2625
|
+
if (event.key !== "Enter") return;
|
|
2626
|
+
event.preventDefault();
|
|
2627
|
+
if (visible.length) onPick(visible[0].value);
|
|
2628
|
+
});
|
|
2629
|
+
render();
|
|
2630
|
+
return wrap;
|
|
2631
|
+
}
|
|
2632
|
+
function markdownPanel({ insertMode = "replace", accept = "", maxText = "", highlight = true, onConvert, onImport }) {
|
|
2633
|
+
const wrap = panel("导入 Markdown");
|
|
2634
|
+
wrap.classList.add("ke-panel-wide", "ke-md-panel");
|
|
2635
|
+
const note = h("span.ke-panel-note", { text: "尚未选择文件" });
|
|
2636
|
+
wrap.querySelector(".ke-panel-head").appendChild(note);
|
|
2637
|
+
const state = { text: "", name: "", mode: insertMode, picked: false };
|
|
2638
|
+
const local = h("div.ke-tab-body");
|
|
2639
|
+
const pasteBody = h("div.ke-tab-body", { hidden: true });
|
|
2640
|
+
const tabs = h("div.ke-tabs", {}, [
|
|
2641
|
+
h("button.ke-tab", { type: "button", text: "选择文件" }),
|
|
2642
|
+
h("button.ke-tab", { type: "button", text: "粘贴文本" })
|
|
2643
|
+
]);
|
|
2644
|
+
const show = (index) => {
|
|
2645
|
+
[...tabs.children].forEach((tab, i) => tab.classList.toggle("ke-is-active", i === index));
|
|
2646
|
+
local.hidden = index !== 0;
|
|
2647
|
+
pasteBody.hidden = index !== 1;
|
|
2648
|
+
if (index === 1) textarea.focus();
|
|
2649
|
+
};
|
|
2650
|
+
tabs.children[0].addEventListener("click", () => show(0));
|
|
2651
|
+
tabs.children[1].addEventListener("click", () => show(1));
|
|
2652
|
+
const input = h("input", { type: "file", accept, hidden: true, style: { display: "none" } });
|
|
2653
|
+
const fileRow = h("div.ke-md-file", { hidden: true });
|
|
2654
|
+
const drop = h("div.ke-drop", {}, [
|
|
2655
|
+
h("span.ke-drop-ico", { html: icon("upload") }),
|
|
2656
|
+
h("div.ke-drop-title", { text: "点击选择 .md 文件,或拖拽到此处" }),
|
|
2657
|
+
h("div.ke-drop-sub", { text: [maxText, "支持 .md / .markdown / .txt,自动识别 UTF-8 与 GBK"].filter(Boolean).join(" · ") })
|
|
2658
|
+
]);
|
|
2659
|
+
drop.addEventListener("click", () => input.click());
|
|
2660
|
+
drop.addEventListener("dragover", (event) => {
|
|
2661
|
+
event.preventDefault();
|
|
2662
|
+
drop.classList.add("ke-is-over");
|
|
2663
|
+
});
|
|
2664
|
+
drop.addEventListener("dragleave", () => drop.classList.remove("ke-is-over"));
|
|
2665
|
+
drop.addEventListener("drop", (event) => {
|
|
2666
|
+
var _a, _b;
|
|
2667
|
+
event.preventDefault();
|
|
2668
|
+
drop.classList.remove("ke-is-over");
|
|
2669
|
+
const file = (_b = (_a = event.dataTransfer) == null ? void 0 : _a.files) == null ? void 0 : _b[0];
|
|
2670
|
+
if (file) loadFile(file);
|
|
2671
|
+
});
|
|
2672
|
+
input.addEventListener("change", () => {
|
|
2673
|
+
var _a;
|
|
2674
|
+
const file = (_a = input.files) == null ? void 0 : _a[0];
|
|
2675
|
+
input.value = "";
|
|
2676
|
+
if (file) loadFile(file);
|
|
2677
|
+
});
|
|
2678
|
+
async function loadFile(file) {
|
|
2679
|
+
try {
|
|
2680
|
+
const text = await readMarkdownFile(file);
|
|
2681
|
+
state.text = text;
|
|
2682
|
+
state.name = file.name || "";
|
|
2683
|
+
state.picked = true;
|
|
2684
|
+
fileRow.hidden = false;
|
|
2685
|
+
fileRow.textContent = "";
|
|
2686
|
+
fileRow.append(
|
|
2687
|
+
h("b", { text: file.name || "未命名" }),
|
|
2688
|
+
h("span", { text: `${formatSize(file.size)} · ${text.length} 字符` })
|
|
2689
|
+
);
|
|
2690
|
+
schedule();
|
|
2691
|
+
} catch (error) {
|
|
2692
|
+
state.text = "";
|
|
2693
|
+
fileRow.hidden = false;
|
|
2694
|
+
fileRow.textContent = "";
|
|
2695
|
+
fileRow.appendChild(h("span.ke-md-error", { text: `读取失败:${error.message}` }));
|
|
2696
|
+
render();
|
|
2697
|
+
}
|
|
700
2698
|
}
|
|
701
|
-
|
|
702
|
-
|
|
2699
|
+
local.append(drop, input, fileRow);
|
|
2700
|
+
const textarea = h("textarea.ke-md-text", {
|
|
2701
|
+
placeholder: "# 标题\n\n正文段落,支持 **加粗**、列表、表格、```js 代码块 ...",
|
|
2702
|
+
spellcheck: "false"
|
|
2703
|
+
});
|
|
2704
|
+
pasteBody.appendChild(textarea);
|
|
2705
|
+
const MODES = [
|
|
2706
|
+
["replace", "替换全文"],
|
|
2707
|
+
["append", "追加文末"],
|
|
2708
|
+
["cursor", "插入光标"]
|
|
2709
|
+
];
|
|
2710
|
+
const modeRow = h("div.ke-md-modes");
|
|
2711
|
+
const modeText = { replace: "清空正文后导入(可撤销)", append: "保留正文,追加到末尾", cursor: "插入到当前光标位置" };
|
|
2712
|
+
MODES.forEach(([value, label]) => {
|
|
2713
|
+
const button = h("button.ke-md-mode", { type: "button", title: modeText[value], text: label });
|
|
2714
|
+
button.classList.toggle("ke-is-active", value === state.mode);
|
|
2715
|
+
button.addEventListener("click", () => {
|
|
2716
|
+
state.mode = value;
|
|
2717
|
+
[...modeRow.children].forEach((node) => node.classList.toggle("ke-is-active", node === button));
|
|
2718
|
+
});
|
|
2719
|
+
modeRow.appendChild(button);
|
|
2720
|
+
});
|
|
2721
|
+
const preview = h("div.ke-md-preview.ke-content");
|
|
2722
|
+
const stats = h("div.ke-md-stats");
|
|
2723
|
+
const importer = h("button.ke-btn-primary", { type: "button", text: "导入到正文", disabled: true });
|
|
2724
|
+
let timer = null;
|
|
2725
|
+
function schedule() {
|
|
2726
|
+
clearTimeout(timer);
|
|
2727
|
+
timer = setTimeout(render, 180);
|
|
703
2728
|
}
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
2729
|
+
function convert() {
|
|
2730
|
+
const text = state.text;
|
|
2731
|
+
if (!text.trim()) return { html: "", summary: null };
|
|
2732
|
+
try {
|
|
2733
|
+
return onConvert(text) || { html: "", summary: null };
|
|
2734
|
+
} catch (error) {
|
|
2735
|
+
return { html: "", summary: null, error };
|
|
2736
|
+
}
|
|
708
2737
|
}
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
2738
|
+
function render() {
|
|
2739
|
+
const result = convert();
|
|
2740
|
+
const empty = !state.text.trim();
|
|
2741
|
+
importer.disabled = empty || !result.html || !!result.error;
|
|
2742
|
+
note.textContent = empty ? "尚未选择文件" : `${state.text.length} 字符`;
|
|
2743
|
+
preview.textContent = "";
|
|
2744
|
+
stats.textContent = "";
|
|
2745
|
+
if (result.error) {
|
|
2746
|
+
preview.appendChild(h("div.ke-md-empty", { text: `转换失败:${result.error.message}` }));
|
|
2747
|
+
return;
|
|
2748
|
+
}
|
|
2749
|
+
if (empty) {
|
|
2750
|
+
preview.appendChild(h("div.ke-md-empty", { text: "选择文件或粘贴 Markdown 后,这里会显示转换预览" }));
|
|
2751
|
+
return;
|
|
2752
|
+
}
|
|
2753
|
+
preview.innerHTML = result.html;
|
|
2754
|
+
if (highlight) highlightCodeBlocks(preview, { highlight: true });
|
|
2755
|
+
const summary = result.summary || {};
|
|
2756
|
+
const items = [
|
|
2757
|
+
["标题", summary.headings],
|
|
2758
|
+
["段落", summary.paragraphs],
|
|
2759
|
+
["列表", summary.lists],
|
|
2760
|
+
["代码块", summary.codeBlocks],
|
|
2761
|
+
["引用", summary.quotes],
|
|
2762
|
+
["表格", summary.tables],
|
|
2763
|
+
["图片", summary.images],
|
|
2764
|
+
["链接", summary.links]
|
|
2765
|
+
].filter(([, count]) => count);
|
|
2766
|
+
items.forEach(([label, count]) => {
|
|
2767
|
+
stats.appendChild(h("span.ke-md-stat", {}, [h("b", { text: String(count) }), ` ${label}`]));
|
|
2768
|
+
});
|
|
2769
|
+
if (!items.length) stats.appendChild(h("span.ke-md-stat", { text: "未识别到块级结构,将按纯文本导入" }));
|
|
2770
|
+
}
|
|
2771
|
+
textarea.addEventListener("input", () => {
|
|
2772
|
+
state.text = textarea.value;
|
|
2773
|
+
state.name = "";
|
|
2774
|
+
schedule();
|
|
2775
|
+
});
|
|
2776
|
+
importer.addEventListener("click", async () => {
|
|
2777
|
+
if (importer.disabled) return;
|
|
2778
|
+
importer.disabled = true;
|
|
2779
|
+
importer.textContent = "导入中…";
|
|
2780
|
+
try {
|
|
2781
|
+
await onImport({ text: state.text, name: state.name, mode: state.mode });
|
|
2782
|
+
} finally {
|
|
2783
|
+
importer.textContent = "导入到正文";
|
|
2784
|
+
importer.disabled = !state.text.trim();
|
|
2785
|
+
}
|
|
2786
|
+
});
|
|
2787
|
+
wrap.append(
|
|
2788
|
+
tabs,
|
|
2789
|
+
h("div.ke-md-body", {}, [
|
|
2790
|
+
local,
|
|
2791
|
+
pasteBody,
|
|
2792
|
+
h("div.ke-panel-sect", { text: "导入位置" }),
|
|
2793
|
+
modeRow,
|
|
2794
|
+
h("div.ke-panel-sect", { text: "转换预览" }),
|
|
2795
|
+
preview,
|
|
2796
|
+
stats
|
|
2797
|
+
]),
|
|
2798
|
+
h("div.ke-panel-foot", {}, [importer, h("span.ke-panel-hint", { text: "转换后为可直接编辑的 HTML" })])
|
|
2799
|
+
);
|
|
2800
|
+
show(0);
|
|
2801
|
+
render();
|
|
714
2802
|
return wrap;
|
|
715
2803
|
}
|
|
716
|
-
function section(label) {
|
|
717
|
-
return h("div.ke-panel-sect", { text: label });
|
|
718
|
-
}
|
|
719
|
-
function divider() {
|
|
720
|
-
return h("div.ke-panel-divider");
|
|
721
|
-
}
|
|
722
2804
|
function colorPanel({ title, kind, colors, value, recents = [], onPick, onClear }) {
|
|
723
2805
|
const isBg = kind === "bg";
|
|
724
2806
|
const reset = h("button.ke-panel-reset", {
|
|
@@ -1182,6 +3264,10 @@ function formatHtml(html, { indent = " " } = {}) {
|
|
|
1182
3264
|
return;
|
|
1183
3265
|
}
|
|
1184
3266
|
const hasBlockChild = [...child.querySelectorAll("*")].some((node) => BLOCK_TAGS.has(node.tagName.toLowerCase()));
|
|
3267
|
+
if (tag === "pre") {
|
|
3268
|
+
lines.push({ depth, text: indent.repeat(depth) + child.outerHTML.trim(), inlineRun: false });
|
|
3269
|
+
return;
|
|
3270
|
+
}
|
|
1185
3271
|
const keepOneLine = tag === "tr" || tag === "figure" || tag === "video";
|
|
1186
3272
|
if (!hasBlockChild || keepOneLine) {
|
|
1187
3273
|
lines.push({ depth, text: indent.repeat(depth) + collapse(child.outerHTML), inlineRun: false });
|
|
@@ -1193,7 +3279,7 @@ function formatHtml(html, { indent = " " } = {}) {
|
|
|
1193
3279
|
});
|
|
1194
3280
|
};
|
|
1195
3281
|
walk2(root, 0);
|
|
1196
|
-
return lines.map((line) => line.text).join("\n")
|
|
3282
|
+
return lines.map((line) => line.text).join("\n");
|
|
1197
3283
|
}
|
|
1198
3284
|
function collapse(markup) {
|
|
1199
3285
|
return markup.replace(/\n\s+/g, " ").replace(/\s{2,}/g, " ").trim();
|
|
@@ -1565,268 +3651,64 @@ class MediaBubble {
|
|
|
1565
3651
|
this.replaceInput.accept = kind === "image" ? this.editor.options.imageAccept : this.editor.options.videoAccept;
|
|
1566
3652
|
this.replaceInput.click();
|
|
1567
3653
|
}
|
|
1568
|
-
setVideoWidth(width) {
|
|
1569
|
-
if (!this.node) return;
|
|
1570
|
-
this.node.style.width = width;
|
|
1571
|
-
this.editor.commitHistory();
|
|
1572
|
-
this.position();
|
|
1573
|
-
}
|
|
1574
|
-
remove() {
|
|
1575
|
-
if (!this.node) return;
|
|
1576
|
-
const task = this.editor.media.taskFromNode(this.node);
|
|
1577
|
-
if (task) this.editor.media.remove(task);
|
|
1578
|
-
else {
|
|
1579
|
-
const next = this.node.nextElementSibling;
|
|
1580
|
-
this.node.remove();
|
|
1581
|
-
if (next) this.editor.focus();
|
|
1582
|
-
this.editor.commitHistory();
|
|
1583
|
-
}
|
|
1584
|
-
this.hide();
|
|
1585
|
-
this.editor.refreshStatus();
|
|
1586
|
-
}
|
|
1587
|
-
onClick() {
|
|
1588
|
-
}
|
|
1589
|
-
destroy() {
|
|
1590
|
-
this.el.remove();
|
|
1591
|
-
this.replaceInput.remove();
|
|
1592
|
-
this.resizeEl.remove();
|
|
1593
|
-
this.resizeTip.remove();
|
|
1594
|
-
}
|
|
1595
|
-
}
|
|
1596
|
-
function btn(iconName, title, onclick, active = false) {
|
|
1597
|
-
const node = h("button", { type: "button", title, html: icon(iconName) });
|
|
1598
|
-
if (active) node.classList.add("ke-is-active");
|
|
1599
|
-
node.addEventListener("click", onclick);
|
|
1600
|
-
return node;
|
|
1601
|
-
}
|
|
1602
|
-
function textBtn(label, title, onclick) {
|
|
1603
|
-
const node = h("button", { type: "button", title, text: label });
|
|
1604
|
-
node.addEventListener("click", onclick);
|
|
1605
|
-
return node;
|
|
1606
|
-
}
|
|
1607
|
-
const sep = () => h("span.ke-sep");
|
|
1608
|
-
function toggleRadius(img, node) {
|
|
1609
|
-
if (!img) return;
|
|
1610
|
-
const has = parseFloat(getComputedStyle(img).borderRadius) > 0;
|
|
1611
|
-
img.style.borderRadius = has ? "0" : "10px";
|
|
1612
|
-
node.dispatchEvent(new Event("change", { bubbles: true }));
|
|
1613
|
-
}
|
|
1614
|
-
function previewImage(img) {
|
|
1615
|
-
if (img) lightbox(img.src);
|
|
1616
|
-
}
|
|
1617
|
-
function clamp(value, min, max) {
|
|
1618
|
-
return Math.min(max, Math.max(min, value));
|
|
1619
|
-
}
|
|
1620
|
-
function currentWidthPercent(img, figureWidth) {
|
|
1621
|
-
var _a, _b;
|
|
1622
|
-
if (!figureWidth) return 100;
|
|
1623
|
-
const match = (_b = (_a = img == null ? void 0 : img.style) == null ? void 0 : _a.width) == null ? void 0 : _b.match(/^([\d.]+)%$/);
|
|
1624
|
-
if (match) return parseFloat(match[1]);
|
|
1625
|
-
return img.getBoundingClientRect().width / figureWidth * 100;
|
|
1626
|
-
}
|
|
1627
|
-
const ALLOWED_TAGS = /* @__PURE__ */ new Set([
|
|
1628
|
-
"a",
|
|
1629
|
-
"abbr",
|
|
1630
|
-
"b",
|
|
1631
|
-
"blockquote",
|
|
1632
|
-
"br",
|
|
1633
|
-
"code",
|
|
1634
|
-
"col",
|
|
1635
|
-
"colgroup",
|
|
1636
|
-
"dd",
|
|
1637
|
-
"del",
|
|
1638
|
-
"div",
|
|
1639
|
-
"dl",
|
|
1640
|
-
"dt",
|
|
1641
|
-
"em",
|
|
1642
|
-
"figcaption",
|
|
1643
|
-
"figure",
|
|
1644
|
-
"font",
|
|
1645
|
-
"h1",
|
|
1646
|
-
"h2",
|
|
1647
|
-
"h3",
|
|
1648
|
-
"h4",
|
|
1649
|
-
"h5",
|
|
1650
|
-
"h6",
|
|
1651
|
-
"hr",
|
|
1652
|
-
"i",
|
|
1653
|
-
"img",
|
|
1654
|
-
"ins",
|
|
1655
|
-
"kbd",
|
|
1656
|
-
"li",
|
|
1657
|
-
"mark",
|
|
1658
|
-
"ol",
|
|
1659
|
-
"p",
|
|
1660
|
-
"pre",
|
|
1661
|
-
"s",
|
|
1662
|
-
"samp",
|
|
1663
|
-
"section",
|
|
1664
|
-
"small",
|
|
1665
|
-
"span",
|
|
1666
|
-
"strong",
|
|
1667
|
-
"sub",
|
|
1668
|
-
"sup",
|
|
1669
|
-
"table",
|
|
1670
|
-
"tbody",
|
|
1671
|
-
"td",
|
|
1672
|
-
"tfoot",
|
|
1673
|
-
"th",
|
|
1674
|
-
"thead",
|
|
1675
|
-
"tr",
|
|
1676
|
-
"u",
|
|
1677
|
-
"ul",
|
|
1678
|
-
"video",
|
|
1679
|
-
"source"
|
|
1680
|
-
]);
|
|
1681
|
-
const GLOBAL_ATTRS = /* @__PURE__ */ new Set(["style", "class"]);
|
|
1682
|
-
const TAG_ATTRS = {
|
|
1683
|
-
A: ["href", "title", "target", "rel"],
|
|
1684
|
-
IMG: ["src", "alt", "title", "width", "height"],
|
|
1685
|
-
VIDEO: ["src", "poster", "controls", "loop", "muted", "playsinline", "preload", "width", "height"],
|
|
1686
|
-
SOURCE: ["src", "type"],
|
|
1687
|
-
FONT: ["size", "color"],
|
|
1688
|
-
TD: ["colspan", "rowspan"],
|
|
1689
|
-
TH: ["colspan", "rowspan"],
|
|
1690
|
-
OL: ["start"],
|
|
1691
|
-
LI: ["value"]
|
|
1692
|
-
};
|
|
1693
|
-
const DATA_PREFIX = ["data-k-", "data-keditor-"];
|
|
1694
|
-
const SAFE_URL_RE = /^(?:https?:|mailto:|tel:|blob:|\/|#|\.{1,2}\/|[^:]*$)/i;
|
|
1695
|
-
const SAFE_DATA_RE = /^data:image\/(?:png|jpe?g|gif|webp|svg\+xml);/i;
|
|
1696
|
-
function isSafeUrl(url) {
|
|
1697
|
-
if (!url) return false;
|
|
1698
|
-
const value = String(url).trim().replace(/\s+/g, "");
|
|
1699
|
-
if (/^(javascript|vbscript|file|about):/i.test(value)) return false;
|
|
1700
|
-
if (value.startsWith("data:")) return SAFE_DATA_RE.test(value);
|
|
1701
|
-
return SAFE_URL_RE.test(value);
|
|
1702
|
-
}
|
|
1703
|
-
function sanitizeStyle(value) {
|
|
1704
|
-
const out = [];
|
|
1705
|
-
for (const decl of String(value).split(";")) {
|
|
1706
|
-
const idx = decl.indexOf(":");
|
|
1707
|
-
if (idx < 0) continue;
|
|
1708
|
-
const prop = decl.slice(0, idx).trim().toLowerCase();
|
|
1709
|
-
const val = decl.slice(idx + 1).trim();
|
|
1710
|
-
if (!prop || !val) continue;
|
|
1711
|
-
if (!/^[a-z-]+$/.test(prop)) continue;
|
|
1712
|
-
if (prop.startsWith("mso-") || prop.startsWith("-mso-")) continue;
|
|
1713
|
-
if (/expression|javascript:|behavior:|url\(\s*['"]?\s*(javascript|data):/i.test(val)) continue;
|
|
1714
|
-
out.push(`${prop}:${val}`);
|
|
1715
|
-
}
|
|
1716
|
-
return out.join(";");
|
|
1717
|
-
}
|
|
1718
|
-
function sanitizeClass(value) {
|
|
1719
|
-
return String(value).split(/\s+/).filter((name) => /^[\w-]+$/.test(name) && !/^(script|javascript)/i.test(name)).join(" ");
|
|
1720
|
-
}
|
|
1721
|
-
function keepAttribute(tagName, attrName, attrValue) {
|
|
1722
|
-
const name = attrName.toLowerCase();
|
|
1723
|
-
if (name.startsWith("on")) return false;
|
|
1724
|
-
if (GLOBAL_ATTRS.has(name)) return true;
|
|
1725
|
-
if (DATA_PREFIX.some((prefix) => name.startsWith(prefix))) return true;
|
|
1726
|
-
const list = TAG_ATTRS[tagName] || [];
|
|
1727
|
-
return list.includes(name);
|
|
1728
|
-
}
|
|
1729
|
-
function sanitizeHtml(html, { allowEmpty = false } = {}) {
|
|
1730
|
-
if (!html) return allowEmpty ? "" : "<p><br></p>";
|
|
1731
|
-
const doc = new DOMParser().parseFromString(`<div>${html}</div>`, "text/html");
|
|
1732
|
-
const root = doc.body.firstChild;
|
|
1733
|
-
walk(root);
|
|
1734
|
-
const result = root.innerHTML.trim();
|
|
1735
|
-
if (!result && !allowEmpty) return "<p><br></p>";
|
|
1736
|
-
return result;
|
|
1737
|
-
}
|
|
1738
|
-
function walk(node) {
|
|
1739
|
-
const children = Array.from(node.childNodes);
|
|
1740
|
-
for (const child of children) {
|
|
1741
|
-
if (child.nodeType === 8) {
|
|
1742
|
-
child.remove();
|
|
1743
|
-
continue;
|
|
1744
|
-
}
|
|
1745
|
-
if (child.nodeType === 3) continue;
|
|
1746
|
-
if (child.nodeType !== 1) {
|
|
1747
|
-
child.remove();
|
|
1748
|
-
continue;
|
|
1749
|
-
}
|
|
1750
|
-
const tagName = child.tagName;
|
|
1751
|
-
if (!ALLOWED_TAGS.has(tagName.toLowerCase())) {
|
|
1752
|
-
if (tagName === "SCRIPT" || tagName === "STYLE" || tagName === "IFRAME" || tagName === "OBJECT" || tagName === "EMBED" || tagName === "FORM" || tagName === "LINK" || tagName === "META") {
|
|
1753
|
-
child.remove();
|
|
1754
|
-
continue;
|
|
1755
|
-
}
|
|
1756
|
-
const parent = child.parentNode;
|
|
1757
|
-
while (child.firstChild) parent.insertBefore(child.firstChild, child);
|
|
1758
|
-
parent.removeChild(child);
|
|
1759
|
-
continue;
|
|
1760
|
-
}
|
|
1761
|
-
for (const attr of Array.from(child.attributes)) {
|
|
1762
|
-
if (!keepAttribute(tagName, attr.name, attr.value)) {
|
|
1763
|
-
child.removeAttribute(attr.name);
|
|
1764
|
-
continue;
|
|
1765
|
-
}
|
|
1766
|
-
const lower = attr.name.toLowerCase();
|
|
1767
|
-
if (lower === "style") child.setAttribute("style", sanitizeStyle(attr.value));
|
|
1768
|
-
else if (lower === "class") {
|
|
1769
|
-
const cls = sanitizeClass(attr.value);
|
|
1770
|
-
if (cls) child.setAttribute("class", cls);
|
|
1771
|
-
else child.removeAttribute("class");
|
|
1772
|
-
} else if (lower === "href" || lower === "src" || lower === "poster") {
|
|
1773
|
-
if (!isSafeUrl(attr.value)) child.removeAttribute(attr.name);
|
|
1774
|
-
}
|
|
1775
|
-
}
|
|
1776
|
-
if (tagName === "A" && child.getAttribute("target") === "_blank") child.setAttribute("rel", "noopener noreferrer");
|
|
1777
|
-
if (child.getAttribute("href") === "" || !child.getAttribute("href")) {
|
|
1778
|
-
if (tagName === "A") child.removeAttribute("href");
|
|
3654
|
+
setVideoWidth(width) {
|
|
3655
|
+
if (!this.node) return;
|
|
3656
|
+
this.node.style.width = width;
|
|
3657
|
+
this.editor.commitHistory();
|
|
3658
|
+
this.position();
|
|
3659
|
+
}
|
|
3660
|
+
remove() {
|
|
3661
|
+
if (!this.node) return;
|
|
3662
|
+
const task = this.editor.media.taskFromNode(this.node);
|
|
3663
|
+
if (task) this.editor.media.remove(task);
|
|
3664
|
+
else {
|
|
3665
|
+
const next = this.node.nextElementSibling;
|
|
3666
|
+
this.node.remove();
|
|
3667
|
+
if (next) this.editor.focus();
|
|
3668
|
+
this.editor.commitHistory();
|
|
1779
3669
|
}
|
|
1780
|
-
|
|
3670
|
+
this.hide();
|
|
3671
|
+
this.editor.refreshStatus();
|
|
3672
|
+
}
|
|
3673
|
+
onClick() {
|
|
3674
|
+
}
|
|
3675
|
+
destroy() {
|
|
3676
|
+
this.el.remove();
|
|
3677
|
+
this.replaceInput.remove();
|
|
3678
|
+
this.resizeEl.remove();
|
|
3679
|
+
this.resizeTip.remove();
|
|
1781
3680
|
}
|
|
1782
3681
|
}
|
|
1783
|
-
|
|
1784
|
-
|
|
1785
|
-
|
|
3682
|
+
function btn(iconName, title, onclick, active = false) {
|
|
3683
|
+
const node = h("button", { type: "button", title, html: icon(iconName) });
|
|
3684
|
+
if (active) node.classList.add("ke-is-active");
|
|
3685
|
+
node.addEventListener("click", onclick);
|
|
3686
|
+
return node;
|
|
1786
3687
|
}
|
|
1787
|
-
function
|
|
1788
|
-
const
|
|
1789
|
-
|
|
1790
|
-
|
|
1791
|
-
const tag = node.tagName.toLowerCase();
|
|
1792
|
-
if (tag.startsWith("o:") || tag.startsWith("w:") || tag === "style" || tag === "script" || tag === "link" || tag === "meta") {
|
|
1793
|
-
node.remove();
|
|
1794
|
-
return;
|
|
1795
|
-
}
|
|
1796
|
-
if (tag === "img") {
|
|
1797
|
-
const width = Number(node.getAttribute("width") || 0);
|
|
1798
|
-
const height = Number(node.getAttribute("height") || 0);
|
|
1799
|
-
if (width && width <= 3 || height && height <= 3) node.remove();
|
|
1800
|
-
return;
|
|
1801
|
-
}
|
|
1802
|
-
if (tag === "font") {
|
|
1803
|
-
const size = WORD_FONT_SIZES[Number(node.getAttribute("size"))];
|
|
1804
|
-
const span = doc.createElement("span");
|
|
1805
|
-
const styles = [];
|
|
1806
|
-
if (size) styles.push(`font-size:${size}px`);
|
|
1807
|
-
if (node.color) styles.push(`color:${node.color}`);
|
|
1808
|
-
if (styles.length) span.setAttribute("style", styles.join(";"));
|
|
1809
|
-
while (node.firstChild) span.appendChild(node.firstChild);
|
|
1810
|
-
node.replaceWith(span);
|
|
1811
|
-
return;
|
|
1812
|
-
}
|
|
1813
|
-
for (const attr of Array.from(node.attributes)) {
|
|
1814
|
-
const name = attr.name.toLowerCase();
|
|
1815
|
-
if (name.startsWith("mso-") || name === "class" || name.startsWith("_") || name.startsWith("w:") || name.startsWith("o:") || name === "lang" || name === "dir") {
|
|
1816
|
-
node.removeAttribute(attr.name);
|
|
1817
|
-
}
|
|
1818
|
-
}
|
|
1819
|
-
});
|
|
1820
|
-
return root.innerHTML;
|
|
3688
|
+
function textBtn(label, title, onclick) {
|
|
3689
|
+
const node = h("button", { type: "button", title, text: label });
|
|
3690
|
+
node.addEventListener("click", onclick);
|
|
3691
|
+
return node;
|
|
1821
3692
|
}
|
|
1822
|
-
|
|
1823
|
-
|
|
3693
|
+
const sep = () => h("span.ke-sep");
|
|
3694
|
+
function toggleRadius(img, node) {
|
|
3695
|
+
if (!img) return;
|
|
3696
|
+
const has = parseFloat(getComputedStyle(img).borderRadius) > 0;
|
|
3697
|
+
img.style.borderRadius = has ? "0" : "10px";
|
|
3698
|
+
node.dispatchEvent(new Event("change", { bubbles: true }));
|
|
1824
3699
|
}
|
|
1825
|
-
function
|
|
1826
|
-
|
|
1827
|
-
|
|
1828
|
-
|
|
1829
|
-
return
|
|
3700
|
+
function previewImage(img) {
|
|
3701
|
+
if (img) lightbox(img.src);
|
|
3702
|
+
}
|
|
3703
|
+
function clamp(value, min, max) {
|
|
3704
|
+
return Math.min(max, Math.max(min, value));
|
|
3705
|
+
}
|
|
3706
|
+
function currentWidthPercent(img, figureWidth) {
|
|
3707
|
+
var _a, _b;
|
|
3708
|
+
if (!figureWidth) return 100;
|
|
3709
|
+
const match = (_b = (_a = img == null ? void 0 : img.style) == null ? void 0 : _a.width) == null ? void 0 : _b.match(/^([\d.]+)%$/);
|
|
3710
|
+
if (match) return parseFloat(match[1]);
|
|
3711
|
+
return img.getBoundingClientRect().width / figureWidth * 100;
|
|
1830
3712
|
}
|
|
1831
3713
|
const DEFAULT_TIMEOUT = 1e4;
|
|
1832
3714
|
function pickArray(raw) {
|
|
@@ -2010,7 +3892,7 @@ function fill(template, item) {
|
|
|
2010
3892
|
return fromRaw === void 0 || fromRaw === null ? match : String(fromRaw);
|
|
2011
3893
|
});
|
|
2012
3894
|
}
|
|
2013
|
-
function pick
|
|
3895
|
+
function pick(raw, item, editor) {
|
|
2014
3896
|
return typeof raw === "function" ? raw(item, editor) : raw;
|
|
2015
3897
|
}
|
|
2016
3898
|
function resolveLink(spec, item, editor) {
|
|
@@ -2022,10 +3904,10 @@ function resolveLink(spec, item, editor) {
|
|
|
2022
3904
|
else if (conf === true || item.url) raw = { url: item.url };
|
|
2023
3905
|
if (!raw) return null;
|
|
2024
3906
|
if (typeof raw === "string") raw = { url: raw };
|
|
2025
|
-
const url = normalizeUrl(fill(String(pick
|
|
3907
|
+
const url = normalizeUrl(fill(String(pick(raw.url, item, editor) ?? ""), item));
|
|
2026
3908
|
if (!url || !isSafeUrl(url)) return null;
|
|
2027
|
-
const text = pick
|
|
2028
|
-
const title = pick
|
|
3909
|
+
const text = pick(raw.text, item, editor);
|
|
3910
|
+
const title = pick(raw.title, item, editor);
|
|
2029
3911
|
const mode = raw.mode === "open" ? "open" : "insert";
|
|
2030
3912
|
const target = raw.target === "_self" || raw.target === false ? "_self" : "_blank";
|
|
2031
3913
|
return {
|
|
@@ -2136,6 +4018,7 @@ const DEFAULT_TOOLBAR = [
|
|
|
2136
4018
|
"hr",
|
|
2137
4019
|
"clear",
|
|
2138
4020
|
":tail",
|
|
4021
|
+
"markdown",
|
|
2139
4022
|
"source",
|
|
2140
4023
|
"fullscreen"
|
|
2141
4024
|
];
|
|
@@ -2157,7 +4040,8 @@ const ITEMS = {
|
|
|
2157
4040
|
image: { icon: "image", title: "图片(本地上传 / 网络链接)", run: (e) => e.toolbar.openMedia("image"), toggles: true },
|
|
2158
4041
|
video: { icon: "video", title: "视频(本地上传 / 网络链接,支持分片上传)", run: (e) => e.toolbar.openMedia("video"), toggles: true },
|
|
2159
4042
|
table: { icon: "table", title: "插入表格", run: (e) => e.toolbar.openTable(), toggles: true },
|
|
2160
|
-
code: { icon: "code", title: "
|
|
4043
|
+
code: { icon: "code", title: "代码块(选择语言并语法高亮)", run: (e) => e.toolbar.openCode(), active: (s) => s.inCode, toggles: true },
|
|
4044
|
+
markdown: { icon: "markdown", text: "导入MD", title: "导入 Markdown 文件 / 粘贴 Markdown 文本,转为 HTML 显示(.md / .txt)", run: (e) => e.toolbar.openMarkdown(), toggles: true },
|
|
2161
4045
|
hr: { icon: "hr", title: "分割线", run: (e) => e.commands.insertDivider() },
|
|
2162
4046
|
clear: { icon: "clear", title: "清除格式", run: (e) => e.commands.clearFormat() },
|
|
2163
4047
|
source: { icon: "source", title: "查看 / 编辑 HTML 源码(⌘/Ctrl+Shift+K)", text: "源码", run: (e) => e.toggleSource(), active: (s) => s.source },
|
|
@@ -2565,6 +4449,51 @@ class Toolbar {
|
|
|
2565
4449
|
this.editor.commands.setColor(kind, color);
|
|
2566
4450
|
this.editor.popover.close();
|
|
2567
4451
|
}
|
|
4452
|
+
/**
|
|
4453
|
+
* 代码块:光标不在代码块里 = 选语言后插入;在代码块里 = 换语言并重新高亮
|
|
4454
|
+
* (代码块对象在打开面板时就锁定,避免面板抢焦点后选区丢失)
|
|
4455
|
+
*/
|
|
4456
|
+
openCode() {
|
|
4457
|
+
const button = this.buttons.get("code");
|
|
4458
|
+
const block = codeBlockAt(this.editor.root);
|
|
4459
|
+
this.togglePop("code", button, () => codePanel({
|
|
4460
|
+
languages: this.editor.codeLanguages(),
|
|
4461
|
+
value: block ? languageOf(block) || "plaintext" : this.editor.lastCodeLang,
|
|
4462
|
+
editing: !!block,
|
|
4463
|
+
onPick: (lang) => {
|
|
4464
|
+
this.editor.lastCodeLang = lang;
|
|
4465
|
+
this.editor.popover.close();
|
|
4466
|
+
this.editor.restoreSelection();
|
|
4467
|
+
if (block) this.editor.commands.setCodeLanguage(lang, block);
|
|
4468
|
+
else this.editor.commands.insertCodeBlock("", lang);
|
|
4469
|
+
this.editor.refresh();
|
|
4470
|
+
}
|
|
4471
|
+
}));
|
|
4472
|
+
}
|
|
4473
|
+
/**
|
|
4474
|
+
* 打开 Markdown 导入面板:选文件 / 粘贴文本 → 预览 → 按落点导入
|
|
4475
|
+
* (转换与落点模式都复用 options.markdown,保证面板与 API 行为一致)
|
|
4476
|
+
*/
|
|
4477
|
+
openMarkdown() {
|
|
4478
|
+
const button = this.buttons.get("markdown");
|
|
4479
|
+
const editor = this.editor;
|
|
4480
|
+
const config = editor.options.markdown;
|
|
4481
|
+
this.togglePop("markdown", button, () => markdownPanel({
|
|
4482
|
+
insertMode: normalizeInsertMode(config.insertMode),
|
|
4483
|
+
accept: MARKDOWN_ACCEPT,
|
|
4484
|
+
maxText: config.maxSize ? `单个文件上限 ${formatSize(config.maxSize)}` : "",
|
|
4485
|
+
highlight: editor.options.code.highlight !== false,
|
|
4486
|
+
onConvert: (text) => {
|
|
4487
|
+
const html = markdownToHtml(text, config);
|
|
4488
|
+
return { html, summary: markdownSummary(html) };
|
|
4489
|
+
},
|
|
4490
|
+
onImport: async ({ text, mode }) => {
|
|
4491
|
+
editor.popover.close();
|
|
4492
|
+
const result = await editor.importMarkdown(text, { mode });
|
|
4493
|
+
return result.ok;
|
|
4494
|
+
}
|
|
4495
|
+
}));
|
|
4496
|
+
}
|
|
2568
4497
|
openTable() {
|
|
2569
4498
|
const button = this.buttons.get("table");
|
|
2570
4499
|
this.togglePop("table", button, () => tablePanel((cols, rows) => {
|
|
@@ -2852,7 +4781,7 @@ function setCaretOffset(root, offset) {
|
|
|
2852
4781
|
}
|
|
2853
4782
|
}
|
|
2854
4783
|
}
|
|
2855
|
-
function insertNode(root, node, { inline = false, selectAfter = true } = {}) {
|
|
4784
|
+
function insertNode(root, node, { inline: inline2 = false, selectAfter = true } = {}) {
|
|
2856
4785
|
root.focus();
|
|
2857
4786
|
const range = getRange(root);
|
|
2858
4787
|
if (!range) {
|
|
@@ -2861,7 +4790,7 @@ function insertNode(root, node, { inline = false, selectAfter = true } = {}) {
|
|
|
2861
4790
|
return node;
|
|
2862
4791
|
}
|
|
2863
4792
|
if (!range.collapsed) range.deleteContents();
|
|
2864
|
-
if (
|
|
4793
|
+
if (inline2) {
|
|
2865
4794
|
range.insertNode(node);
|
|
2866
4795
|
} else {
|
|
2867
4796
|
const block = closestBlock(range.startContainer, root);
|
|
@@ -3061,13 +4990,44 @@ class Commands {
|
|
|
3061
4990
|
this.exec("insertHTML", "");
|
|
3062
4991
|
this.editor.afterEdit();
|
|
3063
4992
|
}
|
|
3064
|
-
|
|
4993
|
+
/**
|
|
4994
|
+
* 插入代码块(默认语言取 options.code.defaultLanguage),并把光标放进代码里
|
|
4995
|
+
*/
|
|
4996
|
+
insertCodeBlock(code = "", lang) {
|
|
3065
4997
|
const pre = document.createElement("pre");
|
|
3066
4998
|
const codeEl = document.createElement("code");
|
|
3067
4999
|
codeEl.textContent = code || "// 在这里输入代码";
|
|
3068
5000
|
pre.appendChild(codeEl);
|
|
5001
|
+
applyLanguage(pre, lang || this.editor.lastCodeLang);
|
|
5002
|
+
refreshCodeBlock(pre);
|
|
3069
5003
|
insertNode(this.root, pre);
|
|
3070
5004
|
this.editor.afterEdit();
|
|
5005
|
+
this.placeCaretIn(pre);
|
|
5006
|
+
return pre;
|
|
5007
|
+
}
|
|
5008
|
+
/** 切换光标所在(或显式指定)代码块的语言并重新高亮;caret 保持块内光标 */
|
|
5009
|
+
setCodeLanguage(lang, target) {
|
|
5010
|
+
const pre = target || codeBlockAt(this.root);
|
|
5011
|
+
if (!pre) return null;
|
|
5012
|
+
const value = applyLanguage(pre, lang);
|
|
5013
|
+
refreshCodeBlock(pre, { caret: true });
|
|
5014
|
+
this.editor.afterEdit();
|
|
5015
|
+
return value;
|
|
5016
|
+
}
|
|
5017
|
+
/** 光标落在代码块内容末尾,插入后可以立刻敲代码 */
|
|
5018
|
+
placeCaretIn(pre) {
|
|
5019
|
+
const codeEl = codeElementOf(pre);
|
|
5020
|
+
const range = document.createRange();
|
|
5021
|
+
range.selectNodeContents(codeEl);
|
|
5022
|
+
range.collapse(false);
|
|
5023
|
+
const sel = window.getSelection();
|
|
5024
|
+
sel.removeAllRanges();
|
|
5025
|
+
sel.addRange(range);
|
|
5026
|
+
}
|
|
5027
|
+
/** 当前光标所在代码块的语言;不在代码块中返回空串 */
|
|
5028
|
+
currentCodeLang() {
|
|
5029
|
+
const pre = codeBlockAt(this.root);
|
|
5030
|
+
return pre ? languageOf(pre) : "";
|
|
3071
5031
|
}
|
|
3072
5032
|
insertDivider() {
|
|
3073
5033
|
const hr = document.createElement("hr");
|
|
@@ -3082,6 +5042,9 @@ class Commands {
|
|
|
3082
5042
|
range.deleteContents();
|
|
3083
5043
|
const tmp = document.createElement("div");
|
|
3084
5044
|
tmp.innerHTML = value;
|
|
5045
|
+
tmp.querySelectorAll("pre").forEach((pre) => {
|
|
5046
|
+
if (pre.querySelector("code") || pre.hasAttribute("data-k-lang")) refreshCodeBlock(pre);
|
|
5047
|
+
});
|
|
3085
5048
|
const frag = document.createDocumentFragment();
|
|
3086
5049
|
while (tmp.firstChild) frag.appendChild(tmp.firstChild);
|
|
3087
5050
|
const last = frag.lastChild;
|
|
@@ -3582,28 +5545,83 @@ function createFingerprint(mode = "fast") {
|
|
|
3582
5545
|
return async (file) => fastFingerprint(file);
|
|
3583
5546
|
}
|
|
3584
5547
|
const MB$1 = 1024 * 1024;
|
|
5548
|
+
class SimpleUploader {
|
|
5549
|
+
constructor(adapter, options = {}) {
|
|
5550
|
+
if (!adapter || typeof adapter.upload !== "function") {
|
|
5551
|
+
throw new Error("[KEditor] 普通上传的 uploader 需要提供 upload() 方法(或直接给一个接口地址 / 上传函数),参见 docs/upload-adapter.md");
|
|
5552
|
+
}
|
|
5553
|
+
this.adapter = adapter;
|
|
5554
|
+
this.mode = "normal";
|
|
5555
|
+
this.options = options;
|
|
5556
|
+
}
|
|
5557
|
+
/**
|
|
5558
|
+
* @param {File|Blob} file
|
|
5559
|
+
* @param {{onProgress?,signal?}} handlers
|
|
5560
|
+
* @returns {Promise<{url:string, chunks:number, size:number, name:string, mode:string}>}
|
|
5561
|
+
*/
|
|
5562
|
+
async upload(file, handlers = {}) {
|
|
5563
|
+
const { onProgress, signal } = handlers;
|
|
5564
|
+
const startedAt = Date.now();
|
|
5565
|
+
const report = (ratio, loaded) => {
|
|
5566
|
+
const elapsed = (Date.now() - startedAt) / 1e3;
|
|
5567
|
+
onProgress == null ? void 0 : onProgress(ratio, {
|
|
5568
|
+
percent: Math.round(ratio * 100),
|
|
5569
|
+
loaded,
|
|
5570
|
+
total: file.size,
|
|
5571
|
+
chunks: 1,
|
|
5572
|
+
uploadedChunks: ratio >= 1 ? 1 : 0,
|
|
5573
|
+
speed: elapsed > 0 ? loaded / elapsed : 0,
|
|
5574
|
+
mode: "normal"
|
|
5575
|
+
});
|
|
5576
|
+
};
|
|
5577
|
+
report(0, 0);
|
|
5578
|
+
const result = await this.adapter.upload(file, {
|
|
5579
|
+
signal,
|
|
5580
|
+
onProgress: (loaded, total) => report(total ? Math.min(1, loaded / total) : 0, loaded)
|
|
5581
|
+
});
|
|
5582
|
+
const url = typeof result === "string" ? result : result == null ? void 0 : result.url;
|
|
5583
|
+
if (!url) throw new Error('[KEditor] 普通上传接口未返回 url:期望响应形如 { "url": "https://…" }');
|
|
5584
|
+
report(1, file.size);
|
|
5585
|
+
return {
|
|
5586
|
+
url,
|
|
5587
|
+
chunks: 1,
|
|
5588
|
+
mode: "normal",
|
|
5589
|
+
size: file.size,
|
|
5590
|
+
name: file.name,
|
|
5591
|
+
key: typeof result === "object" ? result.key : void 0,
|
|
5592
|
+
raw: result
|
|
5593
|
+
};
|
|
5594
|
+
}
|
|
5595
|
+
destroy() {
|
|
5596
|
+
var _a, _b;
|
|
5597
|
+
(_b = (_a = this.adapter).destroy) == null ? void 0 : _b.call(_a);
|
|
5598
|
+
}
|
|
5599
|
+
}
|
|
3585
5600
|
class ChunkUploader {
|
|
3586
5601
|
constructor(adapter, options = {}) {
|
|
3587
|
-
if (!adapter || typeof adapter.put !== "function") {
|
|
3588
|
-
throw new Error("[KEditor] uploader 需要提供 put() 方法,参见 docs/upload-adapter.md");
|
|
5602
|
+
if (!adapter || typeof adapter.put !== "function" && typeof adapter.upload !== "function") {
|
|
5603
|
+
throw new Error("[KEditor] 分片上传的 uploader 需要提供 put() 方法,参见 docs/upload-adapter.md");
|
|
3589
5604
|
}
|
|
3590
5605
|
this.adapter = adapter;
|
|
5606
|
+
this.simple = typeof adapter.put === "function" ? null : new SimpleUploader(adapter, options);
|
|
5607
|
+
this.mode = "chunk";
|
|
3591
5608
|
this.chunkSize = Math.max(64 * 1024, options.chunkSize || MB$1);
|
|
3592
5609
|
this.concurrency = Math.max(1, options.concurrency || 3);
|
|
3593
5610
|
this.retries = options.retries === void 0 ? 2 : Math.max(0, options.retries);
|
|
3594
5611
|
this.retryDelay = options.retryDelay ?? 600;
|
|
3595
5612
|
this.fingerprint = createFingerprint(options.fingerprint || "fast");
|
|
3596
5613
|
this.slice = options.slice;
|
|
5614
|
+
this.completeOnUrl = options.completeOnUrl === void 0 ? Boolean(adapter.completeOnUrl) : Boolean(options.completeOnUrl);
|
|
3597
5615
|
}
|
|
3598
5616
|
/**
|
|
3599
5617
|
* @param {File|Blob} file
|
|
3600
5618
|
* @param {{onProgress?,onChunk?,onInfo?,signal?}} handlers
|
|
3601
|
-
* @returns {Promise<{url:string, instant?:boolean, chunks:number, size:number, name:string}>}
|
|
5619
|
+
* @returns {Promise<{url:string, instant?:boolean, chunks:number, size:number, name:string, mode:string}>}
|
|
3602
5620
|
*/
|
|
3603
5621
|
async upload(file, handlers = {}) {
|
|
3604
5622
|
var _a, _b, _c, _d, _e, _f;
|
|
5623
|
+
if (this.simple) return this.simple.upload(file, handlers);
|
|
3605
5624
|
const { onProgress, onChunk, signal } = handlers;
|
|
3606
|
-
if (this.adapter.simple) return this.uploadSimple(file, handlers);
|
|
3607
5625
|
const total = Math.max(1, Math.ceil(file.size / this.chunkSize));
|
|
3608
5626
|
const meta = {
|
|
3609
5627
|
name: file.name || "blob",
|
|
@@ -3616,8 +5634,8 @@ class ChunkUploader {
|
|
|
3616
5634
|
};
|
|
3617
5635
|
const init = await ((_b = (_a = this.adapter).init) == null ? void 0 : _b.call(_a, meta, { signal })) || {};
|
|
3618
5636
|
if (init.url) {
|
|
3619
|
-
onProgress == null ? void 0 : onProgress(1, { percent: 100, loaded: file.size, total: file.size, chunks: total, instant: true });
|
|
3620
|
-
return { url: init.url, instant: true, chunks: 0, size: file.size, name: meta.name, key: init.key };
|
|
5637
|
+
onProgress == null ? void 0 : onProgress(1, { percent: 100, loaded: file.size, total: file.size, chunks: total, instant: true, mode: "chunk" });
|
|
5638
|
+
return { url: init.url, instant: true, chunks: 0, mode: "chunk", size: file.size, name: meta.name, key: init.key };
|
|
3621
5639
|
}
|
|
3622
5640
|
const uploadId = init.uploadId || meta.fingerprint;
|
|
3623
5641
|
const uploaded = new Set((init.uploadedChunks || init.uploaded || []).map(Number));
|
|
@@ -3627,6 +5645,7 @@ class ChunkUploader {
|
|
|
3627
5645
|
for (let i = 0; i < total; i += 1) if (!uploaded.has(i)) queue.push(i);
|
|
3628
5646
|
const chunkResults = new Array(total);
|
|
3629
5647
|
let doneChunks = uploaded.size;
|
|
5648
|
+
let finishedUrl = "";
|
|
3630
5649
|
const startedAt = Date.now();
|
|
3631
5650
|
const report = () => {
|
|
3632
5651
|
const elapsed = (Date.now() - startedAt) / 1e3;
|
|
@@ -3636,14 +5655,14 @@ class ChunkUploader {
|
|
|
3636
5655
|
total: file.size,
|
|
3637
5656
|
chunks: total,
|
|
3638
5657
|
uploadedChunks: doneChunks,
|
|
3639
|
-
speed: elapsed > 0 ? loadedBytes / elapsed : 0
|
|
5658
|
+
speed: elapsed > 0 ? loadedBytes / elapsed : 0,
|
|
5659
|
+
mode: "chunk"
|
|
3640
5660
|
});
|
|
3641
5661
|
};
|
|
3642
5662
|
report();
|
|
3643
5663
|
let cursor = 0;
|
|
3644
|
-
let firstError = null;
|
|
3645
5664
|
const worker = async () => {
|
|
3646
|
-
while (cursor < queue.length) {
|
|
5665
|
+
while (cursor < queue.length && !finishedUrl) {
|
|
3647
5666
|
if (signal == null ? void 0 : signal.aborted) throw new DOMException("已取消上传", "AbortError");
|
|
3648
5667
|
const index = queue[cursor++];
|
|
3649
5668
|
const blob = this.slice ? this.slice(file, index, this.chunkSize) : file.slice(index * this.chunkSize, (index + 1) * this.chunkSize);
|
|
@@ -3662,6 +5681,13 @@ class ChunkUploader {
|
|
|
3662
5681
|
size: blob.size
|
|
3663
5682
|
});
|
|
3664
5683
|
if (res == null ? void 0 : res.url) chunkResults[index] = res;
|
|
5684
|
+
if ((res == null ? void 0 : res.url) && this.completeOnUrl) {
|
|
5685
|
+
finishedUrl = res.url;
|
|
5686
|
+
doneChunks = total;
|
|
5687
|
+
loadedBytes = file.size;
|
|
5688
|
+
report();
|
|
5689
|
+
break;
|
|
5690
|
+
}
|
|
3665
5691
|
loadedBytes += blob.size;
|
|
3666
5692
|
doneChunks += 1;
|
|
3667
5693
|
onChunk == null ? void 0 : onChunk({ index, total, size: blob.size });
|
|
@@ -3671,7 +5697,6 @@ class ChunkUploader {
|
|
|
3671
5697
|
if ((error == null ? void 0 : error.name) === "AbortError") throw error;
|
|
3672
5698
|
attempt += 1;
|
|
3673
5699
|
if (attempt > this.retries) {
|
|
3674
|
-
firstError = error;
|
|
3675
5700
|
throw new Error(`分片 ${index + 1}/${total} 上传失败:${(error == null ? void 0 : error.message) || error}`);
|
|
3676
5701
|
}
|
|
3677
5702
|
await sleep$1(this.retryDelay * attempt, signal);
|
|
@@ -3680,38 +5705,26 @@ class ChunkUploader {
|
|
|
3680
5705
|
}
|
|
3681
5706
|
};
|
|
3682
5707
|
const workers = Array.from({ length: Math.max(1, Math.min(this.concurrency, queue.length)) }, worker);
|
|
3683
|
-
|
|
3684
|
-
|
|
3685
|
-
|
|
3686
|
-
await ((_d = (_c = this.adapter).abort) == null ? void 0 : _d.call(_c, { uploadId, meta, error }).catch(() => {
|
|
5708
|
+
const settled = await Promise.allSettled(workers);
|
|
5709
|
+
const failure = finishedUrl ? null : settled.find((item) => item.status === "rejected");
|
|
5710
|
+
if (failure) {
|
|
5711
|
+
await ((_d = (_c = this.adapter).abort) == null ? void 0 : _d.call(_c, { uploadId, meta, error: failure.reason }).catch(() => {
|
|
3687
5712
|
}));
|
|
3688
|
-
throw
|
|
5713
|
+
throw failure.reason;
|
|
3689
5714
|
}
|
|
3690
|
-
|
|
3691
|
-
const done = await ((_f = (_e = this.adapter).complete) == null ? void 0 : _f.call(_e, { uploadId, meta, total, uploaded: doneChunks, chunkResults, file })) || {};
|
|
5715
|
+
const done = finishedUrl ? { url: finishedUrl } : await ((_f = (_e = this.adapter).complete) == null ? void 0 : _f.call(_e, { uploadId, meta, total, uploaded: doneChunks, chunkResults, file })) || {};
|
|
3692
5716
|
const url = done.url;
|
|
3693
|
-
if (!url)
|
|
3694
|
-
|
|
3695
|
-
|
|
3696
|
-
|
|
3697
|
-
|
|
3698
|
-
|
|
3699
|
-
const startedAt = Date.now();
|
|
3700
|
-
const result = await this.adapter.upload(file, {
|
|
3701
|
-
signal,
|
|
3702
|
-
onProgress: (loaded, total) => {
|
|
3703
|
-
const ratio = total ? loaded / total : 0;
|
|
3704
|
-
const elapsed = (Date.now() - startedAt) / 1e3;
|
|
3705
|
-
onProgress == null ? void 0 : onProgress(ratio, { percent: Math.round(ratio * 100), loaded, total: total || file.size, chunks: 1, uploadedChunks: ratio >= 1 ? 1 : 0, speed: elapsed > 0 ? loaded / elapsed : 0 });
|
|
3706
|
-
}
|
|
3707
|
-
});
|
|
3708
|
-
const url = typeof result === "string" ? result : result == null ? void 0 : result.url;
|
|
3709
|
-
if (!url) throw new Error("[KEditor] uploader.upload() 未返回 url");
|
|
3710
|
-
return { url, chunks: 1, size: file.size, name: file.name, key: typeof result === "object" ? result.key : void 0, raw: result };
|
|
5717
|
+
if (!url) {
|
|
5718
|
+
throw new Error(
|
|
5719
|
+
this.completeOnUrl ? '[KEditor] 上传结束但接口未返回 url:分片上传要求接口在处理分片时返回 { "url": "…" }' : "[KEditor] uploader.complete() 未返回 url"
|
|
5720
|
+
);
|
|
5721
|
+
}
|
|
5722
|
+
return { url, chunks: total, mode: "chunk", size: file.size, name: meta.name, key: done.key, poster: done.poster, duration: done.duration, raw: done };
|
|
3711
5723
|
}
|
|
3712
5724
|
destroy() {
|
|
3713
|
-
var _a, _b;
|
|
3714
|
-
(
|
|
5725
|
+
var _a, _b, _c;
|
|
5726
|
+
(_a = this.simple) == null ? void 0 : _a.destroy();
|
|
5727
|
+
(_c = (_b = this.adapter).destroy) == null ? void 0 : _c.call(_b);
|
|
3715
5728
|
}
|
|
3716
5729
|
}
|
|
3717
5730
|
const sleep$1 = (ms, signal) => new Promise((resolve, reject) => {
|
|
@@ -3763,8 +5776,19 @@ function mockAdapter(options = {}) {
|
|
|
3763
5776
|
const objectUrls = /* @__PURE__ */ new Map();
|
|
3764
5777
|
let failOnce = failFirstChunk;
|
|
3765
5778
|
const emit = (type, payload) => onEvent == null ? void 0 : onEvent(type, { ...payload, at: Date.now() });
|
|
5779
|
+
const urlFor = (file, meta) => {
|
|
5780
|
+
let url = objectUrls.get(meta.fingerprint);
|
|
5781
|
+
if (!url || !reuseObjectUrl) {
|
|
5782
|
+
const blob = file instanceof File ? file : new File([file], meta.name, { type: meta.type });
|
|
5783
|
+
url = URL.createObjectURL(blob);
|
|
5784
|
+
objectUrls.set(meta.fingerprint, url);
|
|
5785
|
+
}
|
|
5786
|
+
return url;
|
|
5787
|
+
};
|
|
5788
|
+
const remember = (meta, url) => finished.set(meta.fingerprint, { url, name: meta.name, size: meta.size, type: meta.type });
|
|
3766
5789
|
return {
|
|
3767
5790
|
name: "mock",
|
|
5791
|
+
/* ---------------- 分片上传链路 ---------------- */
|
|
3768
5792
|
async init(meta) {
|
|
3769
5793
|
emit("init", meta);
|
|
3770
5794
|
await sleep(120);
|
|
@@ -3795,17 +5819,39 @@ function mockAdapter(options = {}) {
|
|
|
3795
5819
|
},
|
|
3796
5820
|
async complete({ uploadId, meta, file }) {
|
|
3797
5821
|
await sleep(140);
|
|
3798
|
-
|
|
3799
|
-
|
|
3800
|
-
const blob = file instanceof File ? file : new File([file], meta.name, { type: meta.type });
|
|
3801
|
-
url = URL.createObjectURL(blob);
|
|
3802
|
-
objectUrls.set(meta.fingerprint, url);
|
|
3803
|
-
}
|
|
3804
|
-
finished.set(meta.fingerprint, { url, name: meta.name, size: meta.size, type: meta.type });
|
|
5822
|
+
const url = urlFor(file, meta);
|
|
5823
|
+
remember(meta, url);
|
|
3805
5824
|
sessions.delete(uploadId);
|
|
3806
5825
|
emit("complete", { name: meta.name, url, chunks: meta.totalChunks, size: meta.size });
|
|
3807
5826
|
return { url, key: meta.fingerprint };
|
|
3808
5827
|
},
|
|
5828
|
+
/* ---------------- 普通上传链路 ---------------- */
|
|
5829
|
+
async upload(file, ctx = {}) {
|
|
5830
|
+
var _a, _b;
|
|
5831
|
+
const meta = {
|
|
5832
|
+
name: file.name || "blob",
|
|
5833
|
+
size: file.size,
|
|
5834
|
+
type: file.type || "application/octet-stream",
|
|
5835
|
+
// 不做哈希:演示用「文件名 + 大小 + 修改时间」即可识别同一份文件
|
|
5836
|
+
fingerprint: `${file.name || "blob"}|${file.size}|${file.lastModified || 0}`
|
|
5837
|
+
};
|
|
5838
|
+
const hit = finished.get(meta.fingerprint);
|
|
5839
|
+
if (hit) {
|
|
5840
|
+
(_a = ctx.onProgress) == null ? void 0 : _a.call(ctx, file.size, file.size);
|
|
5841
|
+
emit("instant", { name: meta.name, url: hit.url });
|
|
5842
|
+
return { url: hit.url, key: meta.fingerprint, instant: true };
|
|
5843
|
+
}
|
|
5844
|
+
const cost = Math.max(140, jitter(latency * 2 + file.size / (speed * 1024 / 8) / 6, 0.3));
|
|
5845
|
+
const steps = 6;
|
|
5846
|
+
for (let i = 1; i <= steps; i += 1) {
|
|
5847
|
+
await sleep(cost / steps);
|
|
5848
|
+
(_b = ctx.onProgress) == null ? void 0 : _b.call(ctx, Math.round(file.size * i / steps), file.size);
|
|
5849
|
+
}
|
|
5850
|
+
const url = urlFor(file, meta);
|
|
5851
|
+
remember(meta, url);
|
|
5852
|
+
emit("upload", { name: meta.name, url, size: meta.size });
|
|
5853
|
+
return { url, key: meta.fingerprint };
|
|
5854
|
+
},
|
|
3809
5855
|
async abort({ uploadId }) {
|
|
3810
5856
|
emit("abort", { uploadId });
|
|
3811
5857
|
},
|
|
@@ -3817,22 +5863,30 @@ function mockAdapter(options = {}) {
|
|
|
3817
5863
|
}
|
|
3818
5864
|
};
|
|
3819
5865
|
}
|
|
5866
|
+
function pickUrlOf(payload) {
|
|
5867
|
+
if (!payload || typeof payload !== "object") return "";
|
|
5868
|
+
const value = payload.url || payload.fileUrl || payload.src;
|
|
5869
|
+
return typeof value === "string" ? value.trim() : "";
|
|
5870
|
+
}
|
|
5871
|
+
const LEGACY_FIELDS = ["initUrl", "chunkUrl", "completeUrl", "abortUrl"];
|
|
3820
5872
|
function httpAdapter(config = {}) {
|
|
3821
|
-
const {
|
|
3822
|
-
|
|
3823
|
-
|
|
3824
|
-
|
|
3825
|
-
|
|
3826
|
-
|
|
3827
|
-
|
|
3828
|
-
|
|
3829
|
-
|
|
3830
|
-
|
|
3831
|
-
|
|
3832
|
-
|
|
5873
|
+
const { url, fieldName = "file", headers = {}, withCredentials = false, parse = (json) => (json == null ? void 0 : json.data) || json || {}, pickUrl = pickUrlOf, chunkUrlFor } = config;
|
|
5874
|
+
const legacy = LEGACY_FIELDS.filter((key) => config[key]);
|
|
5875
|
+
if (legacy.length) {
|
|
5876
|
+
throw new Error(
|
|
5877
|
+
`[KEditor] 分片上传已改为「单接口」模式:请删除 httpAdapter 的 ${legacy.join(" / ")},只保留 url。服务端在处理分片时返回 { "url": "…" } 即代表上传成功。`
|
|
5878
|
+
);
|
|
5879
|
+
}
|
|
5880
|
+
if (!url) throw new Error('[KEditor] httpAdapter 缺少接口地址:httpAdapter({ url: "/api/upload" })');
|
|
5881
|
+
const mode = config.mode || "formdata";
|
|
5882
|
+
const httpMethod = config.method || (mode === "formdata" ? "POST" : "PUT");
|
|
5883
|
+
const withUrl = (payload) => {
|
|
5884
|
+
const found = (typeof pickUrl === "function" ? pickUrl(payload) : "") || "";
|
|
5885
|
+
return found ? { ...payload && typeof payload === "object" ? payload : {}, url: found } : payload || {};
|
|
5886
|
+
};
|
|
3833
5887
|
const headerOf = () => typeof headers === "function" ? headers() || {} : headers || {};
|
|
3834
|
-
const request = async (
|
|
3835
|
-
const res = await fetch(
|
|
5888
|
+
const request = async (target, init = {}) => {
|
|
5889
|
+
const res = await fetch(target, { credentials: withCredentials ? "include" : "same-origin", ...init });
|
|
3836
5890
|
if (!res.ok) throw new Error(`HTTP ${res.status} ${res.statusText}`);
|
|
3837
5891
|
const text = await res.text();
|
|
3838
5892
|
if (!text) return {};
|
|
@@ -3842,82 +5896,121 @@ function httpAdapter(config = {}) {
|
|
|
3842
5896
|
throw new Error(`服务端返回非 JSON 数据:${text.slice(0, 80)}`);
|
|
3843
5897
|
}
|
|
3844
5898
|
};
|
|
3845
|
-
|
|
3846
|
-
|
|
3847
|
-
|
|
3848
|
-
|
|
3849
|
-
|
|
3850
|
-
|
|
3851
|
-
|
|
3852
|
-
|
|
3853
|
-
|
|
3854
|
-
headers: { "Content-Type": "application/json", ...headerOf() },
|
|
3855
|
-
body: JSON.stringify({
|
|
3856
|
-
fileName: meta.name,
|
|
3857
|
-
fileSize: meta.size,
|
|
3858
|
-
fileType: meta.type,
|
|
3859
|
-
lastModified: meta.lastModified,
|
|
3860
|
-
identifier: meta.fingerprint,
|
|
3861
|
-
chunkSize: meta.chunkSize,
|
|
3862
|
-
totalChunks: meta.totalChunks
|
|
3863
|
-
})
|
|
3864
|
-
}
|
|
3865
|
-
);
|
|
3866
|
-
},
|
|
3867
|
-
async put({ uploadId, index, total, blob, meta, signal }) {
|
|
3868
|
-
if (!chunkUrl) throw new Error("[KEditor] httpAdapter 缺少 chunkUrl");
|
|
3869
|
-
const url = typeof chunkUrlFor === "function" ? chunkUrlFor({ uploadId, index }) : chunkUrl;
|
|
3870
|
-
if (mode === "formdata") {
|
|
3871
|
-
const form = new FormData();
|
|
3872
|
-
form.append(fieldName, blob, `${meta.name}.part${index}`);
|
|
3873
|
-
form.append("uploadId", uploadId);
|
|
3874
|
-
form.append("identifier", meta.fingerprint);
|
|
5899
|
+
const withQuery = (target, pairs) => `${target}${target.includes("?") ? "&" : "?"}${pairs.map(([k, v]) => `${k}=${encodeURIComponent(v)}`).join("&")}`;
|
|
5900
|
+
const send = async ({ target, body, name, index, total, meta, signal }) => {
|
|
5901
|
+
if (mode === "formdata") {
|
|
5902
|
+
const form = new FormData();
|
|
5903
|
+
form.append(fieldName, body, index === void 0 ? name : `${name}.part${index}`);
|
|
5904
|
+
form.append("filename", name);
|
|
5905
|
+
form.append("fileSize", String(meta.size));
|
|
5906
|
+
if (meta.identifier) form.append("identifier", meta.identifier);
|
|
5907
|
+
if (index !== void 0) {
|
|
3875
5908
|
form.append("index", String(index));
|
|
3876
5909
|
form.append("total", String(total));
|
|
3877
|
-
form.append("
|
|
3878
|
-
return request(url, { method: "POST", body: form, signal, headers: headerOf() });
|
|
5910
|
+
form.append("chunkSize", String(meta.chunkSize));
|
|
3879
5911
|
}
|
|
3880
|
-
|
|
3881
|
-
|
|
3882
|
-
|
|
3883
|
-
|
|
3884
|
-
|
|
3885
|
-
|
|
3886
|
-
|
|
3887
|
-
|
|
3888
|
-
|
|
3889
|
-
|
|
3890
|
-
|
|
3891
|
-
|
|
3892
|
-
|
|
3893
|
-
|
|
3894
|
-
method: "POST",
|
|
3895
|
-
headers: { "Content-Type": "application/json", ...headerOf() },
|
|
3896
|
-
body: JSON.stringify({ uploadId, identifier: meta.fingerprint, fileName: meta.name, fileSize: meta.size, fileType: meta.type, chunkSize: meta.chunkSize, totalChunks: total })
|
|
3897
|
-
}
|
|
3898
|
-
);
|
|
5912
|
+
return withUrl(await request(target, { method: httpMethod, body: form, signal, headers: headerOf() }));
|
|
5913
|
+
}
|
|
5914
|
+
const query = index === void 0 ? [["filename", name], ["fileSize", meta.size]] : [["identifier", meta.identifier], ["index", index], ["total", total], ["filename", name]];
|
|
5915
|
+
const headersOut = index === void 0 ? { "Content-Type": "application/octet-stream" } : { "Content-Type": "application/octet-stream", "X-Chunk-Index": String(index) };
|
|
5916
|
+
return withUrl(await request(withQuery(target, query), { method: httpMethod, body, signal, headers: { ...headersOut, ...headerOf() } }));
|
|
5917
|
+
};
|
|
5918
|
+
return {
|
|
5919
|
+
name: "http",
|
|
5920
|
+
/** 响应带非空 url 即代表上传成功(分片链路据此提前收工) */
|
|
5921
|
+
completeOnUrl: true,
|
|
5922
|
+
url,
|
|
5923
|
+
/** 普通上传:整个文件一次请求 */
|
|
5924
|
+
async upload(file, ctx = {}) {
|
|
5925
|
+
return send({ target: url, body: file, name: file.name || "file", meta: { size: file.size, identifier: "" }, signal: ctx.signal });
|
|
3899
5926
|
},
|
|
3900
|
-
|
|
3901
|
-
|
|
3902
|
-
|
|
3903
|
-
});
|
|
5927
|
+
/** 分片上传:一个分片一次请求 */
|
|
5928
|
+
async put({ index, total, blob, meta, signal }) {
|
|
5929
|
+
const target = typeof chunkUrlFor === "function" ? chunkUrlFor({ index, total }) : url;
|
|
5930
|
+
return send({ target, body: blob, name: meta.name, index, total, meta: { size: meta.size, chunkSize: meta.chunkSize, identifier: meta.fingerprint }, signal });
|
|
3904
5931
|
}
|
|
3905
5932
|
};
|
|
3906
5933
|
}
|
|
3907
|
-
|
|
3908
|
-
|
|
3909
|
-
|
|
3910
|
-
if (option
|
|
3911
|
-
|
|
3912
|
-
if (option
|
|
5934
|
+
const CARRY = ["chunkSize", "concurrency", "retries", "retryDelay", "fingerprint", "completeOnUrl", "slice"];
|
|
5935
|
+
const isUploader = (value) => value instanceof SimpleUploader || value instanceof ChunkUploader;
|
|
5936
|
+
function toAdapter(option, label) {
|
|
5937
|
+
if (option === void 0 || option === null || option === "mock") return mockAdapter({});
|
|
5938
|
+
if (typeof option === "string") {
|
|
5939
|
+
if (!/^(https?:)?\/\//.test(option) && !option.startsWith("/")) {
|
|
5940
|
+
throw new Error(`[KEditor] 无法识别的${label}配置:${option}(接口地址请以 / 或 http(s):// 开头)`);
|
|
5941
|
+
}
|
|
5942
|
+
return httpAdapter({ url: option });
|
|
5943
|
+
}
|
|
5944
|
+
if (typeof option === "function") return simpleAdapter(option);
|
|
5945
|
+
if (typeof option === "object") {
|
|
5946
|
+
if (typeof option.upload === "function" || typeof option.put === "function") return option;
|
|
5947
|
+
if (option.type === "mock") return mockAdapter(option);
|
|
5948
|
+
return httpAdapter(option);
|
|
3913
5949
|
}
|
|
3914
|
-
|
|
5950
|
+
throw new Error(`[KEditor] 无法识别的${label}配置:${typeof option}`);
|
|
3915
5951
|
}
|
|
3916
|
-
|
|
3917
|
-
const out = {};
|
|
3918
|
-
|
|
5952
|
+
function carry(config, option) {
|
|
5953
|
+
const out = { ...config || {} };
|
|
5954
|
+
if (option && typeof option === "object") {
|
|
5955
|
+
for (const key of CARRY) if (option[key] !== void 0) out[key] = option[key];
|
|
5956
|
+
}
|
|
3919
5957
|
return out;
|
|
3920
|
-
}
|
|
5958
|
+
}
|
|
5959
|
+
function createSimpleUploader(option, config = {}) {
|
|
5960
|
+
if (isUploader(option)) return option;
|
|
5961
|
+
return new SimpleUploader(toAdapter(option, "普通上传"), carry(config, option));
|
|
5962
|
+
}
|
|
5963
|
+
function createChunkUploader(option, config = {}) {
|
|
5964
|
+
if (isUploader(option)) return option;
|
|
5965
|
+
return new ChunkUploader(toAdapter(option, "分片上传"), carry(config, option));
|
|
5966
|
+
}
|
|
5967
|
+
class UploadPipeline {
|
|
5968
|
+
constructor(normal, chunk, options = {}) {
|
|
5969
|
+
this.normal = normal || null;
|
|
5970
|
+
this.chunk = chunk || null;
|
|
5971
|
+
this.mode = ["auto", "normal", "chunk"].includes(options.mode) ? options.mode : "auto";
|
|
5972
|
+
this.chunkThreshold = Math.max(0, Number(options.chunkThreshold ?? 5 * 1024 * 1024) || 0);
|
|
5973
|
+
if (options.mode === "chunk" && !this.chunk) console.warn('[KEditor] upload.mode = "chunk" 但未配置 chunkUploader,已回退为普通上传');
|
|
5974
|
+
}
|
|
5975
|
+
/** 该文件走哪条链路:'normal' | 'chunk' */
|
|
5976
|
+
pick(file) {
|
|
5977
|
+
if (!this.chunk) return "normal";
|
|
5978
|
+
if (!this.normal) return "chunk";
|
|
5979
|
+
if (this.mode === "normal") return "normal";
|
|
5980
|
+
if (this.mode === "chunk") return "chunk";
|
|
5981
|
+
return ((file == null ? void 0 : file.size) || 0) >= this.chunkThreshold ? "chunk" : "normal";
|
|
5982
|
+
}
|
|
5983
|
+
uploaderFor(file) {
|
|
5984
|
+
return this.pick(file) === "chunk" ? this.chunk : this.normal;
|
|
5985
|
+
}
|
|
5986
|
+
async upload(file, handlers = {}) {
|
|
5987
|
+
const target = this.uploaderFor(file);
|
|
5988
|
+
if (!target) throw new Error("[KEditor] 未配置上传接口:请设置 uploader(普通上传)或 chunkUploader(分片上传)");
|
|
5989
|
+
const result = await target.upload(file, handlers);
|
|
5990
|
+
return { ...result, mode: target.mode };
|
|
5991
|
+
}
|
|
5992
|
+
destroy() {
|
|
5993
|
+
var _a, _b;
|
|
5994
|
+
(_a = this.normal) == null ? void 0 : _a.destroy();
|
|
5995
|
+
(_b = this.chunk) == null ? void 0 : _b.destroy();
|
|
5996
|
+
}
|
|
5997
|
+
}
|
|
5998
|
+
function createUploaders(options = {}) {
|
|
5999
|
+
const upload = options.upload || {};
|
|
6000
|
+
const normal = createSimpleUploader(options.uploader, upload);
|
|
6001
|
+
const chunk = options.chunkUploader ? createChunkUploader(options.chunkUploader, upload) : null;
|
|
6002
|
+
return { normal, chunk, pipeline: new UploadPipeline(normal, chunk, upload) };
|
|
6003
|
+
}
|
|
6004
|
+
function splitFiles(files) {
|
|
6005
|
+
const docs = [];
|
|
6006
|
+
const media = [];
|
|
6007
|
+
for (const file of files) (isMarkdownFile(file) ? docs : media).push(file);
|
|
6008
|
+
return { docs, media };
|
|
6009
|
+
}
|
|
6010
|
+
async function importDocs(editor, docs) {
|
|
6011
|
+
for (const doc of docs) await editor.importMarkdown(doc);
|
|
6012
|
+
return docs.length;
|
|
6013
|
+
}
|
|
3921
6014
|
function attachPaste(editor) {
|
|
3922
6015
|
editor.root.addEventListener("paste", async (event) => {
|
|
3923
6016
|
if (editor.readOnly || !editor.options.paste.enabled) return;
|
|
@@ -3926,9 +6019,12 @@ function attachPaste(editor) {
|
|
|
3926
6019
|
event.preventDefault();
|
|
3927
6020
|
const files = filesFromDataTransfer(dt);
|
|
3928
6021
|
if (files.length) {
|
|
6022
|
+
const { docs, media } = splitFiles(files);
|
|
6023
|
+
if (docs.length) await importDocs(editor, docs);
|
|
6024
|
+
if (!media.length) return;
|
|
3929
6025
|
if (editor.options.paste.uploadFiles) {
|
|
3930
|
-
await editor.media.addFiles(
|
|
3931
|
-
editor.toast.show(`已上传 ${
|
|
6026
|
+
await editor.media.addFiles(media);
|
|
6027
|
+
editor.toast.show(`已上传 ${media.length} 个文件`);
|
|
3932
6028
|
} else {
|
|
3933
6029
|
editor.toast.warn("当前配置不允许粘贴上传文件");
|
|
3934
6030
|
}
|
|
@@ -3999,8 +6095,10 @@ function attachDrop(editor) {
|
|
|
3999
6095
|
placeCaretAtPoint(editor, event);
|
|
4000
6096
|
const files = [...event.dataTransfer.files || []];
|
|
4001
6097
|
if (!files.length) return;
|
|
4002
|
-
|
|
4003
|
-
|
|
6098
|
+
const { docs, media } = splitFiles(files);
|
|
6099
|
+
if (docs.length) await importDocs(editor, docs);
|
|
6100
|
+
if (media.length && editor.options.paste.uploadFiles) {
|
|
6101
|
+
const count = await editor.media.addFiles(media);
|
|
4004
6102
|
if (count) editor.toast.show(`已上传 ${count} 个文件`);
|
|
4005
6103
|
}
|
|
4006
6104
|
});
|
|
@@ -4041,14 +6139,24 @@ async function localizeImages(editor, html) {
|
|
|
4041
6139
|
}
|
|
4042
6140
|
return doc.body.innerHTML.trim();
|
|
4043
6141
|
}
|
|
6142
|
+
function initialCodeLang(code) {
|
|
6143
|
+
const list = listLanguages(code.languages);
|
|
6144
|
+
const wanted = normalizeLang(code.defaultLanguage);
|
|
6145
|
+
return list.some((item) => item.value === wanted) ? wanted : list[0].value;
|
|
6146
|
+
}
|
|
4044
6147
|
const KB = 1024;
|
|
4045
6148
|
const MB = 1024 * KB;
|
|
4046
6149
|
const defaults = {
|
|
4047
6150
|
value: "",
|
|
4048
6151
|
placeholder: "开始撰写内容,支持拖拽 / 粘贴图片与视频…",
|
|
4049
|
-
height:
|
|
4050
|
-
// 编辑区可视高度(px
|
|
6152
|
+
height: 0,
|
|
6153
|
+
// 编辑区可视高度(px):默认 0 = 随内容自动撑开;填了才固定高度并内部滚动
|
|
4051
6154
|
minHeight: 320,
|
|
6155
|
+
// 内容区最小高度(px),自适应模式下也生效
|
|
6156
|
+
/** 代码块:可选语言列表、默认语言、是否语法高亮 */
|
|
6157
|
+
code: { languages: [], defaultLanguage: "plaintext", highlight: true },
|
|
6158
|
+
/** Markdown 导入:落点模式(replace 替换全文 | append 追加文末 | cursor 光标处)/ 文件体积上限 / 转换选项 */
|
|
6159
|
+
markdown: { insertMode: "replace", maxSize: 5 * MB, gfm: true, breaks: false, linkTarget: false, frontMatter: true },
|
|
4052
6160
|
primaryColor: "#07c160",
|
|
4053
6161
|
paperWidth: 677,
|
|
4054
6162
|
// 版心基准宽度:窄屏上限、宽屏最小宽度
|
|
@@ -4070,9 +6178,20 @@ const defaults = {
|
|
|
4070
6178
|
wordCount: true,
|
|
4071
6179
|
sanitize: true,
|
|
4072
6180
|
historyLimit: 60,
|
|
6181
|
+
/** 普通上传(整个文件一次请求):'mock' | 接口地址 | {url,…} | adapter | fn */
|
|
4073
6182
|
uploader: "mock",
|
|
4074
|
-
|
|
4075
|
-
|
|
6183
|
+
/** 分片上传(切片并发,接口返回 url 即成功):同上;null 表示不启用分片 */
|
|
6184
|
+
chunkUploader: "mock",
|
|
6185
|
+
upload: {
|
|
6186
|
+
/** 'auto' 按体积自动选链路 | 'normal' 只走普通上传 | 'chunk' 只走分片上传 */
|
|
6187
|
+
mode: "auto",
|
|
6188
|
+
/** auto 模式下达到该体积才走分片上传 */
|
|
6189
|
+
chunkThreshold: 5 * MB,
|
|
6190
|
+
chunkSize: MB,
|
|
6191
|
+
concurrency: 3,
|
|
6192
|
+
retries: 2,
|
|
6193
|
+
fingerprint: "fast"
|
|
6194
|
+
},
|
|
4076
6195
|
image: { compress: { maxWidth: 1440, quality: 0.85, minSize: 300 * KB } },
|
|
4077
6196
|
maxImageSize: 20 * MB,
|
|
4078
6197
|
maxVideoSize: 512 * MB,
|
|
@@ -4094,6 +6213,7 @@ class KEditor {
|
|
|
4094
6213
|
injectStyle();
|
|
4095
6214
|
this.options = mergeOptions(options);
|
|
4096
6215
|
this.id = `ke-${instanceSeq += 1}`;
|
|
6216
|
+
this.lastCodeLang = initialCodeLang(this.options.code);
|
|
4097
6217
|
this.el = resolveTarget(target, this.id);
|
|
4098
6218
|
this.el.__keditor__ = this;
|
|
4099
6219
|
const hostHTML = this.el.innerHTML;
|
|
@@ -4108,7 +6228,9 @@ class KEditor {
|
|
|
4108
6228
|
this.toast = new Toast();
|
|
4109
6229
|
this.popover = new Popover(this.el);
|
|
4110
6230
|
this.commands = new Commands(this);
|
|
4111
|
-
|
|
6231
|
+
const uploads = createUploaders(this.options);
|
|
6232
|
+
this.uploaders = { normal: uploads.normal, chunk: uploads.chunk };
|
|
6233
|
+
this.uploader = uploads.pipeline;
|
|
4112
6234
|
this.media = createMedia(this);
|
|
4113
6235
|
this.history = new History(this.root, { limit: this.options.historyLimit });
|
|
4114
6236
|
this.toolbar = new Toolbar(this, this.options.toolbar, this.options.customButtons);
|
|
@@ -4157,13 +6279,35 @@ class KEditor {
|
|
|
4157
6279
|
this.el.appendChild(this.mainEl);
|
|
4158
6280
|
if (!this.options.hideStatusbar) this.el.appendChild(this.statusEl);
|
|
4159
6281
|
this.el.appendChild(this.dropzoneEl);
|
|
4160
|
-
if (this.options.height) {
|
|
4161
|
-
this.scrollEl.style.height = `${this.options.height}px`;
|
|
4162
|
-
this.scrollEl.style.maxHeight = `${this.options.height}px`;
|
|
4163
|
-
}
|
|
4164
6282
|
this.paperEl.style.setProperty("--ke-min-height", `${this.options.minHeight}px`);
|
|
6283
|
+
this.applyHeight();
|
|
4165
6284
|
this.applyPaper();
|
|
4166
6285
|
}
|
|
6286
|
+
/**
|
|
6287
|
+
* 内容区高度:height 未配置(0)时随内容自动撑开,整页滚动;
|
|
6288
|
+
* 配置了 height 才固定高度,内容超出时在编辑区内部滚动
|
|
6289
|
+
*/
|
|
6290
|
+
applyHeight() {
|
|
6291
|
+
const height = normalizeHeight(this.options.height);
|
|
6292
|
+
if (height > 0) {
|
|
6293
|
+
this.scrollEl.style.height = `${height}px`;
|
|
6294
|
+
this.scrollEl.style.maxHeight = `${height}px`;
|
|
6295
|
+
} else {
|
|
6296
|
+
this.scrollEl.style.height = "";
|
|
6297
|
+
this.scrollEl.style.maxHeight = "";
|
|
6298
|
+
}
|
|
6299
|
+
this.el.classList.toggle("ke-is-auto", height === 0);
|
|
6300
|
+
return height;
|
|
6301
|
+
}
|
|
6302
|
+
/** 运行时切换内容区高度:传 px 固定,传 0 / 'auto' 恢复自适应 */
|
|
6303
|
+
setHeight(value) {
|
|
6304
|
+
this.options.height = normalizeHeight(value);
|
|
6305
|
+
return this.applyHeight();
|
|
6306
|
+
}
|
|
6307
|
+
/** 当前内容区高度配置:0 表示自适应 */
|
|
6308
|
+
heightOptions() {
|
|
6309
|
+
return { height: normalizeHeight(this.options.height), auto: normalizeHeight(this.options.height) === 0 };
|
|
6310
|
+
}
|
|
4167
6311
|
/** 版心尺寸:宽屏下默认让版心随容器生长,两侧只保留固定留白 */
|
|
4168
6312
|
applyPaper() {
|
|
4169
6313
|
const { paperWidth, paperMode, paperGap, paperMaxWidth } = this.options;
|
|
@@ -4192,13 +6336,21 @@ class KEditor {
|
|
|
4192
6336
|
/* ------------------------------ 事件 ------------------------------ */
|
|
4193
6337
|
bindEvents() {
|
|
4194
6338
|
const debouncedChange = debounce(() => this.emitChange(), 160);
|
|
4195
|
-
this.bind(this.root, "input", () => {
|
|
6339
|
+
this.bind(this.root, "input", (event) => {
|
|
4196
6340
|
this.history.snapshot();
|
|
4197
6341
|
this.refreshStatus();
|
|
4198
6342
|
this.togglePlaceholder();
|
|
6343
|
+
this.queueCodeHighlight(event);
|
|
4199
6344
|
debouncedChange();
|
|
4200
6345
|
this.enforceMaxLength();
|
|
4201
6346
|
});
|
|
6347
|
+
this.bind(this.root, "compositionstart", () => {
|
|
6348
|
+
this.composing = true;
|
|
6349
|
+
});
|
|
6350
|
+
this.bind(this.root, "compositionend", (event) => {
|
|
6351
|
+
this.composing = false;
|
|
6352
|
+
this.queueCodeHighlight(event);
|
|
6353
|
+
});
|
|
4202
6354
|
this.bind(this.root, "keydown", (event) => this.handleKeydown(event));
|
|
4203
6355
|
this.bind(this.root, "blur", () => {
|
|
4204
6356
|
this.history.flush();
|
|
@@ -4331,7 +6483,8 @@ class KEditor {
|
|
|
4331
6483
|
source: this.sourceMode,
|
|
4332
6484
|
preview: this.previewMode,
|
|
4333
6485
|
fullscreen: this.fullscreen,
|
|
4334
|
-
readOnly: this.readOnly
|
|
6486
|
+
readOnly: this.readOnly,
|
|
6487
|
+
inCode: !!codeBlockAt(this.root)
|
|
4335
6488
|
};
|
|
4336
6489
|
}
|
|
4337
6490
|
queryState(command) {
|
|
@@ -4383,8 +6536,8 @@ class KEditor {
|
|
|
4383
6536
|
/* ------------------------------ 内容 API ------------------------------ */
|
|
4384
6537
|
getHTML({ clean = true } = {}) {
|
|
4385
6538
|
const html = this.root.innerHTML;
|
|
4386
|
-
if (
|
|
4387
|
-
return exportHtml(html);
|
|
6539
|
+
if (clean === false) return html;
|
|
6540
|
+
return exportHtml(html, { keepHighlight: clean === "preview" });
|
|
4388
6541
|
}
|
|
4389
6542
|
getText() {
|
|
4390
6543
|
return toPlainText(this.root.innerHTML);
|
|
@@ -4395,6 +6548,7 @@ class KEditor {
|
|
|
4395
6548
|
setContent(html, { sanitize = this.options.sanitize, silent = false } = {}) {
|
|
4396
6549
|
const value = sanitizeHtml(html || "<p><br></p>", { allowEmpty: true });
|
|
4397
6550
|
this.root.innerHTML = value || "<p><br></p>";
|
|
6551
|
+
this.highlightCode();
|
|
4398
6552
|
this.afterEdit({ silent });
|
|
4399
6553
|
if (!silent) this.history.snapshot(true);
|
|
4400
6554
|
this.togglePlaceholder();
|
|
@@ -4496,6 +6650,111 @@ class KEditor {
|
|
|
4496
6650
|
this.refresh();
|
|
4497
6651
|
return this;
|
|
4498
6652
|
}
|
|
6653
|
+
/* ------------------------------ 代码块 ------------------------------ */
|
|
6654
|
+
/** 可选语言清单(可用 options.code.languages 裁剪) */
|
|
6655
|
+
codeLanguages() {
|
|
6656
|
+
return listLanguages(this.options.code.languages);
|
|
6657
|
+
}
|
|
6658
|
+
/** 高亮正文中所有代码块(内容整体替换后调用) */
|
|
6659
|
+
highlightCode() {
|
|
6660
|
+
return highlightCodeBlocks(this.root, { highlight: this.options.code.highlight !== false });
|
|
6661
|
+
}
|
|
6662
|
+
/** 插入代码块:code 为源码,lang 缺省用 code.defaultLanguage */
|
|
6663
|
+
insertCode(code = "", lang) {
|
|
6664
|
+
return this.commands.insertCodeBlock(code, lang);
|
|
6665
|
+
}
|
|
6666
|
+
/** 切换代码块语言并重新高亮;不传目标时取光标所在代码块,返回 null 表示不在代码块中 */
|
|
6667
|
+
setCodeLanguage(lang, target) {
|
|
6668
|
+
return this.commands.setCodeLanguage(lang, target);
|
|
6669
|
+
}
|
|
6670
|
+
/** 光标所在代码块的语言;不在代码块中返回空串 */
|
|
6671
|
+
getCodeLanguage() {
|
|
6672
|
+
return this.commands.currentCodeLang();
|
|
6673
|
+
}
|
|
6674
|
+
/** 在代码块内输入时重新高亮(保持块内光标);输入法组字期间跳过 */
|
|
6675
|
+
queueCodeHighlight(event) {
|
|
6676
|
+
if ((event == null ? void 0 : event.isComposing) || this.composing) return;
|
|
6677
|
+
const block = codeBlockAt(this.root);
|
|
6678
|
+
if (!block) return;
|
|
6679
|
+
clearTimeout(this.codeTimer);
|
|
6680
|
+
this.codeTimer = setTimeout(() => {
|
|
6681
|
+
this.codeTimer = null;
|
|
6682
|
+
if (!this.destroyed) refreshCodeBlock(block, { caret: true });
|
|
6683
|
+
}, 140);
|
|
6684
|
+
}
|
|
6685
|
+
/* ------------------------------ 导入 Markdown ------------------------------ */
|
|
6686
|
+
/** 落点模式:replace 替换全文(默认)| append 追加到文末 | cursor 插入到光标处 */
|
|
6687
|
+
markdownOptions() {
|
|
6688
|
+
const { insertMode, maxSize } = this.options.markdown;
|
|
6689
|
+
return { insertMode: normalizeInsertMode(insertMode), maxSize, auto: insertMode === "replace" };
|
|
6690
|
+
}
|
|
6691
|
+
/**
|
|
6692
|
+
* 导入 Markdown 并转为 HTML:source 可为字符串或 File/Blob(.md / .txt)
|
|
6693
|
+
* 返回 { ok, html, summary, mode, chars, name };失败时 ok=false
|
|
6694
|
+
*/
|
|
6695
|
+
async importMarkdown(source, { mode = this.options.markdown.insertMode, silent = false } = {}) {
|
|
6696
|
+
if (this.readOnly) {
|
|
6697
|
+
this.toast.warn("只读模式不能导入内容");
|
|
6698
|
+
return { ok: false, reason: "readonly" };
|
|
6699
|
+
}
|
|
6700
|
+
const place = normalizeInsertMode(mode);
|
|
6701
|
+
let text = "";
|
|
6702
|
+
let name = "";
|
|
6703
|
+
try {
|
|
6704
|
+
if (typeof source === "string") {
|
|
6705
|
+
text = source;
|
|
6706
|
+
} else if (source && typeof source.arrayBuffer === "function") {
|
|
6707
|
+
name = source.name || "";
|
|
6708
|
+
const limit = this.options.markdown.maxSize;
|
|
6709
|
+
if (limit && source.size > limit) throw new Error(`${name || "文件"} 超出大小限制(${formatSize(limit)})`);
|
|
6710
|
+
text = await readMarkdownFile(source);
|
|
6711
|
+
} else if (source && typeof source.content === "string") {
|
|
6712
|
+
text = source.content;
|
|
6713
|
+
name = source.name || "";
|
|
6714
|
+
} else {
|
|
6715
|
+
throw new Error("导入内容必须是 Markdown 文本或文件");
|
|
6716
|
+
}
|
|
6717
|
+
const html = markdownToHtml(text, this.options.markdown);
|
|
6718
|
+
if (!html.trim()) throw new Error("没有解析到可用内容");
|
|
6719
|
+
if (place === "replace") this.setContent(html);
|
|
6720
|
+
else {
|
|
6721
|
+
if (place === "append") this.moveCaretToEnd();
|
|
6722
|
+
this.commands.insertHTML(html);
|
|
6723
|
+
this.highlightCode();
|
|
6724
|
+
}
|
|
6725
|
+
this.focus();
|
|
6726
|
+
this.history.snapshot(true);
|
|
6727
|
+
const summary = markdownSummary(html);
|
|
6728
|
+
if (!silent) this.toast.show(`已导入${name ? ` ${name}` : " Markdown"}(${summary.paragraphs + summary.headings} 个段落)`);
|
|
6729
|
+
this.emit("markdownimport", { mode: place, name, summary, chars: text.length });
|
|
6730
|
+
return { ok: true, html, summary, mode: place, chars: text.length, name };
|
|
6731
|
+
} catch (error) {
|
|
6732
|
+
this.reportError("markdown", error);
|
|
6733
|
+
return { ok: false, reason: "error", error, name };
|
|
6734
|
+
}
|
|
6735
|
+
}
|
|
6736
|
+
/** 导入并替换全文 */
|
|
6737
|
+
setMarkdown(source, options = {}) {
|
|
6738
|
+
return this.importMarkdown(source, { mode: "replace", ...options });
|
|
6739
|
+
}
|
|
6740
|
+
/** 导入并插入到光标处 */
|
|
6741
|
+
insertMarkdown(source, options = {}) {
|
|
6742
|
+
return this.importMarkdown(source, { mode: "cursor", ...options });
|
|
6743
|
+
}
|
|
6744
|
+
/** 导入并追加到文末 */
|
|
6745
|
+
appendMarkdown(source, options = {}) {
|
|
6746
|
+
return this.importMarkdown(source, { mode: "append", ...options });
|
|
6747
|
+
}
|
|
6748
|
+
/** 光标 / 选区移到正文末尾(追加导入用) */
|
|
6749
|
+
moveCaretToEnd() {
|
|
6750
|
+
const range = document.createRange();
|
|
6751
|
+
range.selectNodeContents(this.root);
|
|
6752
|
+
range.collapse(false);
|
|
6753
|
+
const sel = window.getSelection();
|
|
6754
|
+
sel.removeAllRanges();
|
|
6755
|
+
sel.addRange(range);
|
|
6756
|
+
return this;
|
|
6757
|
+
}
|
|
4499
6758
|
/* ------------------------------ 媒体快捷入口 ------------------------------ */
|
|
4500
6759
|
/** 上传任意文件(自动识别图片/视频),等价于点击工具栏上传 */
|
|
4501
6760
|
upload(file, kind = this.media.kindOf(file)) {
|
|
@@ -4584,7 +6843,7 @@ class KEditor {
|
|
|
4584
6843
|
}
|
|
4585
6844
|
openPreview() {
|
|
4586
6845
|
this.previewMode = true;
|
|
4587
|
-
this.previewPanel.show(previewHtml(this.getHTML()));
|
|
6846
|
+
this.previewPanel.show(previewHtml(this.getHTML({ clean: "preview" })));
|
|
4588
6847
|
this.refresh();
|
|
4589
6848
|
}
|
|
4590
6849
|
closePreview() {
|
|
@@ -4639,9 +6898,12 @@ class KEditor {
|
|
|
4639
6898
|
return this.el;
|
|
4640
6899
|
}
|
|
4641
6900
|
destroy() {
|
|
6901
|
+
var _a;
|
|
4642
6902
|
if (this.destroyed) return;
|
|
4643
6903
|
this.destroyed = true;
|
|
4644
6904
|
this.media.destroy();
|
|
6905
|
+
(_a = this.uploader) == null ? void 0 : _a.destroy();
|
|
6906
|
+
clearTimeout(this.codeTimer);
|
|
4645
6907
|
this.history.destroy();
|
|
4646
6908
|
this.popover.destroy();
|
|
4647
6909
|
this.source.destroy();
|
|
@@ -4702,11 +6964,26 @@ function resolveTarget(target, id) {
|
|
|
4702
6964
|
if ((target == null ? void 0 : target.$el) instanceof HTMLElement) return target.$el;
|
|
4703
6965
|
throw new Error(`[KEditor] 无效的挂载目标(${typeof target})`);
|
|
4704
6966
|
}
|
|
6967
|
+
function normalizeHeight(value) {
|
|
6968
|
+
if (value === "" || value === null || value === void 0 || value === "auto") return 0;
|
|
6969
|
+
const num = Number(value);
|
|
6970
|
+
if (!Number.isFinite(num) || num <= 0) return 0;
|
|
6971
|
+
return clamp$1(Math.round(num), 0, 4e3);
|
|
6972
|
+
}
|
|
4705
6973
|
function mergeOptions(options) {
|
|
6974
|
+
var _a;
|
|
4706
6975
|
const out = { ...defaults, ...options };
|
|
4707
6976
|
out.image = { ...defaults.image, ...options.image || {} };
|
|
4708
6977
|
out.paste = { ...defaults.paste, ...options.paste || {} };
|
|
4709
6978
|
out.upload = { ...defaults.upload, ...options.upload || {} };
|
|
6979
|
+
const explicitNormal = options.uploader !== void 0;
|
|
6980
|
+
const explicitChunk = options.chunkUploader !== void 0;
|
|
6981
|
+
if (explicitNormal && !explicitChunk) out.chunkUploader = null;
|
|
6982
|
+
if (!explicitNormal && explicitChunk && ((_a = options.upload) == null ? void 0 : _a.mode) === void 0) out.upload.mode = "chunk";
|
|
6983
|
+
out.code = { ...defaults.code, ...options.code || {} };
|
|
6984
|
+
out.markdown = { ...defaults.markdown, ...options.markdown || {} };
|
|
6985
|
+
out.markdown.insertMode = normalizeInsertMode(out.markdown.insertMode);
|
|
6986
|
+
out.markdown.maxSize = Math.max(0, Number(out.markdown.maxSize) || 0);
|
|
4710
6987
|
out.customButtons = normalizeCustomButtons(options.customButtons);
|
|
4711
6988
|
if (Array.isArray(options.toolbar)) out.toolbar = options.toolbar;
|
|
4712
6989
|
if (options.toolbar === false) out.toolbar = [];
|
|
@@ -4714,7 +6991,7 @@ function mergeOptions(options) {
|
|
|
4714
6991
|
if (out.customButtons.length && options.toolbar !== false) {
|
|
4715
6992
|
out.toolbar = placeCustomNames(out.toolbar, out.customButtons);
|
|
4716
6993
|
}
|
|
4717
|
-
out.height =
|
|
6994
|
+
out.height = normalizeHeight(out.height);
|
|
4718
6995
|
out.paperWidth = clamp$1(Number(out.paperWidth) || defaults.paperWidth, 200, 8e3);
|
|
4719
6996
|
out.paperMode = out.paperMode === "fixed" ? "fixed" : "fluid";
|
|
4720
6997
|
out.paperGap = Number.isFinite(Number(out.paperGap)) ? clamp$1(Number(out.paperGap), 0, 600) : defaults.paperGap;
|
|
@@ -4829,7 +7106,7 @@ function countWords(text) {
|
|
|
4829
7106
|
const latin = (text.match(/[a-zA-Z0-9'’-]+/g) || []).length;
|
|
4830
7107
|
return cjk + latin;
|
|
4831
7108
|
}
|
|
4832
|
-
function exportHtml(html) {
|
|
7109
|
+
function exportHtml(html, { keepHighlight = false } = {}) {
|
|
4833
7110
|
const doc = new DOMParser().parseFromString(`<div>${html}</div>`, "text/html");
|
|
4834
7111
|
const root = doc.body.firstChild;
|
|
4835
7112
|
root.querySelectorAll("[contenteditable]").forEach((n) => n.removeAttribute("contenteditable"));
|
|
@@ -4838,6 +7115,7 @@ function exportHtml(html) {
|
|
|
4838
7115
|
root.querySelectorAll("[data-ke-marker]").forEach((n) => n.removeAttribute("data-ke-marker"));
|
|
4839
7116
|
root.querySelectorAll("[data-placeholder]").forEach((n) => n.removeAttribute("data-placeholder"));
|
|
4840
7117
|
root.querySelectorAll(".ke-is-selected-media").forEach((n) => n.classList.remove("ke-is-selected-media"));
|
|
7118
|
+
if (!keepHighlight) stripHighlight(root);
|
|
4841
7119
|
root.querySelectorAll('[data-k-state="uploading"], [data-k-state="error"]').forEach((n) => n.remove());
|
|
4842
7120
|
return root.innerHTML.trim();
|
|
4843
7121
|
}
|
|
@@ -4850,7 +7128,7 @@ function previewHtml(html) {
|
|
|
4850
7128
|
});
|
|
4851
7129
|
return root.innerHTML;
|
|
4852
7130
|
}
|
|
4853
|
-
const version = "1.0.
|
|
7131
|
+
const version = "1.0.8";
|
|
4854
7132
|
function create(target, options = {}) {
|
|
4855
7133
|
return new KEditor(target, options);
|
|
4856
7134
|
}
|
|
@@ -4864,23 +7142,38 @@ export {
|
|
|
4864
7142
|
ChunkUploader,
|
|
4865
7143
|
DEFAULT_TOOLBAR,
|
|
4866
7144
|
KEditor,
|
|
7145
|
+
LANGUAGES,
|
|
7146
|
+
MARKDOWN_ACCEPT,
|
|
7147
|
+
SimpleUploader,
|
|
7148
|
+
UploadPipeline,
|
|
4867
7149
|
cleanWordHtml,
|
|
4868
7150
|
create,
|
|
4869
|
-
|
|
7151
|
+
createChunkUploader,
|
|
7152
|
+
createSimpleUploader,
|
|
4870
7153
|
KEditor as default,
|
|
4871
7154
|
defaults,
|
|
4872
7155
|
escapeHtml,
|
|
4873
7156
|
exportHtml,
|
|
4874
7157
|
fastFingerprint,
|
|
4875
7158
|
formatHtml,
|
|
7159
|
+
highlightCode,
|
|
4876
7160
|
httpAdapter,
|
|
7161
|
+
isCodeBlock,
|
|
7162
|
+
isMarkdownFile,
|
|
4877
7163
|
isSafeUrl,
|
|
7164
|
+
languageLabel,
|
|
7165
|
+
listLanguages,
|
|
7166
|
+
markdownSummary,
|
|
7167
|
+
markdownToHtml,
|
|
4878
7168
|
maybeCompress,
|
|
4879
7169
|
mockAdapter,
|
|
4880
7170
|
mount,
|
|
4881
7171
|
normalizeCustomButtons,
|
|
7172
|
+
normalizeInsertMode,
|
|
4882
7173
|
normalizeItems,
|
|
7174
|
+
normalizeLang,
|
|
4883
7175
|
normalizePosition,
|
|
7176
|
+
readMarkdownFile,
|
|
4884
7177
|
replace,
|
|
4885
7178
|
sanitizeHtml,
|
|
4886
7179
|
simpleAdapter,
|