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