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