kyle-editor 1.0.7 → 1.0.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +232 -22
- package/dist/keditor-vue.cjs +3 -2
- package/dist/keditor-vue.es.js +3 -2
- package/dist/keditor-vue.umd.js +3 -2
- package/dist/keditor.cjs +2814 -521
- package/dist/keditor.es.js +2814 -521
- package/dist/keditor.umd.js +2812 -519
- package/dist/keditor.umd.min.js +109 -6
- package/docs/api.md +458 -0
- package/docs/integration.md +357 -0
- package/docs/upload-adapter.md +295 -0
- package/package.json +3 -2
- package/types/index.d.ts +273 -23
- package/types/vue.d.ts +2 -2
package/dist/keditor.umd.min.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
(function(
|
|
1
|
+
(function(y,he){typeof exports=="object"&&typeof module<"u"?he(exports):typeof define=="function"&&define.amd?define(["exports"],he):(y=typeof globalThis<"u"?globalThis:y||self,he(y.KEditor={}))})(this,function(y){"use strict";const he=`
|
|
2
2
|
.ke, .ke * { box-sizing: border-box; }
|
|
3
3
|
.ke {
|
|
4
4
|
--ke-primary: #07c160;
|
|
@@ -26,6 +26,9 @@
|
|
|
26
26
|
}
|
|
27
27
|
.ke[hidden] { display: none; }
|
|
28
28
|
.ke-is-fullscreen { position: fixed; inset: 0; z-index: 9998; border-radius: 0; }
|
|
29
|
+
/* 自适应高度(未配 height):整页滚动;overflow:clip 不建立滚动容器,
|
|
30
|
+
工具栏的 sticky 才能相对视口生效(旧浏览器忽略 clip,退回 hidden 行为) */
|
|
31
|
+
.ke.ke-is-auto { overflow: clip; }
|
|
29
32
|
|
|
30
33
|
/* ---------------- Toolbar ---------------- */
|
|
31
34
|
.ke-tb {
|
|
@@ -209,6 +212,56 @@
|
|
|
209
212
|
.ke-panel-icon + .ke-panel-note { margin-left: 8px; }
|
|
210
213
|
|
|
211
214
|
.ke-panel-select .ke-sel-search { margin-bottom: 8px; }
|
|
215
|
+
.ke-code-panel .ke-sel-search { margin-bottom: 8px; }
|
|
216
|
+
.ke-code-list { display: flex; flex-direction: column; max-height: 252px; overflow-y: auto; overscroll-behavior: contain; margin: 0 -4px; padding: 0 4px; }
|
|
217
|
+
.ke-code-panel .ke-panel-hint { margin-top: 10px; }
|
|
218
|
+
|
|
219
|
+
/* ---------------- Markdown 导入面板 ---------------- */
|
|
220
|
+
/* 固定宽度:预览里的表格 / 长链接不再把弹层撑宽 */
|
|
221
|
+
.ke-md-panel {
|
|
222
|
+
width: 372px; max-width: calc(100vw - 24px);
|
|
223
|
+
display: flex; flex-direction: column; padding-bottom: 0;
|
|
224
|
+
max-height: var(--ke-pop-max, 560px);
|
|
225
|
+
}
|
|
226
|
+
.ke-md-panel .ke-panel-head, .ke-md-panel .ke-tabs { flex: none; }
|
|
227
|
+
.ke-md-panel .ke-tabs { margin-bottom: 0; }
|
|
228
|
+
/* 中间区滚动、底部按钮常驻:窗口再矮也能点到「导入到正文」 */
|
|
229
|
+
.ke-md-body { flex: 1 1 auto; min-height: 0; overflow-y: auto; overscroll-behavior: contain; margin: 0 -14px; padding: 12px 14px 0; }
|
|
230
|
+
.ke-md-panel .ke-panel-foot { flex: none; margin: 10px 0 12px; }
|
|
231
|
+
.ke-md-text {
|
|
232
|
+
width: 100%; min-height: 118px; max-height: 190px; padding: 10px 11px; border: 1px solid var(--ke-line);
|
|
233
|
+
border-radius: 8px; background: #fbfcfd; color: #1f2329; font-size: 12.5px; line-height: 1.7; resize: vertical;
|
|
234
|
+
font-family: 'SFMono-Regular', Consolas, Menlo, Monaco, monospace; outline: none;
|
|
235
|
+
}
|
|
236
|
+
.ke-md-text:focus { border-color: var(--ke-primary); background: #fff; }
|
|
237
|
+
.ke-md-file { display: flex; align-items: center; gap: 8px; margin-top: 8px; font-size: 12px; color: var(--ke-muted); }
|
|
238
|
+
.ke-md-file b { flex: 1 1 auto; min-width: 0; color: #1f2329; font-weight: 600; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
|
239
|
+
.ke-md-file > span { flex: none; }
|
|
240
|
+
.ke-drop-title, .ke-drop-sub { overflow-wrap: anywhere; }
|
|
241
|
+
.ke-md-file[hidden] { display: none; }
|
|
242
|
+
.ke-md-error { color: #e53e3e; }
|
|
243
|
+
.ke-md-modes { display: flex; gap: 6px; }
|
|
244
|
+
.ke-md-mode { flex: 1; height: 28px; border: 1px solid var(--ke-line); border-radius: 7px; background: #fff; color: #4b5158; font-size: 12px; cursor: pointer; }
|
|
245
|
+
.ke-md-mode:hover { border-color: var(--ke-primary); color: var(--ke-primary); }
|
|
246
|
+
.ke-md-mode.ke-is-active { border-color: var(--ke-primary); background: var(--ke-primary-weak); color: var(--ke-primary); font-weight: 600; }
|
|
247
|
+
/* 预览复用正文样式(ke-content),只是尺寸更紧凑 */
|
|
248
|
+
.ke-md-preview {
|
|
249
|
+
max-height: 216px; overflow: auto; overscroll-behavior: contain;
|
|
250
|
+
padding: 10px 12px; border: 1px solid var(--ke-line-weak); border-radius: 8px; background: #fff;
|
|
251
|
+
font-size: 14px; line-height: 1.7; overflow-wrap: anywhere;
|
|
252
|
+
}
|
|
253
|
+
.ke-md-preview > *:last-child { margin-bottom: 0; }
|
|
254
|
+
.ke-md-preview h1, .ke-md-preview h2, .ke-md-preview h3, .ke-md-preview h4 { margin: 12px 0 8px; font-size: 16px; }
|
|
255
|
+
.ke-md-preview p { margin: 0 0 8px; }
|
|
256
|
+
.ke-md-preview ul, .ke-md-preview ol { margin: 0 0 8px; padding-left: 20px; }
|
|
257
|
+
.ke-md-preview blockquote { margin: 0 0 8px; padding: 1px 12px; }
|
|
258
|
+
.ke-md-preview pre { margin: 0 0 8px; padding: 9px 11px; font-size: 12px; }
|
|
259
|
+
.ke-md-preview table { font-size: 13px; }
|
|
260
|
+
.ke-md-preview th, .ke-md-preview td { padding: 4px 7px; }
|
|
261
|
+
.ke-md-empty { color: #b8bec7; font-size: 12.5px; }
|
|
262
|
+
.ke-md-stats { display: flex; flex-wrap: wrap; gap: 3px 10px; margin-top: 8px; font-size: 11.5px; color: #a2a8b3; }
|
|
263
|
+
.ke-md-stat b { color: #4b5158; font-weight: 600; }
|
|
264
|
+
.ke-md-panel .ke-panel-hint { margin-top: 0; }
|
|
212
265
|
.ke-sel-body { max-height: 268px; overflow-y: auto; overscroll-behavior: contain; margin: 0 -4px; padding: 0 4px; }
|
|
213
266
|
.ke-sel-row {
|
|
214
267
|
display: flex; align-items: center; gap: 8px; width: 100%;
|
|
@@ -310,10 +363,36 @@
|
|
|
310
363
|
.ke-content hr { border: 0; border-top: 1px solid var(--ke-line); margin: 24px 0; }
|
|
311
364
|
.ke-content code { background: #f2f3f5; border-radius: 4px; padding: 2px 6px; font-size: 14px; font-family: 'SFMono-Regular', Consolas, Menlo, monospace; color: #c7254e; }
|
|
312
365
|
.ke-content pre {
|
|
366
|
+
position: relative;
|
|
313
367
|
background: #282c34; color: #e6e6e6; padding: 14px 16px; border-radius: 8px; overflow-x: auto;
|
|
314
368
|
font-size: 13px; line-height: 1.7; margin: 0 0 16px; font-family: 'SFMono-Regular', Consolas, Menlo, monospace;
|
|
315
369
|
}
|
|
316
370
|
.ke-content pre code { background: none; color: inherit; padding: 0; font-size: inherit; }
|
|
371
|
+
/* 右上角语言角标:纯 CSS(::before)不进入正文 DOM,导出到公众号时自然消失 */
|
|
372
|
+
.ke-content pre[data-k-lang]:not([data-k-lang='plaintext'])::before {
|
|
373
|
+
content: attr(data-k-lang); position: absolute; top: 6px; right: 8px;
|
|
374
|
+
padding: 1px 6px; border-radius: 4px; background: rgba(255, 255, 255, .09); color: #8b93a1;
|
|
375
|
+
font-size: 10.5px; letter-spacing: .04em; text-transform: uppercase; pointer-events: none; user-select: none;
|
|
376
|
+
}
|
|
377
|
+
/* 代码高亮 token(One Dark 配色,与深色底一致) */
|
|
378
|
+
.ke-content .ke-tok-com { color: #7f848e; font-style: italic; }
|
|
379
|
+
.ke-content .ke-tok-str { color: #98c379; }
|
|
380
|
+
.ke-content .ke-tok-num { color: #d19a66; }
|
|
381
|
+
.ke-content .ke-tok-kw { color: #c678dd; }
|
|
382
|
+
.ke-content .ke-tok-typ { color: #e5c07b; }
|
|
383
|
+
.ke-content .ke-tok-fn { color: #61afef; }
|
|
384
|
+
.ke-content .ke-tok-var { color: #e06c75; }
|
|
385
|
+
.ke-content .ke-tok-op { color: #56b6c2; }
|
|
386
|
+
.ke-content .ke-tok-punc { color: #abb2bf; }
|
|
387
|
+
.ke-content .ke-tok-tag { color: #e06c75; }
|
|
388
|
+
.ke-content .ke-tok-attr { color: #d19a66; }
|
|
389
|
+
.ke-content .ke-tok-sel { color: #e06c75; }
|
|
390
|
+
.ke-content .ke-tok-prop { color: #61afef; }
|
|
391
|
+
.ke-content .ke-tok-key { color: #e06c75; }
|
|
392
|
+
.ke-content .ke-tok-bool { color: #d19a66; }
|
|
393
|
+
.ke-content .ke-tok-meta { color: #c678dd; }
|
|
394
|
+
.ke-content .ke-tok-ins { color: #98c379; }
|
|
395
|
+
.ke-content .ke-tok-del { color: #e06c75; text-decoration: line-through; }
|
|
317
396
|
.ke-content img, .ke-content video { max-width: 100%; height: auto; display: block; }
|
|
318
397
|
.ke-content figure { margin: 0 0 16px; }
|
|
319
398
|
.ke-content figcaption { font-size: 13px; color: var(--ke-muted); text-align: center; margin-top: 6px; }
|
|
@@ -474,10 +553,34 @@
|
|
|
474
553
|
@media (prefers-reduced-motion: reduce) {
|
|
475
554
|
.ke * { animation-duration: .01ms !important; transition-duration: .01ms !important; }
|
|
476
555
|
}
|
|
477
|
-
`;let ve=!1;function it(){if(ve||typeof document>"u")return;const o=document.createElement("style");o.setAttribute("data-keditor-style",""),o.textContent=D,document.head.appendChild(o),ve=!0}const ie=(o="k")=>`${o}${Date.now().toString(36)}${Math.random().toString(36).slice(2,7)}`;function ot(o,e=300){let t=null;const i=(...n)=>{clearTimeout(t),t=setTimeout(()=>o(...n),e)};return i.cancel=()=>clearTimeout(t),i.flush=(...n)=>{clearTimeout(t),o(...n)},i}const I=(o,e,t)=>Math.min(Math.max(o,e),t);function R(o){if(!o&&o!==0)return"-";const e=["B","KB","MB","GB"];let t=0,i=o;for(;i>=1024&&t<e.length-1;)i/=1024,t+=1;return`${i.toFixed(i>=10||t===0?0:1)}${e[t]}`}function l(o,e={},t=[]){let i="div",n="";const r=String(o).split(".");i=r[0]||"div",n=r.slice(1).join(" ");const s=document.createElement(i);n&&(s.className=n);for(const[c,d]of Object.entries(e||{}))d==null||d===!1||(c==="class"?s.className=`${s.className} ${d}`.trim():c==="style"&&typeof d=="object"?Object.assign(s.style,d):c==="html"?s.innerHTML=d:c==="text"?s.textContent=d:c==="dataset"?Object.assign(s.dataset,d):c.startsWith("on")&&typeof d=="function"?s.addEventListener(c.slice(2).toLowerCase(),d):s.setAttribute(c,d===!0?"":String(d)));const a=Array.isArray(t)?t:[t];for(const c of a)c==null||c===!1||s.appendChild(typeof c=="string"||typeof c=="number"?document.createTextNode(String(c)):c);return s}function oe(o){if(!o)return"left";const e=o.style.marginLeft,t=o.style.marginRight;return e==="auto"&&t==="auto"?"center":e==="auto"?"right":"left"}function ne(o,e){o&&(o.style.maxWidth="100%",e==="center"?(o.style.marginLeft="auto",o.style.marginRight="auto"):e==="right"?(o.style.marginLeft="auto",o.style.marginRight="0"):(o.style.marginLeft="0",o.style.marginRight="auto"))}const T=o=>`<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="${o}"/></svg>`,nt={undo:'<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="M9 14 4 9l5-5"/><path d="M4 9h10a5 5 0 0 1 0 10h-3"/></svg>',redo:'<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="m15 14 5-5-5-5"/><path d="M20 9H10a5 5 0 0 0 0 10h3"/></svg>',bold:'<svg class="ke-ico" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M7 5h6.5a3.5 3.5 0 0 1 0 7H7zM7 12h7.5a3.5 3.5 0 0 1 0 7H7z"/></svg>',italic:'<svg class="ke-ico" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"><path d="M15 5h-5M14 19H9M14.5 5 10 19"/></svg>',underline:'<svg class="ke-ico" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"><path d="M7 4v8a5 5 0 0 0 10 0V4M5 20h14"/></svg>',strike:'<svg class="ke-ico" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"><path d="M4 12h16M16.5 7A4.5 4.5 0 0 0 12 5c-2.2 0-3.6 1-4.2 2.4M7.5 17A4.5 4.5 0 0 0 12 19c2.3 0 3.9-1.1 4.4-2.8"/></svg>',foreColor:'<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="M5 17 9.5 5 14 17M6.8 13h5.9"/><rect x="4" y="19.5" width="11" height="2.2" rx="1" fill="currentColor" stroke="none"/></svg>',backColor:'<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 16l7.5-7.5a2 2 0 0 1 2.8 0l3.2 3.2a2 2 0 0 1 0 2.8L13 20z" /><path d="M10 8.5 15.5 14"/></svg>',alignLeft:T("M4 6h16M4 12h10M4 18h13"),alignCenter:T("M4 6h16M7 12h10M5.5 18h13"),alignRight:T("M4 6h16M10 12h10M7 18h13"),alignJustify:T("M4 6h16M4 12h16M4 18h16"),ul:'<svg class="ke-ico" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"><path d="M8 6h12M8 12h12M8 18h12"/><circle cx="4.5" cy="6" r="1.2" fill="currentColor" stroke="none"/><circle cx="4.5" cy="12" r="1.2" fill="currentColor" stroke="none"/><circle cx="4.5" cy="18" r="1.2" fill="currentColor" stroke="none"/></svg>',ol:'<svg class="ke-ico" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"><path d="M9 6h11M9 12h11M9 18h11"/><text x="1.6" y="8.2" font-size="7" font-family="inherit" fill="currentColor" stroke="none">1</text><text x="1.6" y="14.4" font-size="7" font-family="inherit" fill="currentColor" stroke="none">2</text><text x="1.6" y="20.6" font-size="7" font-family="inherit" fill="currentColor" stroke="none">3</text></svg>',quote:'<svg class="ke-ico" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"><path d="M5 5v14"/><path d="M10 8h9M10 12h9M10 16h5"/></svg>',link:'<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="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/></svg>',unlink:'<svg class="ke-ico" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"><path d="M9 14 4.5 18.5M14.5 5.5 19 10"/><path d="M10.5 13.5a4 4 0 0 0 5.6 0l2.4-2.4a4 4 0 0 0-5.6-5.6"/><path d="M13.5 10.5a4 4 0 0 0-5.6 0l-2.4 2.4a4 4 0 0 0 5.6 5.6"/><path d="m3 3 18 18"/></svg>',image:'<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="4.5" width="18" height="15" rx="2.5"/><circle cx="8.5" cy="10" r="1.6"/><path d="m4 18 5-5 3.5 3.5L17 12l3 3"/></svg>',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>',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>',code:T("m9 7-5 5 5 5M15 7l5 5-5 5"),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>',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>',source:T("m8 7-5 5 5 5M16 7l5 5-5 5M13.5 4l-3 16"),preview:'<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="M2.5 12S6 5.5 12 5.5 21.5 12 21.5 12 18 18.5 12 18.5 2.5 12 2.5 12Z"/><circle cx="12" cy="12" r="3"/></svg>',trash:'<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="M4 7h16M9.5 7V4.5h5V7M6.5 7l1 13h9l1-13"/></svg>',close:T("m6 6 12 12M18 6 6 18"),copy:'<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="9" y="9" width="11" height="11" rx="2"/><path d="M15 5H6a2 2 0 0 0-2 2v9"/></svg>',format:T("M4 6h10M4 12h16M4 18h7M18 4v6m0 0 2.5-2.5M18 10l-2.5-2.5"),check:T("m5 13 4 4L19 7"),checkLight:'<svg class="ke-ico" viewBox="0 0 24 24" fill="none" stroke="#fff" stroke-width="2.6" stroke-linecap="round" stroke-linejoin="round"><path d="m5 13 4 4L19 7"/></svg>',plus:T("M12 5v14M5 12h14"),minus:T("M5 12h14"),upload:'<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 16V4m0 0-4 4m4-4 4 4"/><path d="M4 15v3a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-3"/></svg>',retry:'<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="M20 12a8 8 0 1 1-3-6.2"/><path d="M20 4v5h-5"/></svg>',rounded:'<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="4" y="4" width="16" height="16" rx="6"/></svg>',expand:'<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="M4 9V4h5M20 9V4h-5M4 15v5h5M20 15v5h-5"/></svg>',compress:'<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="M9 4v5H4M15 4v5h5M9 20v-5H4M15 20v-5h5"/></svg>'};function M(o){return nt[o]||""}const re=[["#07c160","微信绿"],["#2f6fed","科技蓝"],["#7c3aed","极光紫"],["#d53880","品红"],["#e53e3e","中国红"],["#ed8936","暮橙"],["#f6c344","明黄"],["#0f766e","松石绿"]],rt=[["#1f2329","墨黑"],["#6b7280","深灰"],["#b8bec7","浅灰"],["#f2f3f5","云灰"],["#ffffff","纯白"],["#c00000","深红"],["#ff0000","正红"],["#ffc000","琥珀"],["#ffff00","柠黄"],["#00b050","草绿"],["#00b0f0","天蓝"],["#0070c0","海蓝"],["#7030a0","葡萄紫"],["#ff69b4","桃花粉"]],we=[["#fef08a","柠檬底"],["#dcfce7","薄荷底"],["#e0f2fe","天空底"],["#ede9fe","薰衣底"],["#ffe4e6","樱花底"],["#fff4e6","奶茶底"],["#f2f3f5","纸张灰"],["#1f2329","夜墨"]],se=/^#([0-9a-f]{3}|[0-9a-f]{6})$/i;class st{constructor(e){this.root=e,this.el=l("div.ke-pop",{hidden:!0}),this.anchor=null,this.onClose=null,e.appendChild(this.el),this.el.addEventListener("mousedown",t=>{/^(input|textarea|select)$/i.test(t.target.tagName)||t.preventDefault()}),this.docHandler=t=>{var i,n;this.el.hidden||this.el.contains(t.target)||(n=(i=t.target).closest)!=null&&n.call(i,".ke-btn[data-k-pop]")||this.close()},document.addEventListener("mousedown",this.docHandler,!0),this.keyHandler=t=>{t.key==="Escape"&&this.close()},document.addEventListener("keydown",this.keyHandler)}open(e,t,{align:i="start",onClose:n}={}){var u;this.el.textContent="";const r=t(k=>this.el.appendChild(k));r&&this.el.appendChild(r),this.el.hidden=!1,this.anchor=e,this.onClose=n;const s=this.root.getBoundingClientRect(),a=e.getBoundingClientRect(),c=this.el.getBoundingClientRect();let d=a.left-s.left;i==="center"&&(d=a.left-s.left+a.width/2-c.width/2),i==="end"&&(d=a.right-s.left-c.width),d=Math.max(8,Math.min(d,s.width-c.width-8));let h=a.top-s.top+a.height+8;h+c.height>s.height-8&&a.top-s.top-c.height-8>0&&(h=a.top-s.top-c.height-8),this.el.style.left=`${d}px`,this.el.style.top=`${h}px`,this.el.classList.remove("ke-pop-in"),this.el.offsetWidth,this.el.classList.add("ke-pop-in");const p=[...this.el.querySelectorAll("[data-k-autofocus]")].find(k=>k.offsetParent!==null);(u=p==null?void 0:p.focus)==null||u.call(p)}close(){if(this.el.hidden)return;this.el.hidden=!0,this.el.classList.remove("ke-pop-in"),this.el.textContent="",this.anchor=null;const e=this.onClose;this.onClose=null,e==null||e()}get isOpen(){return!this.el.hidden}destroy(){document.removeEventListener("mousedown",this.docHandler,!0),document.removeEventListener("keydown",this.keyHandler),this.el.remove()}}function O(o,e){const t=l("div.ke-panel-head",{},[l("span.ke-panel-title",{text:o})]);return e&&t.appendChild(e),l("div.ke-panel",{},[t])}function q(o){return l("div.ke-panel-sect",{text:o})}function Ce(){return l("div.ke-panel-divider")}function at({title:o,kind:e,colors:t,value:i,recents:n=[],onPick:r,onClear:s}){const a=e==="bg",c=l("button.ke-panel-reset",{type:"button",title:a?"清除高亮":"恢复默认文字色",text:a?"清除高亮":"恢复默认",onclick:()=>s?s():r(null)}),d=O(o,c);return n.length&&(d.appendChild(q("最近使用")),d.appendChild(U(n.slice(0,8),i,r))),a?(d.appendChild(q("推荐底色")),d.appendChild(U(we.map(([h,p])=>[h,p]),i,r)),d.appendChild(q("主题颜色")),d.appendChild(U(re,i,r))):(d.appendChild(q("主题颜色")),d.appendChild(U(re,i,r)),d.appendChild(q("标准颜色")),d.appendChild(U(rt,i,r))),d.appendChild(Ce()),d.appendChild(lt(i,r)),d}function U(o,e,t){const i=l("div.ke-sw-grid");return o.forEach(([n,r])=>{const s=l("button.ke-sw",{type:"button",title:`${r} ${n}`,"aria-label":r,style:{background:n}});e&&se.test(e)&&n.toLowerCase()===String(e).toLowerCase()&&(s.classList.add("ke-is-active"),s.appendChild(l("span.ke-sw-check",{html:M("checkLight")}))),s.addEventListener("click",()=>t(n)),i.appendChild(s)}),i}function lt(o,e){const t=se.test(o||"")?o:"#07c160",i=l("input.ke-sw-picker",{type:"color",value:t,title:"自定义颜色"}),n=l("input.ke-input.ke-sw-hex",{type:"text",value:t,placeholder:"#000000",maxlength:7}),r=l("button.ke-btn-primary",{type:"button",text:"应用"}),s=()=>{const a=n.value.trim(),c=a.startsWith("#")?a:`#${a}`;if(!se.test(c)){n.classList.add("ke-is-invalid");return}n.classList.remove("ke-is-invalid"),e(c)};return i.addEventListener("input",()=>{n.value=i.value}),i.addEventListener("change",s),r.addEventListener("click",s),n.addEventListener("keydown",a=>{a.key==="Enter"&&(a.preventDefault(),s())}),l("div.ke-panel-foot",{},[i,n,r])}function ct(o,{value:e,onPick:t}){const i=O("段落样式");return i.classList.add("ke-panel-wide"),o.forEach(n=>{const r=l("button.ke-hd-row",{type:"button",dataset:{kValue:n.value},onclick:()=>t(n.value)},[l("span.ke-hd-sample",{class:n.sampleClass||"",text:n.sample||n.label}),l("span.ke-hd-meta",{},[l("span.ke-hd-label",{text:n.label}),l("span.ke-hd-desc",{text:n.desc})])]);n.value===e&&r.classList.add("ke-is-active"),i.appendChild(r)}),i}function dt(o,{value:e,onPick:t}){const i=O("字号",l("span.ke-panel-note",{text:e?`${e}px`:"默认 17px"}));i.classList.add("ke-panel-wide");const n=l("div.ke-size-grid");return o.forEach(r=>{const s=l("button.ke-size-cell",{type:"button",text:String(r),onclick:()=>t(r)});s.style.fontSize=`${Math.min(20,10+r/6)}px`,Number(e)===r&&s.classList.add("ke-is-active"),n.appendChild(s)}),i.appendChild(n),i.appendChild(Ce()),i.appendChild(l("div.ke-panel-hint",{text:"仅作用于选中的文字;未选中时对新输入的文字生效"})),i}re.map(o=>o[0]),we.map(o=>o[0]);function ht(o,{cols:e=10,rows:t=8}={}){const i=O("插入表格",l("span.ke-panel-note",{text:"最大 10×8"})),n=l("div.ke-table-grid",{style:{gridTemplateColumns:`repeat(${e}, 18px)`}}),r=[];for(let c=0;c<t;c+=1)for(let d=0;d<e;d+=1){const h=l("span.ke-table-cell");h.dataset.r=String(c),h.dataset.c=String(d),r.push(h),n.appendChild(h)}i.appendChild(n);const s=l("div.ke-panel-hint",{text:"1 列 × 1 行"});i.appendChild(s);const a=(c,d)=>{r.forEach(h=>{const p=Number(h.dataset.r)<=c&&Number(h.dataset.c)<=d;h.classList.toggle("ke-is-on",p)}),s.textContent=`${d+1} 列 × ${c+1} 行`};return n.addEventListener("mousemove",c=>{const d=c.target.closest(".ke-table-cell");d&&a(Number(d.dataset.r),Number(d.dataset.c))}),n.addEventListener("click",c=>{const d=c.target.closest(".ke-table-cell");d&&o(Number(d.dataset.c)+1,Number(d.dataset.r)+1)}),n.addEventListener("mouseenter",()=>a(0,0)),a(0,0),i}function pt(o,{onFiles:e,onUrl:t,multiple:i,hint:n,maxText:r}){const s=o==="image",a=O(s?"插入图片":"插入视频");a.classList.add("ke-panel-wide","ke-panel-media");const c=l("div.ke-tab-body"),d=l("div.ke-tab-body",{hidden:!0}),h=l("div.ke-drop",{},[l("span.ke-drop-ico",{html:M("upload")}),l("div.ke-drop-title",{text:s?"点击选择图片,或拖拽到此处":"点击选择视频,或拖拽到此处"}),l("div.ke-drop-sub",{text:[r,n].filter(Boolean).join(" · ")})]),p=l("button.ke-btn-primary",{type:"button",text:s?"选择图片":"选择视频",onclick:()=>e(null)});h.addEventListener("click",()=>e(null)),h.addEventListener("dragover",m=>{m.preventDefault(),h.classList.add("ke-is-over")}),h.addEventListener("dragleave",()=>h.classList.remove("ke-is-over")),h.addEventListener("drop",m=>{var x,g;m.preventDefault(),h.classList.remove("ke-is-over"),(g=(x=m.dataTransfer)==null?void 0:x.files)!=null&&g.length&&e(m.dataTransfer.files)}),c.append(h,l("div.ke-panel-foot",{},[p,l("span.ke-panel-hint",{text:i?"可一次插入多张":"单文件大文件将自动分片上传"})]));const u=l("input.ke-input",{type:"url",placeholder:s?"https://example.com/photo.jpg":"https://example.com/video.mp4","data-k-autofocus":""}),k=l("input.ke-input",{type:"text",placeholder:s?"图片描述(可选,作为 alt)":"视频标题(可选)"}),f=l("div.ke-link-status",{text:"粘贴链接后自动校验可访问性"}),y=l("button.ke-btn-primary",{type:"button",text:"插入",disabled:!0});let v=null,C=0;const S=()=>{C+=1;const m=C;clearTimeout(v);const x=W(u.value);if(y.disabled=!x,f.className="ke-link-status",!x){f.textContent="请输入 http(s) 开头的链接";return}f.className="ke-link-status ke-is-checking",f.textContent="正在校验…",v=setTimeout(()=>ut(o,x,g=>{m===C&&(g?(f.className="ke-link-status ke-is-ok",f.textContent=s?"图片可访问 ✓":"视频可播放 ✓"):(f.className="ke-link-status ke-is-bad",f.textContent="未能自动加载(可能限制热链),不阻塞插入,发布前请自行确认"))}),350)};u.addEventListener("input",S),u.addEventListener("paste",()=>setTimeout(S,0));const A=()=>{const m=W(u.value);if(!m){u.classList.add("ke-is-invalid"),u.focus();return}t({url:m,name:k.value.trim()})};y.addEventListener("click",A),d.addEventListener("keydown",m=>{m.key==="Enter"&&(m.preventDefault(),A())}),d.append(l("div.ke-field",{},[l("span.ke-field-label",{text:"地址"}),u]),l("div.ke-field",{},[l("span.ke-field-label",{text:s?"描述":"标题"}),k]),f,l("div.ke-panel-foot",{},[y,l("span.ke-panel-hint",{text:"外链由源站提供,不占用上传配额"})]));const H=l("div.ke-tabs",{},[l("button.ke-tab",{type:"button",text:"本地上传"}),l("button.ke-tab",{type:"button",text:"网络链接"})]),E=m=>{[...H.children].forEach((x,g)=>x.classList.toggle("ke-is-active",g===m)),c.hidden=m!==0,d.hidden=m!==1,m===1&&u.focus()};return H.children[0].addEventListener("click",()=>E(0)),H.children[1].addEventListener("click",()=>E(1)),E(0),a.append(H,c,d),a}function ut(o,e,t){let i=!1;const n=r=>{i||(i=!0,t(r))};try{if(o==="image"){const r=new Image;r.onload=()=>n(!0),r.onerror=()=>n(!1),r.referrerPolicy="no-referrer",r.src=e}else{const r=document.createElement("video");r.preload="metadata",r.muted=!0,r.onloadedmetadata=()=>n(r.videoHeight>0||r.duration>0||Number.isFinite(r.duration)),r.onerror=()=>n(!1),r.src=e}}catch{n(!1)}}function ft({url:o="",text:e="",target:t=!1,onSubmit:i,onCancel:n,onRemove:r}){const s=l("input.ke-input",{type:"url",placeholder:"https://mp.weixin.qq.com/...",value:o,"data-k-autofocus":""}),a=l("input.ke-input",{type:"text",placeholder:"链接文字(留空使用 URL)",value:e}),c=l("input",{type:"checkbox"});c.checked=!!t;const d=O(o?"编辑链接":"插入链接");d.classList.add("ke-panel-wide");const h=l("div",{},[l("div.ke-field",{},[l("span.ke-field-label",{text:"文字"}),a]),l("div.ke-field",{},[l("span.ke-field-label",{text:"地址"}),s]),l("label.ke-check",{},[c,"新窗口打开"]),l("div.ke-panel-foot",{},[r?l("button.ke-btn-ghost",{type:"button",text:"移除链接",style:{marginRight:"auto",color:"#e53e3e"},onclick:r}):null,l("button.ke-btn-ghost",{type:"button",text:"取消",onclick:n}),l("button.ke-btn-primary",{type:"button",text:"确定",onclick:()=>p()})])]),p=()=>{const u=W(s.value);if(!u){s.classList.add("ke-is-invalid"),s.focus();return}i({url:u,text:a.value.trim(),target:c.checked})};return h.addEventListener("keydown",u=>{u.key==="Enter"&&(u.preventDefault(),p())}),d.appendChild(h),d}function mt(o){try{return new URL(o,window.location.href).host}catch{return String(o).slice(0,40)}}function kt({title:o,note:e,searchable:t,width:i,remote:n,value:r,load:s,reload:a,linkOf:c,onPick:d,emptyText:h}){const p=O(o);p.classList.add("ke-panel-wide","ke-panel-select"),i&&(p.style.width=`${Math.min(420,Math.max(200,Number(i)))}px`);const u=p.querySelector(".ke-panel-head"),k=l("span.ke-panel-note",{text:e||""});n&&u.appendChild(l("button.ke-panel-icon",{type:"button",title:"重新加载数据",html:M("retry"),onclick:()=>E(a||s,!0)})),u.appendChild(k);const f=l("div.ke-sel-body");p.appendChild(f);let y=[],v="",C=0;if(t){const m=l("input.ke-input.ke-sel-search",{type:"search",placeholder:"搜索…","data-k-autofocus":""});m.addEventListener("input",()=>{v=m.value.trim().toLowerCase(),A()}),p.insertBefore(m,f)}function S(m,x){if(f.textContent="",f.dataset.state=m,m==="loading"){for(let g=0;g<3;g+=1)f.appendChild(l("div.ke-sel-skel"));f.insertBefore(l("div.ke-sel-loading",{},[l("span.ke-spinner"),"数据加载中…"]),f.firstChild)}else m==="error"?f.appendChild(l("div.ke-sel-tip",{},[l("span.ke-sel-tip-text",{text:x||"数据加载失败"}),l("button.ke-btn-primary",{type:"button",text:"重试",onclick:()=>E(a||s,!0)})])):f.appendChild(l("div.ke-sel-tip",{},[l("span.ke-sel-tip-text",{text:x||h||"暂无数据"})]))}function A(){const m=v?y.filter(g=>`${g.label} ${g.desc} ${g.value} ${g.group}`.toLowerCase().includes(v)):y;if(k.textContent=e||(v?`${m.length} / ${y.length} 项`:`${y.length} 项`),f.textContent="",delete f.dataset.state,!m.length){S("empty",v?`没有匹配「${v}」的选项`:h||"暂无数据");return}let x=null;m.forEach(g=>{g.group&&g.group!==x&&(x=g.group,f.appendChild(l("div.ke-panel-sect",{text:x}))),f.appendChild(H(g))})}function H(m){const x=c?c(m):null,g=l("button.ke-sel-row",{type:"button",disabled:m.disabled||void 0,dataset:{kValue:m.value},title:m.disabled?"该项不可用":x&&x.mode==="open"?`打开 ${x.url}`:x?`插入链接:${x.url}`:m.title||"",onclick:()=>{m.disabled||d(m)}});return g.appendChild(l("span.ke-sel-main",{},[l("span.ke-sel-label",{text:m.label}),m.desc?l("span.ke-sel-desc",{text:m.desc}):null,x?l("span.ke-sel-link",{html:`${M("link")}<i>${mt(x.url)}</i>`}):null])),r&&String(r)===String(m.value)&&(g.classList.add("ke-is-active"),g.appendChild(l("span.ke-sel-check",{html:M("check")}))),x&&g.classList.add("ke-has-link"),g}function E(m,x){C+=1;const g=C;S("loading"),Promise.resolve().then(()=>m({force:x})).then($=>{g!==C||!p.isConnected||(y=Array.isArray($)?$:[],y.length?A():S("empty"))}).catch($=>{g!==C||!p.isConnected||S("error",$&&$.message?$.message:"数据加载失败")})}return E(s),p}function W(o){const e=String(o||"").trim();return e?/^(https?:|mailto:|tel:|#|\/)/i.test(e)?e:/^[\w-]+(\.[\w-]+)+/.test(e)?`https://${e}`:"":""}const Se=new Set(["p","div","section","blockquote","ul","ol","li","table","thead","tbody","tfoot","tr","td","th","figure","figcaption","pre","h1","h2","h3","h4","h5","h6","hr","video"]);function ae(o,{indent:e=" "}={}){if(!o)return"";const i=new DOMParser().parseFromString(`<div>${o}</div>`,"text/html").body.firstChild,n=[],r=(a,c)=>{const d=c.replace(/\s+/g," ").trim();if(!d)return;const h=n[n.length-1];h&&h.depth===a&&h.inlineRun?h.text+=` ${d}`:n.push({depth:a,text:e.repeat(a)+d,inlineRun:!0})},s=(a,c)=>{[...a.childNodes].forEach(h=>{if(h.nodeType===3){const f=h.textContent.trim();f&&r(c,f);return}if(h.nodeType!==1)return;const p=h.tagName.toLowerCase();if(!Se.has(p)){r(c,h.outerHTML);return}if(![...h.querySelectorAll("*")].some(f=>Se.has(f.tagName.toLowerCase()))||(p==="tr"||p==="figure"||p==="video")){n.push({depth:c,text:e.repeat(c)+gt(h.outerHTML),inlineRun:!1});return}n.push({depth:c,text:e.repeat(c)+bt(h),inlineRun:!1}),s(h,c+1),n.push({depth:c,text:e.repeat(c)+`</${p}>`,inlineRun:!1})})};return s(i,0),n.map(a=>a.text).join(`
|
|
478
|
-
`).replace(/\n{3,}/g,`
|
|
479
|
-
|
|
480
|
-
`)}function gt(o){return o.replace(/\n\s+/g," ").replace(/\s{2,}/g," ").trim()}function bt(o){const e=[...o.attributes].map(t=>`${t.name}="${(t.value||"").replace(/"/g,""")}"`);return`<${o.tagName.toLowerCase()}${e.length?` ${e.join(" ")}`:""}>`}class xt{constructor(e){this.editor=e,this.open=!1,this.el=l("div.ke-source",{hidden:!0},[l("div.ke-source-bar",{},[l("span.ke-source-title",{text:"HTML 源码"}),l("span.ke-source-tip",{text:"可直接编辑,点击「应用」或退出源码模式即生效"}),l("span.ke-source-tail",{},[l("button.ke-btn",{type:"button",title:"格式化",html:M("format")+"<span>格式化</span>",onclick:()=>this.format()}),l("button.ke-btn",{type:"button",title:"复制全部",html:M("copy")+"<span>复制</span>",onclick:()=>this.copy()}),l("button.ke-btn",{type:"button",title:"应用修改",html:M("check")+"<span>应用</span>",onclick:()=>this.apply()}),l("button.ke-btn",{type:"button",title:"退出源码模式",html:M("close"),onclick:()=>e.exitSource()})])]),(this.code=l("pre.ke-source-code",{contenteditable:"true",spellcheck:"false",autocapitalize:"off",autocomplete:"off",wrap:"off"}),this.code.addEventListener("keydown",t=>{t.key==="Tab"&&(t.preventDefault(),document.execCommand("insertText",!1," ")),(t.ctrlKey||t.metaKey)&&t.key.toLowerCase()==="s"&&(t.preventDefault(),this.apply()),t.stopPropagation()}),this.code)])}get value(){return this.code.textContent}set value(e){this.code.textContent=e,this.code.scrollTop=0}show(e){this.value=ae(e),this.el.hidden=!1,this.open=!0,this.editor.scrollEl.hidden=!0}hide(){this.el.hidden=!0,this.open=!1,this.editor.scrollEl.hidden=!1}format(){this.value=ae(this.value),this.editor.toast.show("已格式化")}async copy(){var t;const e=this.value;try{(t=navigator.clipboard)!=null&&t.writeText?await navigator.clipboard.writeText(e):(this.code.focus(),document.execCommand("selectAll"),document.execCommand("copy")),this.editor.toast.show("源码已复制到剪贴板")}catch{this.editor.toast.error("复制失败,请手动选择复制")}}apply({silent:e=!1}={}){const t=this.value;try{return this.editor.setContent(t,{sanitize:!0,silent:!1}),e||this.editor.toast.show("源码已应用"),!0}catch(i){return this.editor.toast.error(`源码解析失败:${i.message}`),!1}}destroy(){this.el.remove()}}const le=[{key:"mobile",label:"手机",width:375},{key:"pad",label:"平板",width:540},{key:"pc",label:"电脑",width:677}];class yt{constructor(e){this.editor=e,this.device="pc",this.el=l("div.ke-preview",{hidden:!0},[l("div.ke-preview-bar",{},[l("span",{text:"预览"}),l("span.ke-source-tip",{text:"仅用于查看排版效果,内容不可编辑"}),l("span.ke-status-tail",{},le.map(t=>l("button.ke-btn",{type:"button","data-k-device":t.key,text:t.label,onclick:()=>this.setDevice(t.key)})).concat([l("span.ke-tb-sep"),l("button.ke-btn",{type:"button",title:"关闭预览",html:M("close"),onclick:()=>e.closePreview()})]))]),(this.body=l("div.ke-preview-body",{},[l("div.ke-preview-frame",{style:{maxWidth:"677px"}},[l("div.ke-content.ke-preview-content")])]),this.frame=this.body.firstChild,this.content=this.frame.firstChild,this.body)])}setDevice(e){this.device=e;const t=le.find(i=>i.key===e)||le[2];this.frame.style.maxWidth=`${t.width}px`,this.frame.style.width=e==="mobile"?`${t.width}px`:"100%",this.el.querySelectorAll("[data-k-device]").forEach(i=>i.classList.toggle("ke-is-active",i.dataset.kDevice===e))}show(e){this.content.innerHTML=e,this.el.hidden=!1,this.setDevice(this.device)}hide(){this.el.hidden=!0,this.content.innerHTML=""}destroy(){this.el.remove()}}class vt{constructor(e=null){this.owner=e,this.el=null}show(e,t="",i=2600){if(typeof document>"u")return;this.el||(this.el=l("div.ke-toasts"),document.body.appendChild(this.el));const n=l(`span.ke-toast${t?`.ke-is-${t}`:""}`,{text:e});this.el.appendChild(n),setTimeout(()=>{n.style.opacity="0",n.style.transition="opacity .2s",setTimeout(()=>n.remove(),220)},i)}error(e){this.show(e,"error",3600)}warn(e){this.show(e,"warn",3e3)}ok(e){this.show(e,"ok",2200)}destroy(){this.el&&!this.el.childElementCount&&this.el.remove(),this.el=null}}function J(o,e=document){const t=l("div.ke-lightbox",{tabindex:"-1"},[l("img",{src:o,alt:""})]),i=()=>{t.remove(),document.removeEventListener("keydown",n)},n=r=>{r.key==="Escape"&&i()};return t.addEventListener("click",i),document.addEventListener("keydown",n),e.body.appendChild(t),i}class wt{constructor(e){this.editor=e,this.node=null,this.el=l("div.ke-bubble",{hidden:!0,contenteditable:"false"}),e.el.appendChild(this.el),this.el.addEventListener("mousedown",t=>t.preventDefault()),this.el.addEventListener("click",t=>this.onClick(t)),this.replaceInput=l("input",{type:"file",style:{display:"none"}}),this.replaceInput.addEventListener("change",()=>{var i;const t=(i=this.replaceInput.files)==null?void 0:i[0];this.replaceInput.value="",t&&this.node&&this.editor.media.replaceNode(this.node,t)}),e.el.appendChild(this.replaceInput),this.resizeEl=l("div.ke-img-resize",{hidden:!0,"aria-label":"拖动缩放图片",title:"拖动缩放图片",html:'<svg viewBox="0 0 10 10"><path d="M7 1 L9 3 M4 4 L6 6 M1 7 L3 9" stroke="currentColor" stroke-width="1.6" stroke-linecap="round"/></svg>'}),this.resizeTip=l("div.ke-img-resize-tip",{hidden:!0}),this.resizeEl.addEventListener("pointerdown",t=>this.onResizePointerDown(t)),e.el.appendChild(this.resizeEl),e.el.appendChild(this.resizeTip)}show(e){this.node=e;const t=e.dataset.kMedia==="video"?"video":"image";this.el.textContent="";const i=t==="image"?this.imageActions(e):this.videoActions(e);for(const n of i)n&&this.el.appendChild(n);this.el.hidden=!1,t==="image"&&this.attachResize(),this.position()}hide(){this.el.hidden=!0,this.detachResize(),this.node=null}attachResize(){var e;(e=this.node)!=null&&e.querySelector("img")&&(this.resizeEl.hidden=!1,this.positionHandle())}detachResize(){this.resizeEl.hidden=!0,this.resizeTip.hidden=!0}position(){if(!this.node||(this.positionHandle(),this.el.hidden))return;const e=this.editor.el.getBoundingClientRect(),t=this.node.getBoundingClientRect(),i=this.editor.scrollEl.getBoundingClientRect();if(!t.height&&!t.width)return this.hide();if(t.bottom<i.top||t.top>i.bottom)return this.hide();const n=this.el.getBoundingClientRect(),r=t.left-e.left+t.width/2,a=t.top-e.top<n.height+18,c=a?t.bottom-e.top+10:t.top-e.top-10;this.el.classList.toggle("ke-is-below",a);const d=n.width/2;this.el.style.left=`${Math.min(Math.max(r,d+8),Math.max(d+8,e.width-d-8))}px`,this.el.style.top=`${Math.max(6,c)}px`}positionHandle(){const e=this.node;if(!e||this.resizeEl.hidden)return;const t=e.querySelector("img");if(!t)return;const i=this.editor.el.getBoundingClientRect(),n=t.getBoundingClientRect();if(!n.width&&!n.height)return;const r=18,s=6;this.resizeEl.style.left=`${n.right-i.left-r-s}px`,this.resizeEl.style.top=`${n.bottom-i.top-r-s}px`}updateResizeTip(e){var n;if(this.resizeTip.hidden||!this.node)return;this.resizeTip.textContent=`${Math.round(e)}%`;const t=this.editor.el.getBoundingClientRect(),i=((n=this.node.querySelector("img"))==null?void 0:n.getBoundingClientRect())||this.node.getBoundingClientRect();this.resizeTip.style.left=`${i.left-t.left+i.width/2}px`,this.resizeTip.style.top=`${i.top-t.top-10}px`}onResizePointerDown(e){var d;if(e.button!=null&&e.button!==0)return;const t=(d=this.node)==null?void 0:d.querySelector("img");if(!t)return;e.preventDefault(),e.stopPropagation();const n=this.node.getBoundingClientRect().width,r=Ee(Et(t,n),15,100),s=e.clientX;this.el.hidden=!0,this.resizeTip.hidden=!1,this.updateResizeTip(r);try{this.resizeEl.setPointerCapture(e.pointerId)}catch{}const a=h=>{const p=h.clientX-s,u=n?p/n*100:0,k=Ee(Math.round(r+u),15,100);t.style.width=`${k}%`,t.style.maxWidth="100%",this.updateResizeTip(k),this.positionHandle()},c=()=>{this.resizeEl.removeEventListener("pointermove",a),this.resizeEl.removeEventListener("pointerup",c),this.resizeEl.removeEventListener("pointercancel",c),this.resizeTip.hidden=!0,this.editor.commitHistory(),this.editor.refreshStatus(),this.el.hidden=!1,this.position()};this.resizeEl.addEventListener("pointermove",a),this.resizeEl.addEventListener("pointerup",c),this.resizeEl.addEventListener("pointercancel",c)}imageActions(e){const t=e.querySelector("img"),i=oe(t),n=t&&parseFloat(getComputedStyle(t).borderRadius)>0,r=a=>{ne(t,a),this.editor.commitHistory(),this.position()},s=a=>{t.style.width=a,ne(t,oe(t)),this.editor.commitHistory(),this.position()};return[B("alignLeft","左对齐",()=>r("left"),i==="left"),B("alignCenter","居中",()=>r("center"),i==="center"),B("alignRight","右对齐",()=>r("right"),i==="right"),V(),_("30%","宽度 30%",()=>s("30%")),_("60%","宽度 60%",()=>s("60%")),_("100%","宽度 100%",()=>s("100%")),V(),B("rounded","圆角",()=>Ct(t,e),n),B("preview","查看大图",()=>St(t)),B("upload","替换图片",()=>this.pick("image")),V(),B("trash","删除",()=>this.remove())]}videoActions(){return[_("小","窄版",()=>this.setVideoWidth("60%")),_("大","宽版",()=>this.setVideoWidth("100%")),V(),B("upload","替换视频",()=>this.pick("video")),V(),B("trash","删除",()=>this.remove())]}pick(e){this.replaceInput.accept=e==="image"?this.editor.options.imageAccept:this.editor.options.videoAccept,this.replaceInput.click()}setVideoWidth(e){this.node&&(this.node.style.width=e,this.editor.commitHistory(),this.position())}remove(){if(!this.node)return;const e=this.editor.media.taskFromNode(this.node);if(e)this.editor.media.remove(e);else{const t=this.node.nextElementSibling;this.node.remove(),t&&this.editor.focus(),this.editor.commitHistory()}this.hide(),this.editor.refreshStatus()}onClick(){}destroy(){this.el.remove(),this.replaceInput.remove(),this.resizeEl.remove(),this.resizeTip.remove()}}function B(o,e,t,i=!1){const n=l("button",{type:"button",title:e,html:M(o)});return i&&n.classList.add("ke-is-active"),n.addEventListener("click",t),n}function _(o,e,t){const i=l("button",{type:"button",title:e,text:o});return i.addEventListener("click",t),i}const V=()=>l("span.ke-sep");function Ct(o,e){if(!o)return;const t=parseFloat(getComputedStyle(o).borderRadius)>0;o.style.borderRadius=t?"0":"10px",e.dispatchEvent(new Event("change",{bubbles:!0}))}function St(o){o&&J(o.src)}function Ee(o,e,t){return Math.min(t,Math.max(e,o))}function Et(o,e){var i,n;if(!e)return 100;const t=(n=(i=o==null?void 0:o.style)==null?void 0:i.width)==null?void 0:n.match(/^([\d.]+)%$/);return t?parseFloat(t[1]):o.getBoundingClientRect().width/e*100}const Lt=new Set(["a","abbr","b","blockquote","br","code","col","colgroup","dd","del","div","dl","dt","em","figcaption","figure","font","h1","h2","h3","h4","h5","h6","hr","i","img","ins","kbd","li","mark","ol","p","pre","s","samp","section","small","span","strong","sub","sup","table","tbody","td","tfoot","th","thead","tr","u","ul","video","source"]),Mt=new Set(["style","class"]),zt={A:["href","title","target","rel"],IMG:["src","alt","title","width","height"],VIDEO:["src","poster","controls","loop","muted","playsinline","preload","width","height"],SOURCE:["src","type"],FONT:["size","color"],TD:["colspan","rowspan"],TH:["colspan","rowspan"],OL:["start"],LI:["value"]},Tt=["data-k-","data-keditor-"],At=/^(?:https?:|mailto:|tel:|blob:|\/|#|\.{1,2}\/|[^:]*$)/i,Ht=/^data:image\/(?:png|jpe?g|gif|webp|svg\+xml);/i;function Y(o){if(!o)return!1;const e=String(o).trim().replace(/\s+/g,"");return/^(javascript|vbscript|file|about):/i.test(e)?!1:e.startsWith("data:")?Ht.test(e):At.test(e)}function Bt(o){const e=[];for(const t of String(o).split(";")){const i=t.indexOf(":");if(i<0)continue;const n=t.slice(0,i).trim().toLowerCase(),r=t.slice(i+1).trim();!n||!r||/^[a-z-]+$/.test(n)&&(n.startsWith("mso-")||n.startsWith("-mso-")||/expression|javascript:|behavior:|url\(\s*['"]?\s*(javascript|data):/i.test(r)||e.push(`${n}:${r}`))}return e.join(";")}function $t(o){return String(o).split(/\s+/).filter(e=>/^[\w-]+$/.test(e)&&!/^(script|javascript)/i.test(e)).join(" ")}function Rt(o,e,t){const i=e.toLowerCase();return i.startsWith("on")?!1:Mt.has(i)||Tt.some(r=>i.startsWith(r))?!0:(zt[o]||[]).includes(i)}function K(o,{allowEmpty:e=!1}={}){if(!o)return e?"":"<p><br></p>";const i=new DOMParser().parseFromString(`<div>${o}</div>`,"text/html").body.firstChild;Le(i);const n=i.innerHTML.trim();return!n&&!e?"<p><br></p>":n}function Le(o){const e=Array.from(o.childNodes);for(const t of e){if(t.nodeType===8){t.remove();continue}if(t.nodeType===3)continue;if(t.nodeType!==1){t.remove();continue}const i=t.tagName;if(!Lt.has(i.toLowerCase())){if(i==="SCRIPT"||i==="STYLE"||i==="IFRAME"||i==="OBJECT"||i==="EMBED"||i==="FORM"||i==="LINK"||i==="META"){t.remove();continue}const n=t.parentNode;for(;t.firstChild;)n.insertBefore(t.firstChild,t);n.removeChild(t);continue}for(const n of Array.from(t.attributes)){if(!Rt(i,n.name,n.value)){t.removeAttribute(n.name);continue}const r=n.name.toLowerCase();if(r==="style")t.setAttribute("style",Bt(n.value));else if(r==="class"){const s=$t(n.value);s?t.setAttribute("class",s):t.removeAttribute("class")}else(r==="href"||r==="src"||r==="poster")&&(Y(n.value)||t.removeAttribute(n.name))}i==="A"&&t.getAttribute("target")==="_blank"&&t.setAttribute("rel","noopener noreferrer"),(t.getAttribute("href")===""||!t.getAttribute("href"))&&i==="A"&&t.removeAttribute("href"),Le(t)}}const Ot={1:10,2:13,3:16,4:18,5:24,6:32,7:48};function Me(o){return/urn:schemas-microsoft-com|class=["']?Mso|ProgID|w:val=/i.test(o)}function ze(o){const e=new DOMParser().parseFromString(`<div>${o}</div>`,"text/html"),t=e.body.firstChild;return t.querySelectorAll("*").forEach(i=>{const n=i.tagName.toLowerCase();if(n.startsWith("o:")||n.startsWith("w:")||n==="style"||n==="script"||n==="link"||n==="meta"){i.remove();return}if(n==="img"){const r=Number(i.getAttribute("width")||0),s=Number(i.getAttribute("height")||0);(r&&r<=3||s&&s<=3)&&i.remove();return}if(n==="font"){const r=Ot[Number(i.getAttribute("size"))],s=e.createElement("span"),a=[];for(r&&a.push(`font-size:${r}px`),i.color&&a.push(`color:${i.color}`),a.length&&s.setAttribute("style",a.join(";"));i.firstChild;)s.appendChild(i.firstChild);i.replaceWith(s);return}for(const r of Array.from(i.attributes)){const s=r.name.toLowerCase();(s.startsWith("mso-")||s==="class"||s.startsWith("_")||s.startsWith("w:")||s.startsWith("o:")||s==="lang"||s==="dir")&&i.removeAttribute(r.name)}}),t.innerHTML}function ce(o){return String(o).replace(/[&<>"']/g,e=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[e])}function Te(o){const e=new DOMParser().parseFromString(`<div>${o}</div>`,"text/html");return e.body.querySelectorAll("style,script").forEach(t=>t.remove()),e.body.innerHTML=e.body.innerHTML.replace(/<\/(p|div|h[1-6]|li|blockquote|pre|tr)>/gi,`
|
|
556
|
+
`;let wt=!1;function Cn(){if(wt||typeof document>"u")return;const n=document.createElement("style");n.setAttribute("data-keditor-style",""),n.textContent=he,document.head.appendChild(n),wt=!0}const qe=(n="k")=>`${n}${Date.now().toString(36)}${Math.random().toString(36).slice(2,7)}`;function Sn(n,e=300){let t=null;const i=(...r)=>{clearTimeout(t),t=setTimeout(()=>n(...r),e)};return i.cancel=()=>clearTimeout(t),i.flush=(...r)=>{clearTimeout(t),n(...r)},i}const pe=(n,e,t)=>Math.min(Math.max(n,e),t);function W(n){if(!n&&n!==0)return"-";const e=["B","KB","MB","GB"];let t=0,i=n;for(;i>=1024&&t<e.length-1;)i/=1024,t+=1;return`${i.toFixed(i>=10||t===0?0:1)}${e[t]}`}function d(n,e={},t=[]){let i="div",r="";const o=String(n).split(".");i=o[0]||"div",r=o.slice(1).join(" ");const s=document.createElement(i);r&&(s.className=r);for(const[l,c]of Object.entries(e||{}))c==null||c===!1||(l==="class"?s.className=`${s.className} ${c}`.trim():l==="style"&&typeof c=="object"?Object.assign(s.style,c):l==="html"?s.innerHTML=c:l==="text"?s.textContent=c:l==="dataset"?Object.assign(s.dataset,c):l.startsWith("on")&&typeof c=="function"?s.addEventListener(l.slice(2).toLowerCase(),c):s.setAttribute(l,c===!0?"":String(c)));const a=Array.isArray(t)?t:[t];for(const l of a)l==null||l===!1||s.appendChild(typeof l=="string"||typeof l=="number"?document.createTextNode(String(l)):l);return s}function Ue(n){if(!n)return"left";const e=n.style.marginLeft,t=n.style.marginRight;return e==="auto"&&t==="auto"?"center":e==="auto"?"right":"left"}function We(n,e){n&&(n.style.maxWidth="100%",e==="center"?(n.style.marginLeft="auto",n.style.marginRight="auto"):e==="right"?(n.style.marginLeft="auto",n.style.marginRight="0"):(n.style.marginLeft="0",n.style.marginRight="auto"))}const D=n=>`<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="${n}"/></svg>`,En={undo:'<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="M9 14 4 9l5-5"/><path d="M4 9h10a5 5 0 0 1 0 10h-3"/></svg>',redo:'<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="m15 14 5-5-5-5"/><path d="M20 9H10a5 5 0 0 0 0 10h3"/></svg>',bold:'<svg class="ke-ico" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M7 5h6.5a3.5 3.5 0 0 1 0 7H7zM7 12h7.5a3.5 3.5 0 0 1 0 7H7z"/></svg>',italic:'<svg class="ke-ico" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"><path d="M15 5h-5M14 19H9M14.5 5 10 19"/></svg>',underline:'<svg class="ke-ico" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"><path d="M7 4v8a5 5 0 0 0 10 0V4M5 20h14"/></svg>',strike:'<svg class="ke-ico" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"><path d="M4 12h16M16.5 7A4.5 4.5 0 0 0 12 5c-2.2 0-3.6 1-4.2 2.4M7.5 17A4.5 4.5 0 0 0 12 19c2.3 0 3.9-1.1 4.4-2.8"/></svg>',foreColor:'<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="M5 17 9.5 5 14 17M6.8 13h5.9"/><rect x="4" y="19.5" width="11" height="2.2" rx="1" fill="currentColor" stroke="none"/></svg>',backColor:'<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 16l7.5-7.5a2 2 0 0 1 2.8 0l3.2 3.2a2 2 0 0 1 0 2.8L13 20z" /><path d="M10 8.5 15.5 14"/></svg>',alignLeft:D("M4 6h16M4 12h10M4 18h13"),alignCenter:D("M4 6h16M7 12h10M5.5 18h13"),alignRight:D("M4 6h16M10 12h10M7 18h13"),alignJustify:D("M4 6h16M4 12h16M4 18h16"),ul:'<svg class="ke-ico" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"><path d="M8 6h12M8 12h12M8 18h12"/><circle cx="4.5" cy="6" r="1.2" fill="currentColor" stroke="none"/><circle cx="4.5" cy="12" r="1.2" fill="currentColor" stroke="none"/><circle cx="4.5" cy="18" r="1.2" fill="currentColor" stroke="none"/></svg>',ol:'<svg class="ke-ico" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"><path d="M9 6h11M9 12h11M9 18h11"/><text x="1.6" y="8.2" font-size="7" font-family="inherit" fill="currentColor" stroke="none">1</text><text x="1.6" y="14.4" font-size="7" font-family="inherit" fill="currentColor" stroke="none">2</text><text x="1.6" y="20.6" font-size="7" font-family="inherit" fill="currentColor" stroke="none">3</text></svg>',quote:'<svg class="ke-ico" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"><path d="M5 5v14"/><path d="M10 8h9M10 12h9M10 16h5"/></svg>',link:'<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="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/></svg>',unlink:'<svg class="ke-ico" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"><path d="M9 14 4.5 18.5M14.5 5.5 19 10"/><path d="M10.5 13.5a4 4 0 0 0 5.6 0l2.4-2.4a4 4 0 0 0-5.6-5.6"/><path d="M13.5 10.5a4 4 0 0 0-5.6 0l-2.4 2.4a4 4 0 0 0 5.6 5.6"/><path d="m3 3 18 18"/></svg>',image:'<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="4.5" width="18" height="15" rx="2.5"/><circle cx="8.5" cy="10" r="1.6"/><path d="m4 18 5-5 3.5 3.5L17 12l3 3"/></svg>',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>',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>',code:D("m9 7-5 5 5 5M15 7l5 5-5 5"),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>',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>',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>',source:D("m8 7-5 5 5 5M16 7l5 5-5 5M13.5 4l-3 16"),preview:'<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="M2.5 12S6 5.5 12 5.5 21.5 12 21.5 12 18 18.5 12 18.5 2.5 12 2.5 12Z"/><circle cx="12" cy="12" r="3"/></svg>',trash:'<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="M4 7h16M9.5 7V4.5h5V7M6.5 7l1 13h9l1-13"/></svg>',close:D("m6 6 12 12M18 6 6 18"),copy:'<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="9" y="9" width="11" height="11" rx="2"/><path d="M15 5H6a2 2 0 0 0-2 2v9"/></svg>',format:D("M4 6h10M4 12h16M4 18h7M18 4v6m0 0 2.5-2.5M18 10l-2.5-2.5"),check:D("m5 13 4 4L19 7"),checkLight:'<svg class="ke-ico" viewBox="0 0 24 24" fill="none" stroke="#fff" stroke-width="2.6" stroke-linecap="round" stroke-linejoin="round"><path d="m5 13 4 4L19 7"/></svg>',plus:D("M12 5v14M5 12h14"),minus:D("M5 12h14"),upload:'<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 16V4m0 0-4 4m4-4 4 4"/><path d="M4 15v3a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-3"/></svg>',retry:'<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="M20 12a8 8 0 1 1-3-6.2"/><path d="M20 4v5h-5"/></svg>',rounded:'<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="4" y="4" width="16" height="16" rx="6"/></svg>',expand:'<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="M4 9V4h5M20 9V4h-5M4 15v5h5M20 15v5h-5"/></svg>',compress:'<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="M9 4v5H4M15 4v5h5M9 20v-5H4M15 20v-5h5"/></svg>'};function _(n){return En[n]||""}const Ln=new Set(["a","abbr","b","blockquote","br","code","col","colgroup","dd","del","div","dl","dt","em","figcaption","figure","font","h1","h2","h3","h4","h5","h6","hr","i","img","ins","kbd","li","mark","ol","p","pre","s","samp","section","small","span","strong","sub","sup","table","tbody","td","tfoot","th","thead","tr","u","ul","video","source"]),Mn=new Set(["style","class"]),zn={A:["href","title","target","rel"],IMG:["src","alt","title","width","height"],VIDEO:["src","poster","controls","loop","muted","playsinline","preload","width","height"],SOURCE:["src","type"],FONT:["size","color"],TD:["colspan","rowspan"],TH:["colspan","rowspan"],OL:["start"],LI:["value"]},Tn=["data-k-","data-keditor-"],An=/^(?:https?:|mailto:|tel:|blob:|\/|#|\.{1,2}\/|[^:]*$)/i,$n=/^data:image\/(?:png|jpe?g|gif|webp|svg\+xml);/i;function re(n){if(!n)return!1;const e=String(n).trim().replace(/\s+/g,"");return/^(javascript|vbscript|file|about):/i.test(e)?!1:e.startsWith("data:")?$n.test(e):An.test(e)}function Rn(n){const e=[];for(const t of String(n).split(";")){const i=t.indexOf(":");if(i<0)continue;const r=t.slice(0,i).trim().toLowerCase(),o=t.slice(i+1).trim();!r||!o||/^[a-z-]+$/.test(r)&&(r.startsWith("mso-")||r.startsWith("-mso-")||/expression|javascript:|behavior:|url\(\s*['"]?\s*(javascript|data):/i.test(o)||e.push(`${r}:${o}`))}return e.join(";")}function Hn(n){return String(n).split(/\s+/).filter(e=>/^[\w-]+$/.test(e)&&!/^(script|javascript)/i.test(e)).join(" ")}function Bn(n,e,t){const i=e.toLowerCase();return i.startsWith("on")?!1:Mn.has(i)||Tn.some(o=>i.startsWith(o))?!0:(zn[n]||[]).includes(i)}function ae(n,{allowEmpty:e=!1}={}){if(!n)return e?"":"<p><br></p>";const i=new DOMParser().parseFromString(`<div>${n}</div>`,"text/html").body.firstChild;Ct(i);const r=i.innerHTML.trim();return!r&&!e?"<p><br></p>":r}function Ct(n){const e=Array.from(n.childNodes);for(const t of e){if(t.nodeType===8){t.remove();continue}if(t.nodeType===3)continue;if(t.nodeType!==1){t.remove();continue}const i=t.tagName;if(!Ln.has(i.toLowerCase())){if(i==="SCRIPT"||i==="STYLE"||i==="IFRAME"||i==="OBJECT"||i==="EMBED"||i==="FORM"||i==="LINK"||i==="META"){t.remove();continue}const r=t.parentNode;for(;t.firstChild;)r.insertBefore(t.firstChild,t);r.removeChild(t);continue}for(const r of Array.from(t.attributes)){if(!Bn(i,r.name,r.value)){t.removeAttribute(r.name);continue}const o=r.name.toLowerCase();if(o==="style")t.setAttribute("style",Rn(r.value));else if(o==="class"){const s=Hn(r.value);s?t.setAttribute("class",s):t.removeAttribute("class")}else(o==="href"||o==="src"||o==="poster")&&(re(r.value)||t.removeAttribute(r.name))}i==="A"&&t.getAttribute("target")==="_blank"&&t.setAttribute("rel","noopener noreferrer"),(t.getAttribute("href")===""||!t.getAttribute("href"))&&i==="A"&&t.removeAttribute("href"),Ct(t)}}const Nn={1:10,2:13,3:16,4:18,5:24,6:32,7:48};function St(n){return/urn:schemas-microsoft-com|class=["']?Mso|ProgID|w:val=/i.test(n)}function Et(n){const e=new DOMParser().parseFromString(`<div>${n}</div>`,"text/html"),t=e.body.firstChild;return t.querySelectorAll("*").forEach(i=>{const r=i.tagName.toLowerCase();if(r.startsWith("o:")||r.startsWith("w:")||r==="style"||r==="script"||r==="link"||r==="meta"){i.remove();return}if(r==="img"){const o=Number(i.getAttribute("width")||0),s=Number(i.getAttribute("height")||0);(o&&o<=3||s&&s<=3)&&i.remove();return}if(r==="font"){const o=Nn[Number(i.getAttribute("size"))],s=e.createElement("span"),a=[];for(o&&a.push(`font-size:${o}px`),i.color&&a.push(`color:${i.color}`),a.length&&s.setAttribute("style",a.join(";"));i.firstChild;)s.appendChild(i.firstChild);i.replaceWith(s);return}for(const o of Array.from(i.attributes)){const s=o.name.toLowerCase();(s.startsWith("mso-")||s==="class"||s.startsWith("_")||s.startsWith("w:")||s.startsWith("o:")||s==="lang"||s==="dir")&&i.removeAttribute(o.name)}}),t.innerHTML}function q(n){return String(n).replace(/[&<>"']/g,e=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[e])}function Lt(n){const e=new DOMParser().parseFromString(`<div>${n}</div>`,"text/html");return e.body.querySelectorAll("style,script").forEach(t=>t.remove()),e.body.innerHTML=e.body.innerHTML.replace(/<\/(p|div|h[1-6]|li|blockquote|pre|tr)>/gi,`
|
|
481
557
|
`),e.body.textContent.replace(/\u00a0/g," ").replace(/\n{3,}/g,`
|
|
482
558
|
|
|
483
|
-
`).trim()}const Pt=1e4;function Ae(o){if(Array.isArray(o))return o;if(!o||typeof o!="object")return[];for(const e of["items","list","data","rows","records","result"]){const t=o[e];if(Array.isArray(t))return t;if(t&&typeof t=="object"){const i=Ae(t);if(i.length)return i}}return[]}function Z(o,e){for(const t of e){const i=o[t];if(i!=null)return i}}function Nt(o,e){if(o==null)return null;if(typeof o=="string"||typeof o=="number"){const n=String(o);return{value:n,label:n,desc:"",url:"",group:"",html:"",disabled:!1,raw:o}}if(typeof o!="object")return null;const t=Z(o,["value","id","key","val","code"]),i=Z(o,["label","text","name","title"]);return{value:String(t===void 0?e:t),label:String(i===void 0||i===""?t===void 0?e:t:i),desc:String(Z(o,["desc","description","sub","subtitle","tip"])??""),url:String(Z(o,["url","href","link","jumpUrl","jump"])??""),group:String(o.group??""),html:String(o.html??""),disabled:!!o.disabled,raw:o}}function G(o){return Ae(o).map(Nt).filter(Boolean)}function de(o={}){const e=o.position!==void 0?o.position:o.at,t=n=>Math.max(0,Math.floor(Number(n))),i=n=>typeof n=="object"&&n?n.before||n.after:n;if(typeof e=="number"&&Number.isFinite(e))return t(e);if(typeof e=="string"&&e){const n=e.toLowerCase();return n==="start"||n==="begin"||n==="first"?"start":n==="end"||n==="last"||n==="main"?"end":n==="tail"||n===":tail"||n==="right"?"tail":{before:e}}if(e&&typeof e=="object"){if(e.before)return{before:String(i(e))};if(e.after)return{after:String(i(e))}}return typeof o.index=="number"&&Number.isFinite(o.index)?t(o.index):o.before?{before:String(o.before)}:o.after?{after:String(o.after)}:null}function He(o){if(!o||typeof o!="object")return null;const e=String(o.name||"").trim();return e?{name:e,position:de(o),type:o.type==="button"?"button":"select",title:o.title||o.text||e,text:o.text||"",placeholder:o.placeholder||o.text||"请选择",icon:o.icon||"",width:Number(o.width)>0?Number(o.width):0,searchable:!!o.searchable,note:o.note?String(o.note):"",emptyText:o.emptyText?String(o.emptyText):"",cache:o.cache!==!1,keepValue:o.keepValue!==!1,multiple:!1,options:o.options??null,load:typeof o.load=="function"?o.load:null,url:o.url?String(o.url):"",fetchOptions:o.fetchOptions&&typeof o.fetchOptions=="object"?o.fetchOptions:{},pick:typeof o.pick=="function"?o.pick:null,link:o.link??null,insert:o.insert===void 0?"auto":o.insert,onSelect:typeof o.onSelect=="function"?o.onSelect:null,onClick:typeof o.onClick=="function"?o.onClick:null,active:typeof o.active=="function"?o.active:null,enabled:typeof o.enabled=="function"?o.enabled:null}:null}function Be(o){return Array.isArray(o)?o.map(He).filter(Boolean):[]}function jt(){return{items:null,loaded:!1,loading:null,value:null,controller:null,error:"",gen:0,external:!1}}async function Ft(o,e,t){return o.load?G(await o.load(e)):o.url?G(await Dt(o,e,t)):G(o.options)}async function Dt(o,e,t){var c;const i=o.fetchOptions,n=i.fetch||(typeof fetch=="function"?fetch.bind(globalThis):null);if(!n)throw new Error("当前环境无 fetch,请改用 load 函数提供数据");(c=t.controller)==null||c.abort();const r=typeof AbortController=="function"?new AbortController:null;t.controller=r;const s=Number(i.timeout)>0?Number(i.timeout):Pt,a=setTimeout(()=>r==null?void 0:r.abort(),s);try{const d=await n(o.url,{method:i.method||"GET",headers:i.headers,body:i.body,credentials:i.credentials,signal:r?r.signal:void 0});if(!d||d.ok===!1)throw new Error(`接口返回 ${d&&d.status?d.status:"异常"}`);const h=i.parser?await i.parser(d):await d.json();return o.pick?o.pick(h,e):h}catch(d){throw d&&d.name==="AbortError"?new Error(`请求超时(${s}ms)或被取消`):d}finally{clearTimeout(a),t.controller===r&&(t.controller=null)}}function It(o,e,t,{force:i=!1}={}){if(!i&&t.external&&t.items||!i&&o.cache&&t.items)return Promise.resolve(t.items);if(!i&&t.loading)return t.loading;const n=t.gen,r=Ft(o,e,t).then(s=>n!==t.gen?t.items:(t.items=s,t.loaded=!0,t.error="",s)).catch(s=>{if(n!==t.gen)return t.items;throw t.error=s&&s.message?s.message:String(s),s}).finally(()=>{t.loading===r&&(t.loading=null)});return t.loading=r,r}function qt(o,e){return o.gen+=1,o.items=G(e),o.loaded=!0,o.error="",o.external=!0,he(o),o.loading=null,o.items}function he(o){var e;(e=o.controller)==null||e.abort(),o.controller=null}function pe(o,e){return String(o).replace(/\{(\w+)\}/g,(t,i)=>{if(e[i]!==void 0&&e[i]!==null)return String(e[i]);const n=e.raw&&e.raw[i];return n==null?t:String(n)})}function ue(o,e,t){return typeof o=="function"?o(e,t):o}function $e(o,e,t){const i=o.link;let n=null;if(typeof i=="function"?n=i(e,t):typeof i=="string"?n={url:i}:i&&typeof i=="object"?n=i:(i===!0||e.url)&&(n={url:e.url}),!n)return null;typeof n=="string"&&(n={url:n});const r=W(pe(String(ue(n.url,e,t)??""),e));if(!r||!Y(r))return null;const s=ue(n.text,e,t),a=ue(n.title,e,t),c=n.mode==="open"?"open":"insert",d=n.target==="_self"||n.target===!1?"_self":"_blank";return{mode:c,url:r,text:s==null||s===""?e.label:pe(String(s),e),target:d,title:a?pe(String(a),e):""}}function Re(o,e){o.commands.insertHTML(ce(e))}async function Ut(o,e,t,i){o.restoreSelection();const n=$e(e,i,o),r={editor:o,item:i,link:n,insertLink:d=>Oe(o,{...n,...d}),insertHtml:d=>o.commands.insertHTML(String(d)),insertText:d=>Re(o,d),open:(d,h)=>Pe(d||n&&n.url,h||n&&n.target)};let s="none",a=!1;e.onSelect&&(a=await e.onSelect(i,r)===!1),a||(s=Wt(o,e,i,n)),e.keepValue&&(t.value=i);const c={name:e.name,item:i,link:n,action:s,editor:o};return o.emit("customselect",c),c}function Wt(o,e,t,i){const n=e.insert;return n===!1||n==="none"?"none":i&&i.mode==="open"?(Pe(i.url,i.target),"open"):n==="link"||n==="auto"&&i?i?(Oe(o,i),"link"):"none":n==="html"||n==="auto"&&t.html?t.html?(o.commands.insertHTML(t.html),"html"):"none":(Re(o,t.label),"text")}function Oe(o,e){o.commands.createLink({url:e.url,text:e.text,target:e.target!=="_self"})}function Pe(o,e="_blank"){!o||!Y(o)||(e==="_self"?window.location.href=o:window.open(o,"_blank","noopener,noreferrer"))}const fe='<svg class="ke-caret" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><path d="m6 9 6 6 6-6"/></svg>',Ne="keditor.toolbarScrollHint",_t='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.1" stroke-linecap="round" stroke-linejoin="round"><path d="M8 7 4 12l4 5"/><path d="M16 7l4 5-4 5"/><path d="M4 12h16"/></svg>',me=[{value:"p",label:"正文",desc:"默认段落 · 17px,正文内容都用它",sample:"正文示例文字",sampleClass:"s-body"},{value:"h1",label:"标题一",desc:"大标题 · 22px 加粗,全文主标题(建议只用一次)",sample:"标题一示例",sampleClass:"s-h1"},{value:"h2",label:"标题二",desc:"章节标题 · 20px 加粗,划分小节",sample:"标题二示例",sampleClass:"s-h2"},{value:"h3",label:"标题三",desc:"小标题 · 18px 加粗,章节内的层级",sample:"标题三示例",sampleClass:"s-h3"}],Vt=[12,14,15,16,17,18,20,22,24,28,32],Q=["undo","redo","|","heading","fontsize","|","bold","italic","underline","strike","|","foreColor","backColor","|","alignLeft","alignCenter","alignRight","alignJustify","|","ul","ol","quote","|","link","image","video","table","code","hr","clear",":tail","source","fullscreen"],je={undo:{icon:"undo",title:"撤销 (⌘/Ctrl+Z)",run:o=>o.undo(),active:o=>!!o.canUndo,enabled:o=>o.canUndo},redo:{icon:"redo",title:"重做 (⌘/Ctrl+Shift+Z)",run:o=>o.redo(),active:o=>!!o.canRedo,enabled:o=>o.canRedo},bold:{glyph:["B","ke-glyph"],title:"加粗 (⌘/Ctrl+B)",cmd:"bold",active:o=>o.bold},italic:{glyph:["I","ke-glyph ke-glyph-i"],title:"斜体 (⌘/Ctrl+I)",cmd:"italic",active:o=>o.italic},underline:{glyph:["U","ke-glyph ke-glyph-u"],title:"下划线 (⌘/Ctrl+U)",cmd:"underline",active:o=>o.underline},strike:{glyph:["S","ke-glyph ke-glyph-s"],title:"删除线",cmd:"strike",active:o=>o.strikeThrough},alignLeft:{icon:"alignLeft",title:"左对齐",run:o=>o.commands.setAlign("left"),active:o=>o.align==="left"},alignCenter:{icon:"alignCenter",title:"居中",run:o=>o.commands.setAlign("center"),active:o=>o.align==="center"},alignRight:{icon:"alignRight",title:"右对齐",run:o=>o.commands.setAlign("right"),active:o=>o.align==="right"},alignJustify:{icon:"alignJustify",title:"两端对齐",run:o=>o.commands.setAlign("justify"),active:o=>o.align==="justify"},ul:{icon:"ul",title:"无序列表",run:o=>o.commands.toggleList("unordered"),active:o=>o.ul},ol:{icon:"ol",title:"有序列表",run:o=>o.commands.toggleList("ordered"),active:o=>o.ol},quote:{icon:"quote",title:"引用",run:o=>o.commands.toggleBlockquote(),active:o=>o.block==="blockquote"},link:{icon:"link",title:"插入链接",run:o=>o.toolbar.openLink(),active:o=>o.link,toggles:!0},image:{icon:"image",title:"图片(本地上传 / 网络链接)",run:o=>o.toolbar.openMedia("image"),toggles:!0},video:{icon:"video",title:"视频(本地上传 / 网络链接,支持分片上传)",run:o=>o.toolbar.openMedia("video"),toggles:!0},table:{icon:"table",title:"插入表格",run:o=>o.toolbar.openTable(),toggles:!0},code:{icon:"code",title:"代码块",run:o=>o.commands.insertCodeBlock()},hr:{icon:"hr",title:"分割线",run:o=>o.commands.insertDivider()},clear:{icon:"clear",title:"清除格式",run:o=>o.commands.clearFormat()},source:{icon:"source",title:"查看 / 编辑 HTML 源码(⌘/Ctrl+Shift+K)",text:"源码",run:o=>o.toggleSource(),active:o=>o.source},preview:{icon:"preview",title:"预览效果(手机 / 平板 / 电脑宽度)",text:"预览",run:o=>o.togglePreview(),active:o=>o.preview},fullscreen:{icon:"expand",title:"全屏编辑",text:"全屏",run:o=>o.toggleFullscreen(),active:o=>o.fullscreen},foreColor:{pop:"fore",title:"字体颜色",toggles:!0,swatch:"fore"},backColor:{pop:"back",title:"背景高亮色",toggles:!0,swatch:"back"}};class Kt{constructor(e,t=Q,i=[]){this.editor=e,this.buttons=new Map,this.custom=new Map,this.colorState={foreColor:"#3f3f3f",backColor:"#f6c344"},this.recent={foreColor:[],backColor:[]},this.el=e.tbEl;for(const n of i)this.registerCustom(n);this.build(t),this.setupScrollHints()}build(e){const t=l("div.ke-tb-group");this.el.appendChild(t),this.groupEl=t,this.tailEl=null;const i=()=>this.tailEl||t;for(const n of e){if(n==="|"){i().appendChild(l("span.ke-tb-sep"));continue}if(n===":tail"){this.tailEl=l("div.ke-tb-tail"),this.el.appendChild(this.tailEl);continue}if(this.custom.has(n)){const s=this.custom.get(n);s.button=this.buildCustomButton(s),i().appendChild(s.button);continue}if(n==="heading"){i().appendChild(this.buildHeading());continue}if(n==="fontsize"){i().appendChild(this.buildFontSize());continue}const r=je[n];r&&i().appendChild(this.buildButton(n,r))}for(const[n,r]of this.custom)r.button||(r.button=this.buildCustomButton(r),this.insertButton(r.button,r.spec.position))}buildButton(e,t){const i=l("button.ke-btn",{type:"button",title:t.title,"data-k-item":e,onclick:n=>{var r;n.preventDefault(),t.pop?this.toggleColor(e,i):t.cmd?this.editor.commands.toggleMark(t.cmd):(r=t.run)==null||r.call(t,this.editor),t.toggles||this.editor.popover.close()}});if(t.icon&&(i.innerHTML=M(t.icon)),t.text&&i.appendChild(l("span.ke-btn-text",{text:t.text})),t.glyph){const[n,r]=t.glyph;i.appendChild(l("span",{class:r,text:n}))}if(t.swatch){const n=t.swatch==="fore"?this.colorState.foreColor:this.colorState.backColor,r=l("span",{class:t.swatch==="fore"?"ke-glyph ke-glyph-a":"ke-glyph ke-glyph-a ke-glyph-hl"});r.appendChild(l("span",{text:"A"})),i.appendChild(r),t.swatch==="fore"&&i.appendChild(l("span",{class:"ke-dot"})),this.paintButton(i,t.swatch,n),i.dataset.kPop=t.swatch==="fore"?"foreColor":"backColor"}return t.toggles&&!t.swatch&&(i.dataset.kPop=e),this.buttons.set(e,i),i}paintButton(e,t,i){!e||!i||e.style.setProperty(t==="fore"?"--ke-fore":"--ke-back",i)}openPop(e,t,i={}){this.editor.saveSelection(),this.editor.popover.open(e,t,{align:"start",...i,onClose:()=>{var n;e.classList.remove("ke-is-open"),(n=i.onClose)==null||n.call(i)}}),e.classList.add("ke-is-open")}togglePop(e,t,i,n={}){const r=this.editor.popover;if(r.isOpen&&r.anchor===t){r.close();return}this.openPop(t,i,n)}buildHeading(){const e=me[0],t=l("button.ke-btn.ke-btn-label",{type:"button",title:"段落样式:正文 / 标题一 / 标题二 / 标题三","data-k-item":"heading",dataset:{kPop:"heading"},onclick:i=>{i.preventDefault(),this.togglePop("heading",t,()=>ct(me,{value:this.editor.getState().block,onPick:n=>{this.editor.restoreSelection(),this.editor.commands.setHeading(n),this.editor.popover.close(),this.editor.refresh()}}))}});return t.innerHTML=`<span class="ke-btn-text">${e.label}</span>${fe}`,this.headingEl=t,this.buttons.set("heading",t),t}buildFontSize(){const e=l("button.ke-btn.ke-btn-label",{type:"button",title:"字号","data-k-item":"fontsize",dataset:{kPop:"fontsize"},onclick:t=>{t.preventDefault(),this.togglePop("fontsize",e,()=>dt(Vt,{value:this.editor.getState().fontSize,onPick:i=>{this.editor.restoreSelection(),this.editor.commands.setFontSize(Number(i)),this.editor.popover.close(),this.editor.refresh()}}))}});return e.innerHTML=`<span class="ke-btn-text">字号</span>${fe}`,this.fontSizeEl=e,this.buttons.set("fontsize",e),e}registerCustom(e){const t=He(e);if(!t)return null;const i=this.custom.get(t.name),n={spec:t,rt:i?i.rt:jt(),button:i?i.button:null};return this.custom.set(t.name,n),n}buildCustomButton(e){const{spec:t}=e,i=t.type==="select",n=l("button.ke-btn",{type:"button",class:i?"ke-btn-label ke-btn-custom":"ke-btn-custom",title:t.title,"data-k-item":t.name,dataset:{kPop:t.name,kCustom:t.name},onclick:r=>{r.preventDefault(),i?this.openCustom(t.name):this.runCustomButton(t)}});return t.icon&&(n.innerHTML=/</.test(t.icon)?t.icon:M(t.icon)),i?(n.appendChild(l("span.ke-btn-text",{text:t.text||t.placeholder})),n.insertAdjacentHTML("beforeend",fe)):t.text&&n.appendChild(l("span.ke-btn-text",{text:t.text})),this.syncCustomLabel(t.name,n),n}syncCustomLabel(e,t){const i=this.custom.get(e),n=t||(i==null?void 0:i.button);if(!i||!n)return;const{spec:r,rt:s}=i;if(r.type!=="select")return;const a=n.querySelector(".ke-btn-text");if(!a)return;const c=s.value;a.textContent=c?c.label:r.text||r.placeholder,n.title=c?`${r.title}:${c.label}`:r.title,n.classList.toggle("ke-has-value",!!c)}openCustom(e){const t=this.custom.get(e);if(!t)return;this.revealButton(t.button);const{spec:i,rt:n}=t,r=!!(i.load||i.url),s=({force:a}={})=>It(i,this.editor,n,{force:a});this.togglePop(e,t.button,()=>kt({title:i.title,note:i.note||"",searchable:i.searchable,width:i.width,remote:r,value:n.value?n.value.value:"",emptyText:i.emptyText,load:s,reload:s,linkOf:a=>$e(i,a,this.editor),onPick:a=>this.pickCustom(e,a)}))}async pickCustom(e,t){const i=this.custom.get(e);if(i){this.editor.popover.close();try{await Ut(this.editor,i.spec,i.rt,t)}catch(n){this.editor.reportError("custombutton",n)}this.syncCustomLabel(e),this.editor.refresh()}}async runCustomButton(e){this.editor.popover.close();try{e.onClick&&await e.onClick({editor:this.editor,name:e.name}),this.editor.emit("customclick",{name:e.name,editor:this.editor})}catch(t){this.editor.reportError("custombutton",t)}this.editor.refresh()}addButton(e,t={}){var r;const i=this.registerCustom(e);if(!i)return null;i.button&&i.button.remove(),i.button=this.buildCustomButton(i);const n=t.at!==void 0?t.at:de(t)??i.spec.position;return this.insertButton(i.button,n,{withSep:n==null}),this.revealButton(i.button),(r=this.syncScrollHints)==null||r.call(this),i.button}buttonNodes(){const e=[];for(const t of[this.groupEl,this.tailEl])if(t)for(const i of t.children)i.dataset&&i.dataset.kItem&&e.push(i);return e}slotOf(e){const t={parent:this.groupEl||this.el,ref:null};if(e==="tail")return{parent:this.tailEl||this.groupEl||this.el,ref:null};if(e==null||e==="end")return t;if(e==="start"){const a=this.buttonNodes()[0];return a?{parent:a.parentElement,ref:a}:t}const i=this.buttonNodes();if(typeof e=="number"){const a=i[Math.max(0,Math.floor(e))];if(a)return{parent:a.parentElement,ref:a};const c=i[i.length-1];return c?{parent:c.parentElement,ref:null}:t}const n=!!(e&&typeof e=="object"&&e.after),r=typeof e=="string"?e:String((n?e.after:e.before)||""),s=i.find(a=>a.dataset.kItem===r);return s?{parent:s.parentElement,ref:n?s.nextElementSibling||null:s}:t}insertButton(e,t,{withSep:i}={}){const{parent:n,ref:r}=this.slotOf(t);!n||!e||(i&&!r&&n.appendChild(l("span.ke-tb-sep")),n.insertBefore(e,r||null))}moveButton(e,t){var n,r;const i=this.buttonNodes().find(s=>s.dataset.kItem===String(e));return i?(i.remove(),this.insertButton(i,t===void 0?((n=this.custom.get(String(e)))==null?void 0:n.spec.position)??null:t),this.revealButton(i),(r=this.syncScrollHints)==null||r.call(this),!0):!1}revealButton(e){const t=this.el;if(!t||!e||!e.isConnected)return;const i=t.scrollWidth-t.clientWidth;if(i<=1)return;const n=this.tailEl?this.tailEl.offsetWidth:0,r=e.offsetLeft,s=r+e.offsetWidth,a=t.scrollLeft+t.clientWidth-n;s>a-4?t.scrollLeft=Math.min(i,s-t.clientWidth+n+10):r<t.scrollLeft+4&&(t.scrollLeft=Math.max(0,r-10))}removeButton(e){var r,s,a,c;const t=this.custom.get(e);if(!t)return!1;he(t.rt),this.editor.popover.anchor===t.button&&this.editor.popover.close();const i=(r=t.button)==null?void 0:r.previousElementSibling,n=(s=t.button)==null?void 0:s.nextElementSibling;return(a=t.button)==null||a.remove(),i&&i.classList.contains("ke-tb-sep")&&(!n||n.classList.contains("ke-tb-sep"))&&i.remove(),this.buttons.delete(e),this.custom.delete(e),(c=this.syncScrollHints)==null||c.call(this),!0}setButtonOptions(e,t){const i=this.custom.get(e);if(!i)return null;const n=qt(i.rt,t);return this.editor.popover.isOpen&&this.editor.popover.anchor===i.button&&(this.editor.popover.close(),this.openCustom(e)),n}getButtonValue(e){const t=this.custom.get(e);return t?t.rt.value:null}setButtonValue(e,t){const i=this.custom.get(e);if(!i)return null;const r=(i.rt.items||[]).find(s=>String(s.value)===String(t))||null;return i.rt.value=r,this.syncCustomLabel(e),r}toggleColor(e,t){const i=e==="foreColor"?"fore":"back";this.togglePop(e,t,()=>at({title:i==="fore"?"字体颜色":"背景高亮色",kind:i,value:this.colorState[e],recents:this.recent[e],onPick:n=>this.applyColor(e,i,n,t),onClear:()=>this.applyColor(e,i,null,t)}),{onClose:()=>t.classList.remove("ke-is-active")})}applyColor(e,t,i,n){this.editor.restoreSelection(),i&&(this.colorState[e]=i,this.recent[e]=[i,...this.recent[e].filter(r=>r.toLowerCase()!==i.toLowerCase())].slice(0,8),this.paintButton(n,t,i)),this.editor.commands.setColor(t,i),this.editor.popover.close()}openTable(){const e=this.buttons.get("table");this.togglePop("table",e,()=>ht((t,i)=>{this.editor.restoreSelection(),this.editor.commands.insertTable(t,i),this.editor.popover.close()}))}openLink(){const e=this.buttons.get("link"),t=this.editor.getState(),i=t.linkUrl;this.togglePop("link",e,()=>ft({url:i||"",text:i?"":t.selectionText||"",target:i?t.linkTarget:!0,onCancel:()=>this.editor.popover.close(),onRemove:i?()=>{this.editor.restoreSelection(),this.editor.commands.removeLink(),this.editor.popover.close()}:null,onSubmit:({url:n,text:r,target:s})=>{this.editor.restoreSelection(),this.editor.commands.createLink({url:W(n),text:r,target:s}),this.editor.popover.close()}}))}openMedia(e){const t=this.buttons.get(e),i=this.editor,n=i.options;this.togglePop(e,t,()=>pt(e,{multiple:e==="image",maxText:`${e==="image"?"图片":"视频"}上限 ${Gt(e==="image"?n.maxImageSize:n.maxVideoSize)}`,hint:e==="image"?"支持 PNG / JPG / GIF / WebP / SVG":"支持 MP4 / MOV / WebM,大文件自动分片",onFiles:r=>{i.popover.close(),r&&r.length?i.media.addFiles([...r]):i.media.pickFiles(e)},onUrl:({url:r,name:s})=>{i.popover.close(),i.restoreSelection(),i.media.insertFromUrl(e,r,s)}}))}refresh(e){var t;for(const[i,n]of this.buttons){const r=je[i];if(!r)continue;const s=((t=r.active)==null?void 0:t.call(r,e))||!1;(n.dataset.kPop||!r.pop)&&n.classList.toggle("ke-is-active",s),r.enabled&&(n.disabled=!r.enabled(e))}for(const[i,n]of this.custom){const{spec:r,button:s}=n;s&&(r.active&&s.classList.toggle("ke-is-active",!!r.active(e,this.editor)),r.enabled&&(s.disabled=!r.enabled(e,this.editor)),r.type==="select"&&this.syncCustomLabel(i))}if(this.headingEl){const i=me.find(r=>r.value===e.block),n=this.headingEl.querySelector(".ke-btn-text");n&&(n.textContent=i?i.label:"正文"),this.headingEl.title=i?`${i.label}:${i.desc}`:"段落样式"}if(this.fontSizeEl){const i=this.fontSizeEl.querySelector(".ke-btn-text");i&&(i.textContent=e.fontSize?`${e.fontSize}px`:"字号")}if(e.linkUrl){const i=this.buttons.get("link");i==null||i.classList.add("ke-is-active")}}setupScrollHints(){const e=this.el,t=this.editor.el;e.isConnected&&(this.scrollFades=l("div.ke-tb-fades",{"aria-hidden":"true"},[l("i.ke-tb-fade ke-tb-fade-l")]),e.insertAdjacentElement("afterend",this.scrollFades),this.syncScrollHints=()=>{if(!e.isConnected||!t.isConnected)return;const i=e.scrollWidth-e.clientWidth,n=i>1,r=e.scrollLeft;t.classList.toggle("ke-tb-scrollable",n),t.classList.toggle("ke-tb-can-l",n&&r>1),t.classList.toggle("ke-tb-can-r",n&&r<i-1),t.style.setProperty("--ke-tb-h",`${e.offsetHeight}px`),n&&!this.hintSettled&&this.showScrollHint()},this.onTbScroll=()=>{this.syncScrollHints(),this.hideScrollHint()},e.addEventListener("scroll",this.onTbScroll,{passive:!0}),typeof ResizeObserver<"u"&&(this.tbRO=new ResizeObserver(()=>this.syncScrollHints()),this.tbRO.observe(e)),this.onTbPointerDown=i=>{this.hideScrollHint(),this.startDragScroll(i)},e.addEventListener("pointerdown",this.onTbPointerDown),requestAnimationFrame(this.syncScrollHints))}startDragScroll(e){const t=this.el,i=this.editor.el;if(e.button!==0||e.pointerType!=="mouse"||t.scrollWidth<=t.clientWidth+1||e.target.closest("input, textarea, select"))return;const n=e.clientX,r=t.scrollLeft;let s=!1;const a=d=>{var p;const h=d.clientX-n;if(!s){if(Math.abs(h)<5)return;s=!0;try{t.setPointerCapture(e.pointerId)}catch{}i.classList.add("ke-tb-dragging"),(p=this.editor.popover)==null||p.close()}d.preventDefault(),t.scrollLeft=r-h},c=()=>{if(t.removeEventListener("pointermove",a),t.removeEventListener("pointerup",c),t.removeEventListener("pointercancel",c),i.classList.remove("ke-tb-dragging"),!s)return;try{t.releasePointerCapture(e.pointerId)}catch{}const d=u=>{u.preventDefault(),u.stopPropagation(),h()},h=()=>{clearTimeout(p),t.removeEventListener("click",d,!0)},p=setTimeout(h,400);t.addEventListener("click",d,!0)};t.addEventListener("pointermove",a),t.addEventListener("pointerup",c),t.addEventListener("pointercancel",c)}showScrollHint(){this.hintSettled=!0;let e=!1;try{e=localStorage.getItem(Ne)==="1"}catch{}e||(this.hintEl=l("div.ke-tb-hint",{"aria-hidden":"true"},[l("span.ke-tb-hint-ico",{html:_t}),l("span",{text:"工具栏可左右滑动"})]),this.editor.el.appendChild(this.hintEl),this.hintTimer=setTimeout(()=>this.hideScrollHint(),3800))}hideScrollHint(){this.hintTimer&&(clearTimeout(this.hintTimer),this.hintTimer=null);const e=this.hintEl;if(e){this.hintEl=null;try{localStorage.setItem(Ne,"1")}catch{}e.classList.add("ke-is-out"),setTimeout(()=>e.remove(),260)}}destroy(){var i,n,r;const e=this.el;this.tbRO&&(this.tbRO.disconnect(),this.tbRO=null),this.hintTimer&&(clearTimeout(this.hintTimer),this.hintTimer=null),this.onTbScroll&&e.removeEventListener("scroll",this.onTbScroll),this.onTbPointerDown&&e.removeEventListener("pointerdown",this.onTbPointerDown);for(const s of this.custom.values())he(s.rt);this.custom.clear(),(i=this.scrollFades)==null||i.remove(),(n=this.hintEl)==null||n.remove(),this.scrollFades=null,this.hintEl=null;const t=(r=this.editor)==null?void 0:r.el;t&&(t.classList.remove("ke-tb-scrollable","ke-tb-can-l","ke-tb-can-r","ke-tb-dragging"),t.style.removeProperty("--ke-tb-h")),e.innerHTML="",this.buttons.clear()}}function Gt(o){if(!o)return"不限";const e=o/1024/1024;return e>=1?`${Math.round(e)}MB`:`${Math.round(o/1024)}KB`}function z(o){const e=window.getSelection();if(!e||e.rangeCount===0)return null;const t=e.getRangeAt(0);return o.contains(t.commonAncestorContainer)?t:null}function Fe(o){const e=window.getSelection();if(!e||e.rangeCount===0)return null;const t=e.getRangeAt(0);if(!o.contains(t.startContainer))return null;let i=0;return document.createTreeWalker(o,NodeFilter.SHOW_TEXT,{acceptNode(s){return s===t.startContainer?NodeFilter.FILTER_ACCEPT:(i+=s.textContent.length,NodeFilter.FILTER_SKIP)}}).nextNode()?i+t.startOffset:t.startContainer===o?0:null}function Xt(o,e){if(e==null)return;const t=window.getSelection();let i=Math.max(0,e);const n=document.createTreeWalker(o,NodeFilter.SHOW_TEXT);let r=n.nextNode(),s=null;for(;r;){const a=r.textContent.length;if(i<=a){try{t.setBaseAndExtent(r,i,r,i)}catch{}return}i-=a,s=r,r=n.nextNode()}if(s)try{t.setBaseAndExtent(s,s.textContent.length,s,s.textContent.length)}catch{}}function P(o,e,{inline:t=!1,selectAfter:i=!0}={}){o.focus();const n=z(o);if(!n)return o.appendChild(e),ee(o),e;if(n.collapsed||n.deleteContents(),t)n.insertNode(e);else{const a=N(n.startContainer,o);!a||a===o?o.appendChild(e):a.after(e)}const r=document.createRange();r.setStartAfter(e),r.collapse(!0);const s=window.getSelection();return s.removeAllRanges(),s.addRange(r),ee(o),i&&s.rangeCount===0&&o.focus(),e}function ee(o){const e=o.lastElementChild;if(!e){o.appendChild(document.createElement("p"));return}if(/^(IMG|VIDEO|IFRAME)$/.test(e.tagName)||e.dataset.kmedia!==void 0){const t=document.createElement("p");t.appendChild(document.createElement("br")),o.appendChild(t)}}function N(o,e){let t=o;for(;t&&t!==e;){if(t.nodeType===1&&/^(P|DIV|H[1-6]|LI|BLOCKQUOTE|PRE|SECTION|TD|TH)$/.test(t.tagName))return t;t=t.parentNode}return null}class Jt{constructor(e){this.editor=e,this.root=e.root}exec(e,t=null){this.editor.focus(),document.execCommand("styleWithCSS",!1,!0),document.execCommand("defaultParagraphSeparator",!1,"p");const i=document.execCommand(e,!1,t);return this.editor.afterEdit(),i}queryState(e){try{return document.queryCommandState(e)}catch{return!1}}queryValue(e){try{return document.queryCommandValue(e)}catch{return""}}hasSelection(){const e=z(this.root);return!!(e&&!e.collapsed)}toggleMark(e){const i={bold:"bold",italic:"italic",underline:"underline",strike:"strikeThrough"}[e];i&&(this.exec(i),this.root.querySelectorAll('span[style=""]').forEach(n=>n.replaceWith(...n.childNodes)))}setFontSize(e){this.editor.focus(),document.execCommand("styleWithCSS",!1,!1);const t=`__ke_fs_${ie()}__`;this.root.setAttribute("data-ke-marker",t),document.execCommand("fontSize",!1,"7"),this.root.removeAttribute("data-ke-marker"),this.root.querySelectorAll('font[size="7"]').forEach(i=>{const n=document.createElement("span");for(n.style.fontSize=`${e}px`;i.firstChild;)n.appendChild(i.firstChild);i.replaceWith(n)}),this.root.querySelectorAll("span").forEach(i=>{/xx-large/i.test(i.style.fontSize)&&(i.style.fontSize=`${e}px`)}),document.execCommand("styleWithCSS",!1,!0),this.editor.afterEdit()}setColor(e,t){this.editor.focus(),document.execCommand("styleWithCSS",!1,!0),t||(t=e==="fore"?"#3f3f3f":"transparent"),document.execCommand(e==="fore"?"foreColor":"hiliteColor",!1,t)||document.execCommand(e==="fore"?"foreColor":"backColor",!1,t),e==="back"&&t==="transparent"&&this.root.querySelectorAll('[style*="background-color"]').forEach(n=>{/background-color:\s*transparent|rgba\(0, 0, 0, 0\)/i.test(n.getAttribute("style")||"")&&(n.style.backgroundColor="",n.getAttribute("style").trim()||n.replaceWith(...n.childNodes))}),this.editor.afterEdit()}setAlign(e){var c,d;const t=(c=this.editor.bubble)==null?void 0:c.node;if(t&&((d=t.dataset)==null?void 0:d.kMedia)==="image"&&e!=="justify"){const h=t.querySelector("img");if(h){ne(h,e),this.editor.commitHistory(),this.editor.bubble.position();return}}const n={left:"justifyLeft",center:"justifyCenter",right:"justifyRight",justify:"justifyFull"}[e];if(!n)return;this.editor.focus();const r=z(this.root),s=N((r==null?void 0:r.commonAncestorContainer)||this.root,this.root);document.execCommand("styleWithCSS",!1,!0),document.execCommand(n);const a=s||this.root.firstElementChild;a&&/^(FIGURE|DIV|VIDEO)/.test(a.tagName||"")&&(a.style.textAlign=e),this.editor.afterEdit()}toggleList(e){this.exec(e==="ordered"?"insertOrderedList":"insertUnorderedList")}setHeading(e){const t=e?`<${e}>`:"<p>";this.exec("formatBlock",t)}toggleBlockquote(){const e=z(this.root),t=N((e==null?void 0:e.commonAncestorContainer)||this.root,this.root);t&&t.tagName==="BLOCKQUOTE"?this.exec("formatBlock","<p>"):this.exec("formatBlock","<blockquote>")}createLink({url:e,text:t="",target:i=!1}){var a,c;this.editor.focus();const n=z(this.root),r=n&&!n.collapsed,s=t||(r?n.toString():e);if(r)document.execCommand("createLink",!1,e),(c=(a=n.commonAncestorContainer.parentElement)==null?void 0:a.closest)==null||c.call(a,"a"),this.root.querySelectorAll(`a[href="${Zt(e)}"]`).forEach(d=>{i?(d.setAttribute("target","_blank"),d.setAttribute("rel","noopener noreferrer")):d.removeAttribute("target")});else{const d=l("a",{href:e},[s]);i&&(d.setAttribute("target","_blank"),d.setAttribute("rel","noopener noreferrer")),P(this.root,d,{inline:!0})}this.editor.afterEdit()}removeLink(){const e=z(this.root);Yt(e,this.root).forEach(i=>i.replaceWith(...i.childNodes)),this.editor.afterEdit()}insertTable(e,t){const i=document.createElement("table"),n=document.createElement("tbody");for(let r=0;r<t;r+=1){const s=document.createElement("tr");for(let a=0;a<e;a+=1){const c=document.createElement(r===0?"th":"td");c.innerHTML="<br>",s.appendChild(c)}n.appendChild(s)}i.appendChild(n),P(this.root,i),this.exec("insertHTML",""),this.editor.afterEdit()}insertCodeBlock(e=""){const t=document.createElement("pre"),i=document.createElement("code");i.textContent=e||"// 在这里输入代码",t.appendChild(i),P(this.root,t),this.editor.afterEdit()}insertDivider(){const e=document.createElement("hr");P(this.root,e),this.editor.afterEdit()}insertHTML(e,{clean:t=!0}={}){const i=t?K(e):e;this.editor.focus();const n=z(this.root);if(n){n.deleteContents();const r=document.createElement("div");r.innerHTML=i;const s=document.createDocumentFragment();for(;r.firstChild;)s.appendChild(r.firstChild);const a=s.lastChild;if(n.insertNode(s),a){const c=document.createRange();c.setStartAfter(a.nodeType===3?a:a.lastChild||a),c.collapse(!0);const d=window.getSelection();d.removeAllRanges(),d.addRange(c)}}else this.root.insertAdjacentHTML("beforeend",i);this.editor.afterEdit()}clearFormat(){if(this.editor.focus(),this.hasSelection()){document.execCommand("removeFormat"),document.execCommand("unlink");const e=z(this.root),t=N(e==null?void 0:e.commonAncestorContainer,this.root);t&&/^(H[1-6]|BLOCKQUOTE|PRE)$/.test(t.tagName)&&this.exec("formatBlock","<p>"),this.stripInlineStylesInRange(e)}else{const e=z(this.root),t=N((e==null?void 0:e.commonAncestorContainer)||this.root,this.root);if(t){const i=t.innerHTML,n=document.createElement("p");n.innerHTML=K(i,{allowEmpty:!0}),n.innerHTML=n.innerHTML.replace(/<(?!br|img)[^>]+>/gi,""),t.replaceWith(n)}}this.editor.afterEdit()}stripInlineStylesInRange(e){if(!e)return;const t=[],i=document.createTreeWalker(e.commonAncestorContainer,NodeFilter.SHOW_ELEMENT);let n=i.currentNode;for(;n;)e.intersectsNode(n)&&n.nodeType===1&&t.push(n),n=i.nextNode();t.forEach(r=>{r!==this.root&&(r.removeAttribute("style"),/^(SPAN|FONT)$/.test(r.tagName)&&!r.attributes.length&&r.replaceWith(...r.childNodes))})}currentBlock(){var i;const e=z(this.root),t=N((e==null?void 0:e.commonAncestorContainer)||this.root,this.root);return((i=t==null?void 0:t.tagName)==null?void 0:i.toLowerCase())||"p"}currentFontSize(){const e=z(this.root);if(!e)return"";let t=e.startContainer;for(;t&&t!==this.root;){if(t.nodeType===1&&t.style.fontSize)return t.style.fontSize.replace("px","");t=t.parentNode}return""}}function Yt(o,e){var s,a,c;if(!o)return[];const t=new Set;let n=o.startContainer.nodeType===1&&((a=(s=o.startContainer).querySelector)==null?void 0:a.call(s,"a"))||o.startContainer;for(;n&&n!==e;)n.tagName==="A"&&t.add(n),n=n.parentNode;try{(c=o.querySelectorAll)==null||c.call(o,"a").forEach(d=>t.add(d))}catch{}const r=o.commonAncestorContainer;return r.nodeType===1&&r.querySelectorAll("a").forEach(d=>o.intersectsNode(d)?t.add(d):null),[...t]}function Zt(o){var e;return(e=window.CSS)!=null&&e.escape?CSS.escape(o):String(o).replace(/["\\]/g,"\\$&")}class Qt{constructor(e,{limit:t=60,delay:i=400}={}){this.root=e,this.limit=t,this.delay=i,this.stack=[],this.index=-1,this.timer=null,this.locked=!1,this.lastHtml=e.innerHTML}snapshot(e=!1){clearTimeout(this.timer);const t=()=>{const i=this.root.innerHTML;if(i===this.lastHtml)return;this.lastHtml=i;const n={html:i,offset:Fe(this.root)};this.stack=this.stack.slice(0,this.index+1),this.stack.push(n),this.stack.length>this.limit&&this.stack.shift(),this.index=this.stack.length-1};e?t():this.timer=setTimeout(t,this.delay)}flush(){clearTimeout(this.timer),this.snapshot(!0)}apply(e,t){this.locked=!0,this.root.innerHTML=e,this.lastHtml=e,t!=null&&Xt(this.root,t),this.locked=!1}canUndo(){return this.index>0}canRedo(){return this.index>=0&&this.index<this.stack.length-1}undo(){if(!this.canUndo())return!1;clearTimeout(this.timer),this.index-=1;const e=this.stack[this.index];return this.apply(e.html,this.currentOffset(e,"undo")),this.lastHtml=e.html,!0}redo(){if(!this.canRedo())return!1;const e=this.stack[this.index+1];return this.index+=1,this.apply(e.html,this.currentOffset(e,"redo")),this.lastHtml=e.html,!0}currentOffset(e){const t=Fe(this.root);return e.offset}reset(e){clearTimeout(this.timer),this.stack=[{html:e,offset:0}],this.index=0,this.lastHtml=e}destroy(){clearTimeout(this.timer),this.stack=[]}}const ei=/\.(jpe?g|png|gif|webp|bmp|svg|avif)$/i,ti=/\.(mp4|mov|webm|m4v|ogv|avi|mkv)$/i;class ii{constructor(e){this.editor=e,this.options=e.options,this.tasks=new Map,this.input=null}kindOf(e){const t=String(e.type||""),i=String(e.name||"");return t.startsWith("image/")||ei.test(i)?"image":t.startsWith("video/")||ti.test(i)?"video":null}check(e,t){if(!t)return`不支持的文件类型:${e.name||"剪贴板内容"}`;const i=t==="image"?this.options.maxImageSize:this.options.maxVideoSize;return i&&e.size>i?`${e.name} 超出大小限制(${R(i)})`:null}pickFiles(e){this.input||(this.input=l("input",{type:"file",multiple:!0,style:{display:"none"}}),this.input.addEventListener("change",()=>{const t=[...this.input.files||[]];this.input.value="",this.addFiles(t)}),document.body.appendChild(this.input)),this.input.accept=e==="image"?this.options.imageAccept:this.options.videoAccept,this.input.multiple=e==="image",this.input.click()}async addFiles(e){const t=[];for(const i of e){const n=this.kindOf(i),r=this.check(i,n);r?this.editor.toast.warn(r):t.push({file:i,kind:n})}for(const i of t)await this.upload(i.file,i.kind);return t.length}async upload(e,t){const i=t==="image"?this.createImageHolder():this.createVideoHolder();this.editor.focus(),P(this.editor.root,i);const n={id:i.dataset.kId,file:e,kind:t,holder:i,ctrl:new AbortController,previewUrl:URL.createObjectURL(e)};this.tasks.set(n.id,n),this.decorateHolder(n);const r=i.querySelector("[data-k-preview]");return r&&(r.src=n.previewUrl),this.runUpload(n)}async runUpload(e){const t=this.editor,{holder:i,file:n,kind:r}=e;t.emit("uploadstart",{file:n,kind:r}),t.refreshStatus();let s=n;try{r==="image"&&(s=await Ie(n,this.options.image));const a=await t.uploader.upload(s,{signal:e.ctrl.signal,onProgress:(d,h)=>this.updateProgress(i,d,h,s,e)}),c=typeof a=="string"?{url:a}:a;if(!(c!=null&&c.url))throw new Error("上传结果缺少 url");return this.finish(e,{...c,size:s.size}),t.emit("uploaddone",{file:n,kind:r,url:c.url}),c}catch(a){return(a==null?void 0:a.name)==="AbortError"?(this.remove(e),t.emit("uploadcancel",{file:n,kind:r}),null):(this.fail(e,a),t.emit("uploaderror",{file:n,kind:r,error:a}),t.toast.error((a==null?void 0:a.message)||"上传失败"),null)}finally{ee(t.root),t.commitHistory(),t.refreshStatus()}}createImageHolder(){const e=l("figure",{"data-k-media":"image","data-k-id":ie("m"),"data-k-state":"uploading",contenteditable:"false"}),t=l("div.ke-media-holder",{},[l("img",{"data-k-preview":"",alt:"",style:{display:"none"}}),l("div.ke-media-name",{text:"图片上传中…"}),De()]);return t.appendChild(this.actionRow()),e.appendChild(t),e}createVideoHolder(){const e=l("div.ke-video-card",{"data-k-media":"video","data-k-id":ie("m"),"data-k-state":"uploading",contenteditable:"false"}),t=l("div.ke-video-body",{},[l("div.ke-video-head",{},[l("span",{text:"视频上传中…"}),l("span.ke-video-size",{text:""})]),De()]);return t.appendChild(this.actionRow()),e.appendChild(t),e}actionRow(){const e=this;return l("div",{"data-k-actions":"",style:{display:"flex",alignItems:"center",gap:"8px",width:"100%",marginTop:"2px"},onclick:t=>{const i=t.target.closest("[data-k-id]"),n=i&&e.tasks.get(i.dataset.kId);n&&(t.target.matches(".ke-media-cancel")?(n.ctrl.abort(),e.remove(n)):t.target.matches(".ke-media-retry")&&(n.ctrl=new AbortController,e.resetHolder(n),e.runUpload(n)))}},[l("button.ke-media-cancel",{type:"button",text:"取消"})])}decorateHolder(e){const{holder:t,file:i}=e,n=t.querySelector(".ke-media-name");n&&(n.textContent=`${i.name||"未命名"}(${R(i.size)})`);const r=t.querySelector(".ke-video-size");r&&(r.textContent=R(i.size));const s=t.querySelector(".ke-video-head span");s&&e.kind==="video"&&(s.textContent=`${i.name||"视频"} 上传中…`)}resetHolder(e){const t=e.holder;t.dataset.kState="uploading";const i=t.querySelector(".ke-progress i");i&&(i.style.width="0%",i.style.background="");const n=t.querySelector(".ke-media-pct");n&&(n.textContent="0%");const r=t.querySelector("[data-k-actions]");r&&(r.innerHTML='<button class="ke-media-cancel" type="button">取消</button>'),this.decorateHolder(e)}updateProgress(e,t,i,n,r){const s=Math.max(0,Math.min(100,Math.round((t||0)*100))),a=e.querySelector(".ke-progress i");a&&(a.style.width=`${s}%`);const c=e.querySelector(".ke-media-pct");c&&(c.textContent=`${s}%`),r&&this.editor.emit("uploadprogress",{file:r.file,kind:r.kind,percent:s,info:i});const d=e.querySelector(".ke-media-meta");if(!d)return;let h=d.querySelector("[data-k-chunks]");h||(h=l("span",{"data-k-chunks":"",style:{color:"#8a8f99",fontSize:"12px"}}),d.insertBefore(h,d.firstChild)),(i==null?void 0:i.chunks)>1?h.textContent=`${i.chunks} 片 · ${R(i.loaded)}/${R(i.total||n.size)}`:i!=null&&i.speed&&(h.textContent=`${R(i.speed)}/s`)}finish(e,t){const{holder:i,kind:n,file:r}=e,s=t.url;if(i.dataset.kState="done",i.dataset.kUrl=s,i.innerHTML="",n==="image"){const a=l("img",{src:s,alt:oi(r),"data-k-name":r.name||"",draggable:"false"});a.addEventListener("dblclick",()=>J(a.src)),i.appendChild(a)}else{const a=l("video",{src:s,controls:"",playsinline:"",preload:"metadata","data-k-name":r.name||""}),c=l("div.ke-video-body",{},[l("div.ke-video-head",{},[l("span",{text:r.name||"视频"}),l("span.ke-video-size",{text:R(t.size||r.size)})]),a]);i.appendChild(c)}e.previewUrl&&URL.revokeObjectURL(e.previewUrl),this.tasks.delete(e.id),this.editor.refreshStatus()}fail(e,t){const i=e.holder;i.dataset.kState="error";const n=i.querySelector(".ke-progress i");n&&(n.style.background="#e53e3e");const r=i.querySelector("[data-k-actions]");r&&(r.innerHTML="",r.appendChild(l("span.ke-media-error",{text:(t==null?void 0:t.message)||"上传失败",style:{marginRight:"auto",fontSize:"12px"}})),r.appendChild(l("button.ke-media-retry",{type:"button",text:"重试"})),r.appendChild(l("button.ke-media-cancel",{type:"button",text:"移除"})))}remove(e){var t;(t=e.holder)==null||t.remove(),e.previewUrl&&URL.revokeObjectURL(e.previewUrl),this.tasks.delete(e.id),ee(this.editor.root),this.editor.refreshStatus()}taskFromNode(e){var i;const t=(i=e==null?void 0:e.closest)==null?void 0:i.call(e,"[data-k-id]");return t?this.tasks.get(t.dataset.kId):null}cancelAll(){for(const e of[...this.tasks.values()])e.ctrl.abort(),this.remove(e)}insertFromUrl(e,t,i=""){const n=e==="image"?this.insertImageUrl(t,i):this.insertVideoUrl(t,i||"网络视频");return this.editor.toast.ok(e==="image"?"已插入网络图片":"已插入网络视频"),this.editor.emit("insertmedia",{kind:e,url:t,node:n}),n}insertImageUrl(e,t=""){const i=l("img",{src:e,alt:t||"",draggable:"false"});i.addEventListener("dblclick",()=>J(i.src));const n=l("figure",{"data-k-media":"image","data-k-state":"done","data-k-url":e,contenteditable:"false"},[i]);return P(this.editor.root,n),this.editor.commitHistory(),n}insertVideoUrl(e,t="视频"){const i=l("video",{src:e,controls:"",playsinline:"",preload:"metadata"}),n=l("div.ke-video-card",{"data-k-media":"video","data-k-state":"done","data-k-url":e,contenteditable:"false"},[l("div.ke-video-body",{},[l("div.ke-video-head",{},[l("span",{text:t})]),i])]);return P(this.editor.root,n),this.editor.commitHistory(),n}destroy(){var e;this.cancelAll(),(e=this.input)==null||e.remove(),this.input=null}}function oi(o){return String(o.name||"").replace(/\.[^.]+$/,"")}function De(){return l("div.ke-media-meta",{},[l("div.ke-progress",{},[l("i",{style:{width:"0%"}})]),l("span.ke-media-pct",{text:"0%"})])}async function Ie(o,e={}){var s,a;const t=e==null?void 0:e.compress;if(!t||!/^image\/(jpeg|jpg|png|webp)$/i.test(o.type))return o;const{maxWidth:i=1440,quality:n=.85,minSize:r=300*1024}=typeof t=="object"?t:{};if(o.size<r)return o;try{const c=await createImageBitmap(o);if(c.width<=i)return(s=c.close)==null||s.call(c),o;const d=document.createElement("canvas");d.width=i,d.height=Math.round(c.height*i/c.width),d.getContext("2d").drawImage(c,0,0,d.width,d.height),(a=c.close)==null||a.call(c);const h=await new Promise(p=>d.toBlob(p,"image/jpeg",n));return!h||h.size>=o.size?o:new File([h],String(o.name).replace(/\.\w+$/,".jpg"),{type:"image/jpeg",lastModified:o.lastModified})}catch{return o}}function ke(o){return`${Ue(o.size)}-${ni(o.lastModified)}-${ri(o.name)}`}async function qe(o){var a;if(!((a=globalThis.crypto)!=null&&a.subtle))return ke(o);const e=256*1024,t=[o.slice(0,e)];o.size>e&&t.push(o.slice(o.size-e));const i=new Uint8Array(t.reduce((c,d)=>c+d.size,0));let n=0;for(const c of t){const d=new Uint8Array(await c.arrayBuffer());i.set(d,n),n+=d.length}const r=await crypto.subtle.digest("SHA-256",i);return`${Array.from(new Uint8Array(r)).map(c=>c.toString(16).padStart(2,"0")).join("").slice(0,24)}-${Ue(o.size)}`}const Ue=o=>Number(o).toString(16),ni=o=>Number(o||0).toString(16),ri=o=>String(o).replace(/[^\w.-]/g,"").slice(0,24);function si(o="fast"){return o==="strong"||o==="sha256"?qe:typeof o=="function"?o:async e=>ke(e)}const ai=1024*1024;class j{constructor(e,t={}){if(!e||typeof e.put!="function")throw new Error("[KEditor] uploader 需要提供 put() 方法,参见 docs/upload-adapter.md");this.adapter=e,this.chunkSize=Math.max(64*1024,t.chunkSize||ai),this.concurrency=Math.max(1,t.concurrency||3),this.retries=t.retries===void 0?2:Math.max(0,t.retries),this.retryDelay=t.retryDelay??600,this.fingerprint=si(t.fingerprint||"fast"),this.slice=t.slice}async upload(e,t={}){var x,g,$,Qe,et,tt;const{onProgress:i,onChunk:n,signal:r}=t;if(this.adapter.simple)return this.uploadSimple(e,t);const s=Math.max(1,Math.ceil(e.size/this.chunkSize)),a={name:e.name||"blob",size:e.size,type:e.type||ci(e.name),lastModified:e.lastModified||0,fingerprint:await this.fingerprint(e),chunkSize:this.chunkSize,totalChunks:s},c=await((g=(x=this.adapter).init)==null?void 0:g.call(x,a,{signal:r}))||{};if(c.url)return i==null||i(1,{percent:100,loaded:e.size,total:e.size,chunks:s,instant:!0}),{url:c.url,instant:!0,chunks:0,size:e.size,name:a.name,key:c.key};const d=c.uploadId||a.fingerprint,h=new Set((c.uploadedChunks||c.uploaded||[]).map(Number));let p=0;for(const w of h)p+=Math.min(this.chunkSize,e.size-w*this.chunkSize);const u=[];for(let w=0;w<s;w+=1)h.has(w)||u.push(w);const k=new Array(s);let f=h.size;const y=Date.now(),v=()=>{const w=(Date.now()-y)/1e3;i==null||i(e.size?p/e.size:1,{percent:Math.min(100,Math.round(p/Math.max(1,e.size)*100)),loaded:p,total:e.size,chunks:s,uploadedChunks:f,speed:w>0?p/w:0})};v();let C=0,S=null;const A=async()=>{for(;C<u.length;){if(r!=null&&r.aborted)throw new DOMException("已取消上传","AbortError");const w=u[C++],te=this.slice?this.slice(e,w,this.chunkSize):e.slice(w*this.chunkSize,(w+1)*this.chunkSize);let ye=0;for(;;)try{const L=await this.adapter.put({uploadId:d,index:w,total:s,chunkSize:this.chunkSize,blob:te,file:e,meta:a,signal:r,size:te.size});L!=null&&L.url&&(k[w]=L),p+=te.size,f+=1,n==null||n({index:w,total:s,size:te.size}),v();break}catch(L){if((L==null?void 0:L.name)==="AbortError")throw L;if(ye+=1,ye>this.retries)throw S=L,new Error(`分片 ${w+1}/${s} 上传失败:${(L==null?void 0:L.message)||L}`);await li(this.retryDelay*ye,r)}}},H=Array.from({length:Math.max(1,Math.min(this.concurrency,u.length))},A);try{await Promise.all(H)}catch(w){throw await((Qe=($=this.adapter).abort)==null?void 0:Qe.call($,{uploadId:d,meta:a,error:w}).catch(()=>{})),w}if(S)throw S;const E=await((tt=(et=this.adapter).complete)==null?void 0:tt.call(et,{uploadId:d,meta:a,total:s,uploaded:f,chunkResults:k,file:e}))||{},m=E.url;if(!m)throw new Error("[KEditor] uploader.complete() 未返回 url");return{url:m,chunks:s,size:e.size,name:a.name,key:E.key,poster:E.poster,duration:E.duration,raw:E}}async uploadSimple(e,t={}){const{onProgress:i,signal:n}=t,r=Date.now(),s=await this.adapter.upload(e,{signal:n,onProgress:(c,d)=>{const h=d?c/d:0,p=(Date.now()-r)/1e3;i==null||i(h,{percent:Math.round(h*100),loaded:c,total:d||e.size,chunks:1,uploadedChunks:h>=1?1:0,speed:p>0?c/p:0})}}),a=typeof s=="string"?s:s==null?void 0:s.url;if(!a)throw new Error("[KEditor] uploader.upload() 未返回 url");return{url:a,chunks:1,size:e.size,name:e.name,key:typeof s=="object"?s.key:void 0,raw:s}}destroy(){var e,t;(t=(e=this.adapter).destroy)==null||t.call(e)}}const li=(o,e)=>new Promise((t,i)=>{const n=setTimeout(()=>{e==null||e.removeEventListener("abort",r),t()},o),r=()=>{clearTimeout(n),i(new DOMException("已取消上传","AbortError"))};e==null||e.addEventListener("abort",r,{once:!0})});function ci(o=""){var i;const e=(i=String(o).split(".").pop())==null?void 0:i.toLowerCase();return{jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",mp4:"video/mp4",mov:"video/quicktime",webm:"video/webm",m4v:"video/x-m4v"}[e]||"application/octet-stream"}function We(o){return{simple:!0,async upload(e,t={}){const i=await o(di(e),t);return typeof i=="string"?{url:i}:i}}}function di(o,e="blob",t=o.type){return o instanceof File?o:new File([o],e,{type:t})}const ge=o=>new Promise(e=>setTimeout(e,o)),hi=(o,e=.4)=>o*(1-e+Math.random()*e*2);function _e(o={}){const{latency:e=160,speed:t=12,onEvent:i=null,reuseObjectUrl:n=!0,failFirstChunk:r=!1}=o,s=new Map,a=new Map,c=new Map;let d=r;const h=(p,u)=>i==null?void 0:i(p,{...u,at:Date.now()});return{name:"mock",async init(p){h("init",p),await ge(120);const u=s.get(p.fingerprint);if(u)return h("instant",{name:p.name,url:u.url}),{url:u.url,key:p.fingerprint,instant:!0};const k=a.get(p.fingerprint)||new Set;return a.set(p.fingerprint,k),{uploadId:p.fingerprint,uploadedChunks:[...k]}},async put({uploadId:p,index:u,total:k,size:f,blob:y}){if(d&&u===0){d=!1,h("chunk-error",{index:u,total:k,message:"mock: 模拟首个分片网络异常"});const S=new Error("mock: 模拟首个分片网络异常");throw S.retryable=!0,S}const v=Math.max(40,hi(e+f/(t*1024/8)/8,.35));await ge(v);const C=a.get(p)||new Set;return C.add(u),a.set(p,C),h("chunk",{index:u,total:k,size:f,blobSize:y==null?void 0:y.size}),{etag:`${p}-${u}`}},async complete({uploadId:p,meta:u,file:k}){await ge(140);let f=c.get(u.fingerprint);if(!f||!n){const y=k instanceof File?k:new File([k],u.name,{type:u.type});f=URL.createObjectURL(y),c.set(u.fingerprint,f)}return s.set(u.fingerprint,{url:f,name:u.name,size:u.size,type:u.type}),a.delete(p),h("complete",{name:u.name,url:f,chunks:u.totalChunks,size:u.size}),{url:f,key:u.fingerprint}},async abort({uploadId:p}){h("abort",{uploadId:p})},list:()=>[...s.entries()].map(([p,u])=>({key:p,...u})),reset:()=>{s.clear(),a.clear()}}}function Ve(o={}){const{initUrl:e,chunkUrl:t,completeUrl:i,abortUrl:n,mode:r="raw",fieldName:s="file",headers:a={},withCredentials:c=!1,parse:d=k=>(k==null?void 0:k.data)||k||{},chunkUrlFor:h}=o,p=()=>typeof a=="function"?a()||{}:a||{},u=async(k,f={})=>{const y=await fetch(k,{credentials:c?"include":"same-origin",...f});if(!y.ok)throw new Error(`HTTP ${y.status} ${y.statusText}`);const v=await y.text();if(!v)return{};try{return d(JSON.parse(v))}catch{throw new Error(`服务端返回非 JSON 数据:${v.slice(0,80)}`)}};return{name:"http",async init(k,{signal:f}){if(!e)throw new Error("[KEditor] httpAdapter 缺少 initUrl");return u(e,{method:"POST",signal:f,headers:{"Content-Type":"application/json",...p()},body:JSON.stringify({fileName:k.name,fileSize:k.size,fileType:k.type,lastModified:k.lastModified,identifier:k.fingerprint,chunkSize:k.chunkSize,totalChunks:k.totalChunks})})},async put({uploadId:k,index:f,total:y,blob:v,meta:C,signal:S}){if(!t)throw new Error("[KEditor] httpAdapter 缺少 chunkUrl");const A=typeof h=="function"?h({uploadId:k,index:f}):t;if(r==="formdata"){const m=new FormData;return m.append(s,v,`${C.name}.part${f}`),m.append("uploadId",k),m.append("identifier",C.fingerprint),m.append("index",String(f)),m.append("total",String(y)),m.append("filename",C.name),u(A,{method:"POST",body:m,signal:S,headers:p()})}const H=A.includes("?")?"&":"?",E=`${A}${H}uploadId=${encodeURIComponent(k)}&index=${f}&total=${y}&filename=${encodeURIComponent(C.name)}`;return u(E,{method:"PUT",body:v,signal:S,headers:{"Content-Type":"application/octet-stream","X-Chunk-Index":String(f),...p()}})},async complete({uploadId:k,meta:f,total:y}){if(!i)throw new Error("[KEditor] httpAdapter 缺少 completeUrl");return u(i,{method:"POST",headers:{"Content-Type":"application/json",...p()},body:JSON.stringify({uploadId:k,identifier:f.fingerprint,fileName:f.name,fileSize:f.size,fileType:f.type,chunkSize:f.chunkSize,totalChunks:y})})},async abort({uploadId:k}){n&&await u(n,{method:"POST",headers:{"Content-Type":"application/json",...p()},body:JSON.stringify({uploadId:k})}).catch(()=>{})}}}function Ke(o="mock",e={}){if(o instanceof j)return o;if(typeof o=="function"&&!o.put)return new j(We(o),e);if(o&&typeof o=="object"&&!(o instanceof j)){if(typeof o.put=="function"||typeof o.upload=="function")return new j(o,{...e,...Ge(o)});if(o.type==="http")return new j(Ve(o),{...e,...Ge(o)})}return new j(_e(typeof o=="object"?o:{}),e)}const Ge=o=>{const e={};for(const t of["chunkSize","concurrency","retries","fingerprint"])o[t]!==void 0&&(e[t]=o[t]);return e};function pi(o){o.root.addEventListener("paste",async e=>{if(o.readOnly||!o.options.paste.enabled)return;const t=e.clipboardData;if(!t)return;e.preventDefault();const i=ui(t);if(i.length){o.options.paste.uploadFiles?(await o.media.addFiles(i),o.toast.show(`已上传 ${i.length} 个文件`)):o.toast.warn("当前配置不允许粘贴上传文件");return}const n=t.getData("text/html"),r=t.getData("text/plain");if(n&&o.options.paste.clean){let s=Me(n)?ze(n):n;s=K(s,{allowEmpty:!0}),o.options.paste.localizeImages&&(s=await ki(o,s)),o.commands.insertHTML(s,{clean:!1}),Me(n)&&o.toast.show("已清理 Word/WPS 格式")}else if(r){const s=r.split(/\r?\n/).map(a=>`<p>${ce(a)||"<br>"}</p>`).join("");o.commands.insertHTML(s,{clean:!1})}})}function ui(o){var t,i;const e=[];if((t=o.items)!=null&&t.length){for(const n of o.items)if(n.kind==="file"){const r=n.getAsFile();r&&e.push(Xe(r,e.length))}}return!e.length&&((i=o.files)!=null&&i.length)&&e.push(...Array.from(o.files).map((n,r)=>Xe(n,r))),e}function Xe(o,e){if(o.name&&o.name!=="image.png")return o;const t=(o.type.split("/")[1]||"png").replace("jpeg","jpg").replace("+xml",""),i=new Date().toISOString().slice(11,19).replace(/:/g,"");return new File([o],`pasted-${i}-${e}.${t}`,{type:o.type,lastModified:o.lastModified})}function fi(o){const e=o.root;let t=0;const i=n=>{var r;return Array.from(((r=n.dataTransfer)==null?void 0:r.types)||[]).includes("Files")};e.addEventListener("dragenter",n=>{!i(n)||o.readOnly||(n.preventDefault(),t+=1,o.el.classList.add("ke-is-dragover"))}),e.addEventListener("dragover",n=>{!i(n)||o.readOnly||(n.preventDefault(),n.dataTransfer.dropEffect="copy")}),e.addEventListener("dragleave",n=>{i(n)&&(t=Math.max(0,t-1),t===0&&o.el.classList.remove("ke-is-dragover"))}),e.addEventListener("drop",async n=>{if(!i(n)||o.readOnly)return;n.preventDefault(),t=0,o.el.classList.remove("ke-is-dragover"),mi(o,n);const r=[...n.dataTransfer.files||[]];if(r.length&&o.options.paste.uploadFiles){const s=await o.media.addFiles(r);s&&o.toast.show(`已上传 ${s} 个文件`)}})}function mi(o,e){let t=null;if(document.caretRangeFromPoint)t=document.caretRangeFromPoint(e.clientX,e.clientY);else if(document.caretPositionFromPoint){const i=document.caretPositionFromPoint(e.clientX,e.clientY);i&&(t=document.createRange(),t.setStart(i.offsetNode,i.offset),t.collapse(!0))}if(t&&o.root.contains(t.commonAncestorContainer)){const i=window.getSelection();i.removeAllRanges(),i.addRange(t)}else o.focus()}async function ki(o,e){const t=new DOMParser().parseFromString(`<div>${e}</div>`,"text/html"),i=[...t.body.querySelectorAll("img")].filter(n=>/^https?:/i.test(n.getAttribute("src")||""));for(const n of i)try{const r=await fetch(n.src,{mode:"cors"});if(!r.ok)continue;const s=await r.blob(),a=new File([s],n.alt||`remote-${Date.now()}.jpg`,{type:s.type||"image/jpeg"}),c=await o.media.upload(a,"image");n.remove(),c!=null&&c.url&&o.toast.show("外链图片已本地化")}catch{}return t.body.innerHTML.trim()}const Je=1024,be=1024*Je,F={value:"",placeholder:"开始撰写内容,支持拖拽 / 粘贴图片与视频…",height:460,minHeight:320,primaryColor:"#07c160",paperWidth:677,paperMode:"fluid",paperGap:24,paperMaxWidth:0,toolbar:Q,customButtons:[],hideToolbar:!1,hideStatusbar:!1,readOnly:!1,autofocus:!1,maxLength:0,wordCount:!0,sanitize:!0,historyLimit:60,uploader:"mock",upload:{chunkSize:be,concurrency:3,retries:2,fingerprint:"fast"},image:{compress:{maxWidth:1440,quality:.85,minSize:300*Je}},maxImageSize:20*be,maxVideoSize:512*be,imageAccept:"image/png,image/jpeg,image/gif,image/webp,image/bmp,image/svg+xml,image/avif",videoAccept:"video/mp4,video/quicktime,video/webm,video/x-m4v,video/ogg",paste:{enabled:!0,clean:!0,uploadFiles:!0,localizeImages:!1},onChange:null,onReady:null,onError:null,onUpload:null,beforeUpload:null,toolbarFloat:!1};let gi=0;class X{constructor(e,t={}){it(),this.options=yi(t),this.id=`ke-${gi+=1}`,this.el=xi(e,this.id),this.el.__keditor__=this;const i=this.el.innerHTML;this.emitters=new Map,this.domListeners=[],this.destroyed=!1,this.sourceMode=!1,this.previewMode=!1,this.fullscreen=!1,this.readOnly=!1,this.buildDOM(),this.toast=new vt,this.popover=new st(this.el),this.commands=new Jt(this),this.uploader=Ke(this.options.uploader,this.options.upload),this.media=bi(this),this.history=new Qt(this.root,{limit:this.options.historyLimit}),this.toolbar=new Kt(this,this.options.toolbar,this.options.customButtons),this.source=new xt(this),this.previewPanel=new yt(this),this.bubble=new wt(this),this.mainEl.append(this.source.el,this.previewPanel.el),this.applyTheme(),this.setContent(this.options.value||i,{sanitize:this.options.sanitize,silent:!0}),this.bindEvents(),this.setReadOnly(this.options.readOnly),this.refresh(),this.refreshStatus(),this.history.reset(this.root.innerHTML),queueMicrotask(()=>{var n,r;this.destroyed||(this.emit("ready",{editor:this}),(r=(n=this.options).onReady)==null||r.call(n,this),this.options.autofocus&&this.focus())})}buildDOM(){this.el.classList.add("ke"),this.el.id=this.el.id||this.id,this.el.innerHTML="",this.tbEl=l("div.ke-tb",{role:"toolbar","aria-label":"编辑器工具栏"}),this.scrollEl=l("div.ke-scroll"),this.paperEl=l("div.ke-paper"),this.root=l("div.ke-content",{contenteditable:this.readOnly?"false":"true",role:"textbox","aria-multiline":"true",spellcheck:"false","data-placeholder":this.options.placeholder,"data-ke-root":""}),this.root.style.minHeight=`${this.options.minHeight}px`,this.paperEl.appendChild(this.root),this.scrollEl.appendChild(this.paperEl),this.mainEl=l("div.ke-main",{},[this.scrollEl]),this.statusEl=Ci(this),this.dropzoneEl=l("div.ke-dropzone",{},[l("span",{text:"松开即可上传(分片传输)"})]),this.options.hideToolbar||this.el.appendChild(this.tbEl),this.el.appendChild(this.mainEl),this.options.hideStatusbar||this.el.appendChild(this.statusEl),this.el.appendChild(this.dropzoneEl),this.options.height&&(this.scrollEl.style.height=`${this.options.height}px`,this.scrollEl.style.maxHeight=`${this.options.height}px`),this.paperEl.style.setProperty("--ke-min-height",`${this.options.minHeight}px`),this.applyPaper()}applyPaper(){const{paperWidth:e,paperMode:t,paperGap:i,paperMaxWidth:n}=this.options;this.paperEl.style.setProperty("--ke-paper",`${e}px`),this.paperEl.style.setProperty("--ke-paper-gap",`${i}px`),n>0?this.paperEl.style.setProperty("--ke-paper-max",`${n}px`):this.paperEl.style.removeProperty("--ke-paper-max"),this.paperEl.classList.toggle("ke-is-fluid",t!=="fixed")}setPaper(e={}){return e.width!==void 0&&(this.options.paperWidth=I(Number(e.width)||0,200,8e3)),e.mode!==void 0&&(this.options.paperMode=e.mode==="fixed"?"fixed":"fluid"),e.gap!==void 0&&(this.options.paperGap=I(Number(e.gap)||0,0,600)),e.maxWidth!==void 0&&(this.options.paperMaxWidth=Math.max(0,Number(e.maxWidth)||0)),this.applyPaper(),{...this.paperOptions()}}paperOptions(){const{paperWidth:e,paperMode:t,paperGap:i,paperMaxWidth:n}=this.options;return{width:e,mode:t,gap:i,maxWidth:n}}applyTheme(){this.options.primaryColor&&this.el.style.setProperty("--ke-primary",this.options.primaryColor)}bindEvents(){const e=ot(()=>this.emitChange(),160);this.bind(this.root,"input",()=>{this.history.snapshot(),this.refreshStatus(),this.togglePlaceholder(),e(),this.enforceMaxLength()}),this.bind(this.root,"keydown",t=>this.handleKeydown(t)),this.bind(this.root,"blur",()=>{this.history.flush(),this.el.classList.remove("ke-is-focus"),this.emit("blur")}),this.bind(this.root,"focus",()=>{this.el.classList.add("ke-is-focus"),this.emit("focus")}),this.bind(this.root,"click",t=>this.handleContentClick(t)),this.bind(this.root,"dblclick",t=>{const i=t.target.closest("img");i&&this.root.contains(i)&&J(i.src)}),pi(this),fi(this),this.selectionHandler=()=>{!this.root.contains(document.activeElement)&&document.activeElement!==this.root||(this.refresh(),this.syncBubble())},document.addEventListener("selectionchange",this.selectionHandler),this.scrollHandler=()=>this.bubble.position(),this.bind(this.scrollEl,"scroll",this.scrollHandler),window.addEventListener("resize",this.scrollHandler)}bind(e,t,i){return e.addEventListener(t,i),this.domListeners.push({node:e,type:t,handler:i}),i}handleKeydown(e){const t=e.metaKey||e.ctrlKey,i=e.key.toLowerCase();if(t&&i==="z"){e.preventDefault(),e.shiftKey?this.redo():this.undo();return}if(t&&i==="y"){e.preventDefault(),this.redo();return}if(t&&["b","i","u"].includes(i)){e.preventDefault(),this.commands.toggleMark({b:"bold",i:"italic",u:"underline"}[i]),this.refresh();return}if(t&&e.shiftKey&&i==="k"){e.preventDefault(),this.toggleSource();return}if(t&&i==="k"){e.preventDefault(),this.toolbar.openLink();return}if(t&&i==="s"){e.preventDefault(),this.emit("save",{html:this.getHTML()});return}if(e.key==="Escape"){this.popover.close(),this.bubble.hide(),this.previewMode&&this.closePreview();return}(e.key==="Backspace"||e.key==="Delete")&&this.bubble.node&&(e.preventDefault(),this.bubble.remove())}handleContentClick(e){const t=e.target.closest("[data-k-media]");if(t&&this.root.contains(t)){this.selectMedia(t);return}this.clearMediaSelection(),this.bubble.hide()}selectMedia(e){this.clearMediaSelection(),e.classList.add("ke-is-selected-media"),this.bubble.show(e),this.refreshStatus()}clearMediaSelection(){this.root.querySelectorAll(".ke-is-selected-media").forEach(e=>e.classList.remove("ke-is-selected-media")),this.bubble.hide()}syncBubble(){!this.bubble.node||!this.root.contains(this.bubble.node)?this.bubble.hide():this.bubble.position()}getState(){var a,c,d;const e=z(this.root),t=N((e==null?void 0:e.commonAncestorContainer)||this.root,this.root),i=e?Si(e,this.root):null,n=(a=this.bubble)==null?void 0:a.node,r=n&&((c=n.dataset)==null?void 0:c.kMedia)==="image"?n.querySelector("img"):null,s=r?oe(r):Ei(e,t);return{bold:this.queryState("bold"),italic:this.queryState("italic"),underline:this.queryState("underline"),strikeThrough:this.queryState("strikeThrough"),ul:this.queryState("insertUnorderedList"),ol:this.queryState("insertOrderedList"),align:s,block:((d=t==null?void 0:t.tagName)==null?void 0:d.toLowerCase())||"p",fontSize:this.commands.currentFontSize(),linkUrl:i?i.getAttribute("href"):"",linkTarget:i?i.getAttribute("target")==="_blank":!1,selectionText:e?e.toString():"",canUndo:this.history.canUndo(),canRedo:this.history.canRedo(),source:this.sourceMode,preview:this.previewMode,fullscreen:this.fullscreen,readOnly:this.readOnly}}queryState(e){var t;if(!this.root.contains(((t=window.getSelection())==null?void 0:t.anchorNode)||null))return!1;try{return document.queryCommandState(e)}catch{return!1}}refresh(){if(!this.destroyed)try{this.toolbar.refresh(this.getState())}catch{}}refreshStatus(){const e=this.statusApi;e&&e.update(this.counts())}counts(){const e=Te(this.root.innerHTML);return{chars:e.replace(/\s/g,"").length,words:Li(e),images:this.root.querySelectorAll("img").length,videos:this.root.querySelectorAll('[data-k-media="video"] video, video').length,uploading:this.media?this.media.tasks.size:0}}togglePlaceholder(){const e=!this.root.textContent.trim()&&!this.root.querySelector("img,video,hr,table,iframe");this.root.classList.toggle("ke-is-empty",e)}enforceMaxLength(){var i,n;const e=this.options.maxLength;if(!e)return;const{chars:t}=this.counts();t>e?(this.toast.warn(`已超过建议字数 ${e}`),(i=this.statusEl)==null||i.classList.add("ke-is-over")):(n=this.statusEl)==null||n.classList.remove("ke-is-over")}getHTML({clean:e=!0}={}){const t=this.root.innerHTML;return e?Ze(t):t}getText(){return Te(this.root.innerHTML)}getJSON(){return{html:this.getHTML(),text:this.getText(),counts:this.counts()}}setContent(e,{sanitize:t=this.options.sanitize,silent:i=!1}={}){const n=K(e||"<p><br></p>",{allowEmpty:!0});return this.root.innerHTML=n||"<p><br></p>",this.afterEdit({silent:i}),i||this.history.snapshot(!0),this.togglePlaceholder(),this}appendHTML(e){const t=document.createRange();t.selectNodeContents(this.root),t.collapse(!1);const i=window.getSelection();return i.removeAllRanges(),i.addRange(t),this.commands.insertHTML(e),this}clear(){return this.media.cancelAll(),this.setContent("<p><br></p>"),this.focus(),this}afterEdit({silent:e=!1}={}){this.history.snapshot(),this.refreshStatus(),this.togglePlaceholder(),e||this.emitChange()}commitHistory(){this.history.snapshot(!0),this.refreshStatus(),this.emitChange()}emitChange(){var e,t;this.emit("change",{html:this.getHTML(),text:this.getText()}),(t=(e=this.options).onChange)==null||t.call(e,this.getHTML(),this)}focus(){if(this.readOnly||this.sourceMode)return this.sourceMode&&this.source.code.focus(),this;this.root.focus();const e=window.getSelection();if(!e||e.rangeCount===0||!this.root.contains(e.anchorNode)){const t=document.createRange(),i=this.root.firstElementChild||this.root;t.selectNodeContents(i),t.collapse(!1),e.removeAllRanges(),e.addRange(t)}return this}blur(){return this.root.blur(),this}saveSelection(){const e=z(this.root);return this.savedRange=e?e.cloneRange():null,this}restoreSelection(){this.root.focus();const e=window.getSelection();return this.savedRange&&this.root.contains(this.savedRange.startContainer)&&this.root.contains(this.savedRange.endContainer)?(e.removeAllRanges(),e.addRange(this.savedRange),this):this.focus()}setReadOnly(e){return this.readOnly=!!e,this.root.setAttribute("contenteditable",this.readOnly?"false":"true"),this.el.classList.toggle("ke-is-readonly",this.readOnly),this.refresh(),this}undo(){return this.history.flush(),this.history.undo()?(this.afterEdit({silent:!1}),this.refresh(),this):(this.toast.show("没有可撤销的操作"),this)}redo(){return this.history.redo()?(this.afterEdit(),this.refresh(),this):(this.toast.show("没有可重做的操作"),this)}upload(e,t=this.media.kindOf(e)){if(!t)throw new Error("[KEditor] 不支持的文件类型");return this.media.upload(e,t)}insertImage(e,t=""){return this.media.insertImageUrl(e,t)}insertVideo(e,t="视频"){return this.media.insertVideoUrl(e,t)}cancelUploads(){return this.media.cancelAll(),this}addButton(e,t){return this.toolbar.addButton(e,t)}moveButton(e,t){return this.toolbar.moveButton(e,t)}removeButton(e){return this.toolbar.removeButton(e)}setButtonOptions(e,t){return this.toolbar.setButtonOptions(e,t)}getButtonValue(e){return this.toolbar.getButtonValue(e)}setButtonValue(e,t){return this.toolbar.setButtonValue(e,t)}reportError(e,t){var r,s,a;const i=t&&t.message?t.message:String(t),n={type:e,error:t instanceof Error?t:new Error(i),message:i};return(r=this.toast)==null||r.error(i),this.emit("error",n),(a=(s=this.options).onError)==null||a.call(s,n),this}toggleSource(){return this.sourceMode?this.exitSource():this.enterSource(),this.sourceMode}enterSource(){this.sourceMode||(this.history.flush(),this.sourceMode=!0,this.el.classList.add("ke-is-source"),this.clearMediaSelection(),this.source.show(this.getHTML({clean:!0})),this.previewPanel.hide(),this.previewMode=!1,this.refresh(),this.emit("sourcechange",{mode:"source"}))}exitSource(){this.sourceMode&&(this.source.apply({silent:!0}),this.sourceMode=!1,this.el.classList.remove("ke-is-source"),this.source.hide(),this.focus(),this.refresh(),this.emit("sourcechange",{mode:"visual"}))}togglePreview(){return this.previewMode?this.closePreview():this.openPreview(),this.previewMode}openPreview(){this.previewMode=!0,this.previewPanel.show(Mi(this.getHTML())),this.refresh()}closePreview(){this.previewMode=!1,this.previewPanel.hide(),this.refresh()}toggleFullscreen(){return this.fullscreen=!this.fullscreen,this.el.classList.toggle("ke-is-fullscreen",this.fullscreen),document.body.style.overflow=this.fullscreen?"hidden":"",this.refresh(),this.fullscreen}on(e,t){return this.addListener(e,t)}off(e,t){return this.removeListener(e,t)}emit(e,t={}){var n,r,s,a;const i=this.emitters.get(e)||[];for(const c of i)try{c(t)}catch(d){(r=(n=this.options).onError)==null||r.call(n,d)}return e.startsWith("upload")&&((a=(s=this.options).onUpload)==null||a.call(s,{stage:e,...t})),this}addListener(e,t){return this.emitters.has(e)||this.emitters.set(e,[]),this.emitters.get(e).push(t),()=>this.removeListener(e,t)}removeListener(e,t){const i=this.emitters.get(e)||[],n=i.indexOf(t);return n>=0&&i.splice(n,1),this}get element(){return this.root}get editorElement(){return this.el}destroy(){if(!this.destroyed){this.destroyed=!0,this.media.destroy(),this.history.destroy(),this.popover.destroy(),this.source.destroy(),this.previewPanel.destroy(),this.bubble.destroy(),this.toolbar.destroy(),this.toast.destroy();for(const{node:e,type:t,handler:i}of this.domListeners)e.removeEventListener(t,i);document.removeEventListener("selectionchange",this.selectionHandler),this.scrollEl.removeEventListener("scroll",this.scrollHandler),window.removeEventListener("resize",this.scrollHandler),this.fullscreen&&(document.body.style.overflow=""),this.el.__keditor__===this&&(this.el.__keditor__=null),this.el.innerHTML="",this.el.classList.remove("ke","ke-is-fullscreen","ke-is-readonly"),this.el.removeAttribute("style"),this.emitters.clear()}}static create(e,t){return new X(e,t)}}function bi(o){const e=new ii(o),t=e.upload.bind(e);return e.upload=async(i,n)=>{const r=o.options.beforeUpload;let s=i;return r&&(s=await r(i,n),s===!1)?null:t(s,n)},e.replaceNode=async(i,n)=>{const r=i.dataset.kMedia==="video"?"video":"image",s=document.createRange();s.setStartBefore(i),s.collapse(!0);const a=window.getSelection();a.removeAllRanges(),a.addRange(s);const c=await e.upload(n,r);return i.remove(),o.commitHistory(),c},e}function xi(o,e){if(typeof o=="string"){const t=document.querySelector(o);if(!t)throw new Error(`[KEditor] 找不到挂载节点:${o}`);return t}if(o instanceof HTMLElement)return o;if((o==null?void 0:o.$el)instanceof HTMLElement)return o.$el;throw new Error(`[KEditor] 无效的挂载目标(${typeof o})`)}function yi(o){const e={...F,...o};return e.image={...F.image,...o.image||{}},e.paste={...F.paste,...o.paste||{}},e.upload={...F.upload,...o.upload||{}},e.customButtons=Be(o.customButtons),Array.isArray(o.toolbar)&&(e.toolbar=o.toolbar),o.toolbar===!1&&(e.toolbar=[]),o.toolbar===!0&&(e.toolbar=Q),e.customButtons.length&&o.toolbar!==!1&&(e.toolbar=wi(e.toolbar,e.customButtons)),e.height=I(e.height??460,0,4e3),e.paperWidth=I(Number(e.paperWidth)||F.paperWidth,200,8e3),e.paperMode=e.paperMode==="fixed"?"fixed":"fluid",e.paperGap=Number.isFinite(Number(e.paperGap))?I(Number(e.paperGap),0,600):F.paperGap,e.paperMaxWidth=Math.max(0,Number(e.paperMaxWidth)||0),e}const vi=o=>o!=="|"&&o!==":tail";function wi(o,e){const t=[...o],i=[];for(const n of e)if(!t.includes(n.name)){if(n.position==null){i.push(n.name);continue}t.splice(Ye(t,n.position),0,n.name)}return i.length&&t.splice(Ye(t,null),0,"|",...i),t}function Ye(o,e){const t=(()=>{const s=o.indexOf(":tail");return s<0?o.length:s})();if(e==null||e==="end")return t;if(e==="start")return 0;if(e==="tail")return o.length;if(typeof e=="number"){let s=0;for(let a=0;a<o.length;a++)if(vi(o[a])){if(s===Math.max(0,Math.floor(e)))return a;s++}return t}const i=!!(e&&typeof e=="object"&&e.after),n=String(typeof e=="string"?e:(i?e.after:e.before)||""),r=o.indexOf(n);return r<0?t:i?r+1:r}function Ci(o){const e=l("b",{text:"0"}),t=l("b",{text:"0"}),i=l("b",{text:"0"}),n=l("b",{text:"0"}),r=l("span.ke-chip",{hidden:!0}),s=l("span.ke-status-hint",{text:"支持拖拽 / 粘贴上传,Ctrl/⌘ + S 保存"}),a=l("span.ke-status-tail"),c=l("div.ke-status",{},[l("span",{},["字数 ",e," · ",t," 词"]),l("span",{},["图片 ",i," · 视频 ",n]),r,s,a]),d={update:h=>{e.textContent=String(h.chars),t.textContent=String(h.words),i.textContent=String(h.images),n.textContent=String(h.videos),h.uploading>0?(r.hidden=!1,r.className="ke-chip ke-is-busy",r.textContent=`${h.uploading} 个上传进行中`):r.hidden=!0},addExtra:h=>a.appendChild(h)};return o.statusApi=d,o.options.wordCount||(c.style.display="none"),c}function Si(o,e){var n;let t=o==null?void 0:o.commonAncestorContainer;if(!t||!e.contains(t))return null;t.nodeType===3&&(t=t.parentElement);const i=(n=t==null?void 0:t.closest)==null?void 0:n.call(t,"a");return i&&e.contains(i)?i:null}function Ei(o,e){var n,r;const t=e||(o==null?void 0:o.commonAncestorContainer),i=[t,t==null?void 0:t.parentElement].filter(s=>s&&s.nodeType===1);for(const s of i){const a=(n=s.style)==null?void 0:n.textAlign;if(a)return a==="-webkit-justify"?"justify":a;const c=(r=s.getAttribute)==null?void 0:r.call(s,"align");if(c)return c}try{if(document.queryCommandState("justifyCenter"))return"center";if(document.queryCommandState("justifyRight"))return"right";if(document.queryCommandState("justifyFull"))return"justify"}catch{}return"left"}function Li(o){const e=(o.match(/[\u4e00-\u9fa5\u3040-\u30ff]/g)||[]).length,t=(o.match(/[a-zA-Z0-9'’-]+/g)||[]).length;return e+t}function Ze(o){const t=new DOMParser().parseFromString(`<div>${o}</div>`,"text/html").body.firstChild;return t.querySelectorAll("[contenteditable]").forEach(i=>i.removeAttribute("contenteditable")),t.querySelectorAll("[data-k-id]").forEach(i=>i.removeAttribute("data-k-id")),t.querySelectorAll("[data-k-state]").forEach(i=>i.removeAttribute("data-k-state")),t.querySelectorAll("[data-ke-marker]").forEach(i=>i.removeAttribute("data-ke-marker")),t.querySelectorAll("[data-placeholder]").forEach(i=>i.removeAttribute("data-placeholder")),t.querySelectorAll(".ke-is-selected-media").forEach(i=>i.classList.remove("ke-is-selected-media")),t.querySelectorAll('[data-k-state="uploading"], [data-k-state="error"]').forEach(i=>i.remove()),t.innerHTML.trim()}function Mi(o){const t=new DOMParser().parseFromString(`<div>${o}</div>`,"text/html").body.firstChild;return t.querySelectorAll("[data-k-media]").forEach(i=>{i.removeAttribute("data-k-media"),i.removeAttribute("data-k-url")}),t.innerHTML}const zi="1.0.7";function xe(o,e={}){return new X(o,e)}const Ti=xe;function Ai(o,e={}){const t=typeof o=="string"?document.querySelector(o):o;return t!=null&&t.__keditor__&&t.__keditor__.destroy(),xe(t,e)}b.ChunkUploader=j,b.DEFAULT_TOOLBAR=Q,b.KEditor=X,b.cleanWordHtml=ze,b.create=xe,b.createUploader=Ke,b.default=X,b.defaults=F,b.escapeHtml=ce,b.exportHtml=Ze,b.fastFingerprint=ke,b.formatHtml=ae,b.httpAdapter=Ve,b.isSafeUrl=Y,b.maybeCompress=Ie,b.mockAdapter=_e,b.mount=Ti,b.normalizeCustomButtons=Be,b.normalizeItems=G,b.normalizePosition=de,b.replace=Ai,b.sanitizeHtml=K,b.simpleAdapter=We,b.strongFingerprint=qe,b.version=zi,Object.defineProperties(b,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});
|
|
559
|
+
`).trim()}const On=6e4,fe=[["plaintext","纯文本",["text","txt","plain","none"],"不做着色,保留原始排版"],["javascript","JavaScript",["js","jsx","mjs","cjs","node"],"前端与 Node 脚本"],["typescript","TypeScript",["ts","tsx"],"带类型标注的 JS"],["html","HTML / XML",["xml","svg","vue","htm","markup"],"标签结构,内嵌 script / style 一并着色"],["css","CSS",["scss","less","sass","styl"],"样式表,兼容 scss / less"],["json","JSON",["jsonc"],"配置与接口数据"],["python","Python",["py"],"脚本与数据处理"],["java","Java",["kotlin"],"后端与安卓"],["go","Go",["golang"],"服务端与云原生"],["rust","Rust",["rs"],"系统级语言"],["c","C / C++",["cpp","c++","h","hpp","cc","objc"],"含预处理指令"],["csharp","C#",["cs","dotnet"],".NET 体系"],["php","PHP",[],"含 <?php ?> 标记"],["ruby","Ruby",["rb"],"含符号与实例变量"],["sql","SQL",["mysql","postgres","postgresql","sqlite","pg"],"建表与查询语句"],["bash","Shell / Bash",["sh","shell","zsh","console","terminal"],"命令行与脚本"],["yaml","YAML",["yml"],"CI 与部署配置"],["ini","INI / TOML",["toml","conf","env","properties"],"键值配置"],["markdown","Markdown",["md"],"文档与说明"],["diff","Diff / Patch",["patch"],"代码差异"]].map(([n,e,t,i])=>({value:n,label:e,aliases:t,hint:i})),Mt=new Map(fe.map(n=>[n.value,n.label])),Ge=new Map;for(const{value:n,aliases:e}of fe){Ge.set(n,n);for(const t of e)Ge.set(t,n)}function X(n){const e=String(n||"").trim().toLowerCase();return Ge.get(e)||"plaintext"}function _n(n){return Mt.get(X(n))||Mt.get("plaintext")}function Ke(n){const e=Array.isArray(n)&&n.length?new Set(n.map(X)):null,t=fe.filter(i=>!e||e.has(i.value));return(t.length?t:[fe[0]]).map(({value:i,label:r,hint:o})=>({value:i,label:r,hint:o}))}const R=[{re:/[^\S\n]+/y,cls:null},{re:/\n/y,cls:null}],B={re:/[A-Za-z_$][\w$]*/y,cls:null},O={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,cls:"num"},Y={re:/[A-Z][A-Za-z0-9_]*/y,cls:"typ"},U={re:/[A-Za-z_$][\w$]*(?=\s*\()/y,cls:"fn"},H={re:/[{}[\]();,.]+/y,cls:"op"},j={re:/[+\-*/%=!<>&|^~?:@]+/y,cls:"op"},G={re:/\/\*[\s\S]*?(?:\*\/|$)/y,cls:"com"},J={re:/\/\/[^\n]*/y,cls:"com"},K={re:/"(?:\\[\s\S]|[^\\"\n])*"/y,cls:"str"},Q={re:/'(?:\\[\s\S]|[^\\'\n])*'/y,cls:"str"},me=[K,Q,{re:/`(?:\\[\s\S]|[^\\`])*`/y,cls:"str"}],F=(n,e="y")=>({re:new RegExp(`\\b(?:${n})\\b`,e),cls:"kw"}),V=(n,e="y")=>({re:new RegExp(`\\b(?:${n})\\b`,e),cls:"typ"}),I=n=>({re:new RegExp(`\\b(?:${n})\\b`,"y"),cls:"bool"}),le=n=>({re:/[A-Za-z_$][\w$]*/y,cls:"fn",when:e=>n.includes(e)}),zt=V("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"),jn={plaintext:null,javascript:[...R,G,J,{re:/`(?:\\[\s\S]|\$\{(?:[^{}]|\{[^{}]*\})*\}|[^\\`])*`/y,cls:"str"},K,Q,{re:/\/(?![/*\s])(?:\\.|\[(?:\\.|[^\]\n])*\]|[^\\/\n])*\/[a-z]*/y,cls:"str"},I("true|false|null|undefined|NaN|Infinity"),F("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"),zt,Y,U,O,B,j,H],typescript:[...R,G,J,{re:/`(?:\\[\s\S]|\$\{(?:[^{}]|\{[^{}]*\})*\}|[^\\`])*`/y,cls:"str"},K,Q,I("true|false|null|undefined|NaN|Infinity"),F("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"),zt,Y,U,O,B,j,H],json:[...R,{re:/"(?:\\.|[^\\"\n])*"(?=\s*:)/y,cls:"key"},{re:/"(?:\\.|[^\\"\n])*"/y,cls:"str"},I("true|false|null"),O,B,H],css:[...R,G,J,{re:/@[\w-]+/y,cls:"kw"},K,Q,{re:/#[0-9a-fA-F]{3,8}\b/y,cls:"num"},{re:/[\w-]+(?=\s*\()/y,cls:"fn"},{re:/!important\b/y,cls:"kw"},{re:/[\w-]+(?=\s*:)/y,cls:"prop"},{re:/\.[a-zA-Z_-][\w-]*|#[\w-]+|::?[\w-]+|\[[^\]]*\]|\*|&/y,cls:"sel"},{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"},{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"},B,O,j,H],python:[...R,{re:/#[^\n]*/y,cls:"com"},{re:/'''[\s\S]*?'''|"""[\s\S]*?"""/y,cls:"str"},{re:/[rbfu]{0,2}'(?:\\.|[^\\'\n])*'|[rbfu]{0,2}"(?:\\.|[^\\"\n])*"/y,cls:"str"},{re:/@[\w.]+/y,cls:"meta"},I("True|False|None"),F("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"),V("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"),Y,U,O,B,j,H],java:[...R,G,J,me[0],me[1],{re:/@[\w.]+/y,cls:"meta"},I("true|false|null"),F("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"),V("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"),le(["class","interface","enum","record","new"]),Y,U,O,B,j,H],go:[...R,G,J,{re:/`[^`]*`/y,cls:"str"},K,Q,I("true|false|nil|iota"),F("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"),V("any|bool|byte|comparable|complex64|complex128|error|float32|float64|int|int8|int16|int32|int64|rune|string|uint|uint8|uint16|uint32|uint64|uintptr"),le(["func","type","struct","interface"]),Y,U,O,B,j,H],rust:[...R,G,J,K,{re:/'(?:\\.|[^\\'])'/y,cls:"str"},{re:/'[A-Za-z_]\w*/y,cls:"meta"},{re:/(?:r|b)?#*"(?:\\[\s\S]|[^\\"])*"#*/y,cls:"str"},{re:/#!?\[[^\]]*\]/y,cls:"meta"},I("true|false|None|Some|Ok|Err"),F("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"),V("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"),le(["fn","struct","enum","trait","impl","mod"]),Y,U,O,B,j,H],c:[{re:/^[ \t]*#[ \t]*\w+[^\n]*/my,cls:"meta"},...R,G,J,me[0],me[1],I("true|false|nullptr|NULL|stdin|stdout|stderr"),F("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"),V("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"),le(["struct","class","enum","union","namespace"]),Y,U,O,B,j,H],csharp:[{re:/^[ \t]*#[ \t]*\w+[^\n]*/my,cls:"meta"},...R,G,J,{re:/\$?"(?:""|\\.|[^\\"\n])*"/y,cls:"str"},me[1],I("true|false|null"),F("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"),V("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"),le(["class","struct","interface","enum","namespace","new"]),Y,U,O,B,j,H],php:[...R,{re:/<\?php|\?>|<\?=/y,cls:"meta"},G,J,{re:/#[^\n]*/y,cls:"com"},K,Q,{re:/\$[A-Za-z_]\w*/y,cls:"var"},I("true|false|null|TRUE|FALSE|NULL"),F("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"),V("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"),U,O,B,j,H],ruby:[{re:/^=begin[\s\S]*?^=end[^\n]*/my,cls:"com"},...R,{re:/#[^\n]*/y,cls:"com"},K,Q,{re:/%[wWiI][([{][^)\]}]*[)\]}]/y,cls:"str"},{re:/@@?[A-Za-z_]\w*|\$[A-Za-z_]\w*/y,cls:"var"},{re:/:[A-Za-z_]\w*[?!]?/y,cls:"typ"},I("true|false|nil|__FILE__|__LINE__"),F("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?"),Y,le(["def","class","module"]),U,O,B,j,H],sql:[...R,{re:/--[^\n]*/y,cls:"com"},G,{re:/'[^']*(?:''[^']*)*'/y,cls:"str"},{re:/"[^"]*"|`[^`]*`/y,cls:"var"},{re:/\$\$[\s\S]*?\$\$/y,cls:"str"},I("true|false|null"),F("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"),V("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"),U,O,B,j,H],bash:[{re:/^#![^\n]*/my,cls:"meta"},...R,{re:/#[^\n]*/y,cls:"com"},{re:/'[^']*'/y,cls:"str"},{re:/\$?"(?:\\[\s\S]|[^\\"\n])*"/y,cls:"str"},{re:/\$\{[^}\n]*\}|\$\(|\$[A-Za-z_]\w*|\$[0-9@*#?$!-]/y,cls:"var"},F("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"),V("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"),{re:/\{\d+(?:,\d*)?\}/y,cls:"num"},O,{re:/--?[A-Za-z][\w-]*/y,cls:"attr"},B,j,H],yaml:[{re:/^---[^\n]*|^\.\.\.[^\n]*/my,cls:"meta"},{re:/^[ \t]*-[ \t]/my,cls:"kw"},...R,{re:/#[^\n]*/y,cls:"com"},{re:/[|>][-+]?\d*\s*(?=\n|$)/y,cls:"meta"},{re:new RegExp("(?<![\\w$])&[\\w.-]+|\\*[\\w.-]+","y"),cls:"var"},{re:/!!?[\w:.-]+/y,cls:"meta"},I("true|false|null|yes|no|on|off|True|False|Null|~"),{re:/[\w$.-]+(?=\s*:(?:\s|$))/y,cls:"key"},K,Q,O,B,j,H],ini:[...R,{re:/[#;][^\n]*/y,cls:"com"},{re:/\[[^\]\n]*\]/y,cls:"kw"},{re:/"""[\s\S]*?"""|'''[\s\S]*?'''/y,cls:"str"},K,Q,I("true|false|yes|no|on|off"),{re:/[\w$.-]+(?=\s*=(?!=))/y,cls:"key"},{re:/\d{4}-\d{2}-\d{2}(?:[T ]\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})?)?/y,cls:"num"},O,B,j,H],markdown:[{re:/^[ \t]*```[^\n]*\n[\s\S]*?^[ \t]*```[ \t]*$/my,cls:"str"},{re:/^[ \t]*```[^\n]*/my,cls:"str"},{re:/^#{1,6}[ \t][^\n]*/my,cls:"kw"},{re:/^[ \t]*>[^\n]*/my,cls:"com"},{re:/^[ \t]*(?:-{3,}|\*{3,}|_{3,})[ \t]*$/my,cls:"com"},{re:/^[ \t]*(?:[-*+][ \t]|\d+\.[ \t])/my,cls:"kw"},...R,{re:/!?\[[^\]\n]*\]\([^)\n]*\)/y,cls:"str"},{re:/`[^`\n]+`/y,cls:"str"},{re:/\*\*[^*\n]+\*\*|__[^_\n]+__/y,cls:"typ"},{re:/\*[^*\n]+\*/y,cls:"var"},{re:/https?:\/\/[^\s)]+/y,cls:"fn"},{re:/<\/?[A-Za-z][^>\n]*>/y,cls:"tag"},H],diff:[{re:/^(?:diff|index|new file|deleted file|similarity|rename|Binary files)[^\n]*/my,cls:"meta"},{re:/^(?:---|\+\+\+)[^\n]*/my,cls:"meta"},{re:/^@@[^\n]*/my,cls:"kw"},{re:/^\+[^\n]*/my,cls:"ins"},{re:/^-[^\n]*/my,cls:"del"},{re:/^\\[^\n]*/my,cls:"com"},...R,B,H]};function In(n,e){let t="",i="",r="",o=0;const s=()=>{i&&(t+=q(i),i="")};for(;o<n.length;){let a=null,l=null;for(const h of e){if(h.when&&!h.when(r))continue;h.re.lastIndex=o;const g=h.re.exec(n);if(g&&g[0]){a=h,l=g;break}}if(!l){i+=n[o],o+=1;continue}const c=l[0];a.cls?(s(),t+=`<span class="ke-tok-${a.cls}">${q(c)}</span>`):i+=c;const u=c.trim();u&&(r=u),o+=c.length}return s(),t}const Tt=/<\/?([A-Za-z][\w:.-]*)/y;function Pn(n,e,t,i){let r=e,o=!1;for(;r<n.length;){const s=n.slice(r);let a=/^[\s]+/.exec(s);if(a){i(null,a[0]),r+=a[0].length;continue}if(a=/^\/?>/.exec(s),a){i("tag",a[0]),r+=a[0].length,o=!0;break}if(a=/^[^\s=/>]+/.exec(s),a){i("attr",a[0]),r+=a[0].length;continue}if(a=/^=/.exec(s),a){i("op",a[0]),r+=a[0].length;continue}i(null,n[r]),r+=1}return{index:r,closed:o}}function Fn(n){let e="",t="",i=0;const r=()=>{t&&(e+=q(t),t="")},o=(s,a,l=!1)=>{s?(r(),e+=l?a:`<span class="ke-tok-${s}">${q(a)}</span>`):t+=a};for(;i<n.length;){const s=n.slice(i);let a=/^<!--[\s\S]*?(?:-->|$)/.exec(s);if(a){o("com",a[0]),i+=a[0].length;continue}if(a=/^<!\[CDATA\[[\s\S]*?(?:\]\]>|$)/.exec(s),a){o("str",a[0]),i+=a[0].length;continue}if(a=/^<[!?][^>]*/.exec(s),a){o("meta",a[0]),i+=a[0].length;continue}if(Tt.lastIndex=i,a=Tt.exec(n),a){o("tag",a[0]),i+=a[0].length;const l=a[1].toLowerCase(),c=Pn(n,i,e,o);if(i=c.index,c.closed&&(l==="script"||l==="style")){const u=n.toLowerCase().indexOf(`</${l}`,i);u>i&&(o("raw",Ae(n.slice(i,u),l==="script"?"javascript":"css"),!0),i=u)}continue}if(a=/^&[#\w]+;/.exec(s),a){o("num",a[0]),i+=a[0].length;continue}t+=n[i],i+=1}return r(),e}function Ae(n,e){const t=String(n??""),i=X(e);if(i==="plaintext"||t.length>On)return q(t);if(i==="html")return Fn(t);const r=jn[i];return r?In(t,r):q(t)}function $e(n){return!n||n.nodeType!==1||n.tagName!=="PRE"?!1:n.hasAttribute("data-k-lang")?!0:Array.from(n.children).some(e=>e.tagName==="CODE")}function ge(n,e){var i;let t=e||((i=window.getSelection())!=null&&i.rangeCount?window.getSelection().getRangeAt(0).startContainer:null);if(!t||!n||!n.contains(t))return null;for(;t&&t!==n;){if(t.nodeType===1&&t.tagName==="PRE")return $e(t)?t:null;t=t.parentNode}return null}function Re(n){const e=Array.from(n.children).find(i=>i.tagName==="CODE");if(e)return e;const t=document.createElement("code");for(;n.firstChild;)t.appendChild(n.firstChild);return n.appendChild(t),t}function ce(n){if(!n)return"";const e=n.getAttribute("data-k-lang");if(e)return X(e);const t=Array.from(n.children).find(r=>r.tagName==="CODE"),i=/(?:^|\s)language-([\w+#-]+)/.exec((t==null?void 0:t.className)||"");return i?X(i[1]):""}function Ve(n,e){const t=X(e),i=Re(n);n.setAttribute("data-k-lang",t);const r=(i.className||"").split(/\s+/).filter(o=>o&&!/^language-/.test(o));return t!=="plaintext"&&r.push(`language-${t}`),i.className=r.join(" "),i.className||i.removeAttribute("class"),t}function Ze(n){const e=n.cloneNode(!0);return e.querySelectorAll("br").forEach(t=>t.replaceWith(`
|
|
560
|
+
`)),e.querySelectorAll("div, p").forEach(t=>t.replaceWith(document.createTextNode(`
|
|
561
|
+
${t.textContent}`))),e.textContent.replace(/\u00a0/g," ")}function Dn(n){const e=window.getSelection();if(!e||!e.rangeCount)return null;const t=e.getRangeAt(0);if(!n.contains(t.startContainer))return null;const i=document.createRange();return i.selectNodeContents(n),i.setEnd(t.startContainer,t.startOffset),Ze(i.cloneContents())}function qn(n,e){const t=window.getSelection();if(!t)return;const i=(a,l)=>{if(!a)return;const c=document.createRange();a.nodeType===3?c.setStart(a,Math.max(0,Math.min(a.data.length,l))):c.setStartAfter(a),c.collapse(!0),t.removeAllRanges(),t.addRange(c)};let r=0,o=!1;const s=a=>{const l=Array.from(a.childNodes);for(const c of l)if(c.nodeType===3){const u=c.data.length;if(r+u>=e)return i(c,e-r),!0;r+=u}else if(c.nodeType===1){if(c.tagName==="BR"){if(r+1>=e)return i(c),!0;r+=1}else if(c.tagName==="DIV"||c.tagName==="P"){if(r+=1,s(c))return!0}else if(s(c))return!0}return!1};if(o=s(n),!o){const a=document.createRange();a.selectNodeContents(n),a.collapse(!1),t.removeAllRanges(),t.addRange(a)}}function He(n,{caret:e=!1}={}){if(!$e(n))return!1;const t=Re(n);n.hasAttribute("data-k-lang")||Ve(n,ce(n)||"plaintext");const i=Ze(t),r=Ae(i,ce(n));if(t.innerHTML===r)return!1;const o=e?Dn(t):null;return t.innerHTML=r,o!==null&&qn(t,o),!0}function At(n,{highlight:e=!0}={}){if(!n)return 0;let t=0;return n.querySelectorAll("pre").forEach(i=>{if(!$e(i))return;const r=Re(i);i.hasAttribute("data-k-lang")||i.setAttribute("data-k-lang",ce(i)||"plaintext");const o=Ze(r),s=e?Ae(o,ce(i)):q(o);r.innerHTML!==s&&(r.innerHTML=s),t+=1}),t}function Un(n){if(!n)return 0;const e=n.querySelectorAll('span[class*="ke-tok-"]');return e.forEach(t=>t.replaceWith(document.createTextNode(t.textContent))),e.length&&n.normalize(),e.length}const Wn=/\.(md|markdown|mdown|mkd|mkdn|mdx|txt)$/i,Gn=/^text\/(markdown|x-markdown)$|^application\/(x-)?markdown$/i;function $t(n){if(!n)return!1;const e=String(n.name||""),t=String(n.type||"");return Gn.test(t)?!0:t&&!/^text\//i.test(t)?!1:Wn.test(e)}const Rt=".md,.markdown,.mdown,.mkd,.mkdn,.mdx,.txt,text/markdown,text/plain";function ke(n){return n==="append"||n==="cursor"?n:"replace"}async function Xe(n){if(!n)return"";if(typeof n.arrayBuffer!="function")return String(await n.text());const e=await n.arrayBuffer();try{return Ye(e,"utf-8",!0)}catch{for(const t of["gb18030","gbk","big5"])try{return Ye(e,t,!0)}catch{}return Ye(e,"utf-8",!1)}}function Ye(n,e,t){return new TextDecoder(e,{fatal:t}).decode(n)}const Ht=/^ {0,3}(#{1,6})(?:[ \t]+(.*?))?[ \t]*#*[ \t]*$/,Kn=/^ {0,3}(=+|-+)[ \t]*$/,Bt=/^ {0,3}(?:(?:\*[ \t]*){3,}|(?:-[ \t]*){3,}|(?:_[ \t]*){3,})$/,Je=/^( {0,3})(`{3,}|~{3,})[ \t]*([^`\n]*)$/,Qe=/^ {0,3}>/,Vn=/^ {0,3}\[([^\]]+)\]:[ \t]*<?([^\s>]+)>?(?:[ \t]+(?:"([^"]*)"|'([^']*)'|\(([^)]*)\)))?[ \t]*$/,Nt=/^ {0,3}\|?[ \t]*:?-+:?[ \t]*(?:\|[ \t]*:?-+:?[ \t]*)*\|?[ \t]*$/,Ot=/^ {0,3}<(\/?)([A-Za-z][\w-]*)(\s|\/?>|$)/,Zn=new Set(["div","section","article","aside","header","footer","main","nav","center","font","span","table","thead","tbody","tfoot","tr","td","th","caption","colgroup","col","dl","dt","dd","figure","figcaption","details","summary","pre","hr","br","img","a","video","source","p","ul","ol","li","blockquote","h1","h2","h3","h4","h5","h6","strong","em","b","i","u","s","del","ins","mark","code","kbd","samp","small","sub","sup","abbr","time"]),Xn=new Set(["a","img","br","wbr","em","i","strong","b","u","s","del","ins","mark","sub","sup","kbd","code","samp","var","span","small","abbr","cite","q","time","font","sup"]),Yn=/^<(\/?)([A-Za-z][A-Za-z0-9-]*)((?:\s+[^<>]*?)?)(\/?)>/,Jn=/^<([A-Za-z][A-Za-z0-9+.-]{1,31}:[^<>\s]*)>/,Qn=/^<([^\s<>@]+@[^\s<>@]+\.[^\s<>@]+)>/,ei=/[!-/:-@[-`{-~]/,_t=/[!-/:-@[-`{-~]/,jt=/(^|[\s(([【>])((?:https?:\/\/|www\.)[^\s<>()"']*[^\s<>()"'.,;:!?、。,;:!?])/g;function ti(n){return{gfm:n.gfm!==!1,breaks:!!n.breaks,linkTarget:n.linkTarget||!1,frontMatter:n.frontMatter!==!1,sanitize:n.sanitize!==!1}}function et(n,e={}){if(n==null)return"";const t=ti(e);let i=String(n).replace(/^\uFEFF/,"").replace(/\r\n?/g,`
|
|
562
|
+
`).replace(/\u0000/g,"");i=i.replace(/\t/g," "),t.frontMatter&&(i=ni(i));const r=new Map,s=nt(i.split(`
|
|
563
|
+
`),r,t).map(a=>ot(a,r,t)).join(`
|
|
564
|
+
`);return t.sanitize?ae(s,{allowEmpty:!0}):s}function tt(n){const e=t=>(String(n||"").match(t)||[]).length;return{headings:e(/<h[1-6][\s>]/g),paragraphs:e(/<p[\s>]/g),lists:e(/<[uo]l[\s>]/g),items:e(/<li[\s>]/g),codeBlocks:e(/<pre[\s>]/g),quotes:e(/<blockquote[\s>]/g),tables:e(/<table[\s>]/g),images:e(/<img[\s>]/g),links:e(/<a\s[^>]*href=/g)}}function ni(n){const e=/^---[ \t]*\n([\s\S]*?)\n(?:---|\.\.\.)[ \t]*(?:\n|$)/.exec(n);return e?n.slice(e[0].length):n}const Z=n=>!n||!n.trim(),ii=n=>n.length-n.replace(/^ +/,"").length;function de(n){const e=/^( *)([-+*]|\d{1,9}[.)])([ \t]*)([\s\S]*)$/.exec(n);if(!e)return null;const[,t,i,r,o]=e;if(r.length===0&&o.length||o.length===0&&r.length===0&&!/^[-+*]$/.test(i))return null;const s=/^\d/.test(i),a=r.length||1;return{indent:t.length,marker:i,ordered:s,start:s&&parseInt(i,10)||1,contentIndent:t.length+i.length+a,text:o}}function Be(n,e){return Ht.test(n)||Je.test(n)||Bt.test(n)||Qe.test(n)||Ot.test(n)||!!de(n)||e.gfm&&Nt.test(n)}function nt(n,e,t,i){const r=[];let o=0;for(;o<n.length;){const s=n[o];if(Z(s)){o+=1;continue}const a=Je.exec(s);if(a){const p=a[1].length,f=a[2],k=a[3].trim(),m=[];for(o+=1;o<n.length;){const x=Je.exec(n[o]);if(x&&x[2][0]===f[0]&&x[2].length>=f.length&&!x[3].trim())break;m.push(p?n[o].slice(0,p).trim()?n[o]:n[o].slice(p):n[o]),o+=1}o<n.length&&(o+=1),r.push({t:"code",lang:It(k),text:m.join(`
|
|
565
|
+
`)});continue}if(/^ {4}/.test(s)&&!de(s.replace(/^ {4}/,""))){const p=[];for(;o<n.length&&(Z(n[o])?ri(n,o):/^ {4}/.test(n[o]));)p.push(n[o].slice(4)),o+=1;for(;p.length&&Z(p[p.length-1]);)p.pop();r.push({t:"code",lang:"",text:p.join(`
|
|
566
|
+
`)});continue}const l=Ht.exec(s);if(l){r.push({t:"h",level:l[1].length,raw:(l[2]||"").replace(/[ \t]+#+[ \t]*$/,"").trim()}),o+=1;continue}if(Bt.test(s)){r.push({t:"hr"}),o+=1;continue}if(Qe.test(s)){const p=[];for(;o<n.length;){const f=n[o];if(Qe.test(f)){p.push(f.replace(/^ {0,3}> ?/,"")),o+=1;continue}if(Z(f)||Be(f,t))break;p.push(f),o+=1}r.push({t:"quote",children:nt(p,e,t)});continue}const c=de(s);if(c){const p=si(n,o,c,e,t);r.push(p.node),o=p.next;continue}if(t.gfm&&s.includes("|")&&o+1<n.length&&Nt.test(n[o+1])&&n[o+1].includes("-")){const p=li(n,o,e,t);r.push(p.node),o=p.next;continue}const u=Ot.exec(s);if(u&&Zn.has(u[2].toLowerCase())){const p=[];for(;o<n.length&&!Z(n[o]);)p.push(n[o]),o+=1;r.push({t:"html",raw:p.join(`
|
|
567
|
+
`)});continue}const h=[];let g=null;for(;o<n.length&&!Z(n[o]);){const p=n[o];if(h.length===1&&Kn.test(p)){g=p.trim()[0]==="="?1:2,o+=1;break}if(h.length>0&&Be(p,t))break;if(h.length===0){const k=Vn.exec(p);if(k){oi(e,k),o+=1;continue}}const f=/(?: {2,}|\\)$/.test(p);h.push(f?p.replace(/(?: +|\\)$/,""):p),f&&(h[h.length-1]+=""),o+=1}if(h.length){const p=h.join(`
|
|
568
|
+
`).replace(/\u0001\n/g,"");g?r.push({t:"h",level:g,raw:p.trim()}):r.push({t:"p",raw:p})}}return r}function ri(n,e){let t=e;for(;t<n.length&&Z(n[t]);)t+=1;return t<n.length&&/^ {4}/.test(n[t])}function oi(n,e){const t=it(e[1]);!t||n.has(t)||n.set(t,{href:e[2]||"",title:e[3]??e[4]??e[5]??""})}function it(n){return String(n||"").trim().replace(/\s+/g," ").toLowerCase()}function It(n){const e=String(n||"").trim();return e?e.split(/\s+/)[0]:""}function si(n,e,t,i,r,o){const s=t.ordered?"ol":"ul",a=t.indent,l=[];let c=!1,u=e;for(;u<n.length;){const h=de(n[u]);if(!h||h.indent!==a||h.ordered!==t.ordered)break;const g=h.contentIndent,p=[h.text];u+=1;let f=0;for(;u<n.length;){const k=n[u];if(Z(k)){p.push(""),f+=1,u+=1;continue}const m=ii(k);if(de(k)&&m<=a)break;if(m>=g){p.push(k.slice(g)),f>0&&(c=!0),f=0,u+=1;continue}if(f>0||Be(k,r))break;p.push(k.replace(/^ {0,3}/,"")),u+=1}for(;p.length&&Z(p[p.length-1]);)p.pop();if(f>0){const k=u<n.length?de(n[u]):null;k&&k.indent===a&&k.ordered===t.ordered&&(c=!0)}l.push(ai(p,s,i,r))}return{node:{t:s,start:t.start,loose:c,items:l},next:u}}function ai(n,e,t,i){let r=null;if(e==="ul"&&n.length){const o=/^\[([ xX])\][ \t]+/.exec(n[0]);o&&(r=o[1].toLowerCase()==="x",n[0]=n[0].slice(o[0].length))}return{checked:r,children:nt(n,t,i)}}function li(n,e,t,i){const r=rt(n[e]),o=rt(n[e+1]).map(u=>{const h=u.trim();return/^:-+:$/.test(h)?"center":/^-+:$/.test(h)?"right":"left"}),s=[];let a=e+2;for(;a<n.length&&!Z(n[a])&&n[a].includes("|")&&!Be(n[a],i);)s.push(rt(n[a])),a+=1;const l=Math.max(r.length,o.length),c=u=>{const h=u.slice(0,l);for(;h.length<l;)h.push("");return h};return{node:{t:"table",align:c(o),head:c(r),rows:s.map(c)},next:a}}function rt(n){let e=n.trim();e.startsWith("|")&&(e=e.slice(1)),e.endsWith("|")&&!e.endsWith("\\|")&&(e=e.slice(0,-1));const t=[];let i="";for(let r=0;r<e.length;r+=1){const o=e[r];if(o==="\\"&&e[r+1]==="|"){i+="\\|",r+=1;continue}if(o==="|"){t.push(i),i="";continue}i+=o}return t.push(i),t.map(r=>r.trim())}function Ne(n,e,t){return be(Pt(String(n||""),e,t),e,t)}function Pt(n,e,t,i=!1){return gi(ci(n,e,t,i))}function ci(n,e,t,i=!1){const r=[],o=a=>{if(!a)return;const l=r[r.length-1];l&&l.type==="text"&&l.bare?l.value+=a:r.push({type:"text",value:a,bare:!0})};let s=0;for(;s<n.length;){const a=n[s];if(a==="\\"){const u=n[s+1];if(u===`
|
|
569
|
+
`){r.push({type:"br"}),s+=2;continue}if(u&&ei.test(u)){o(u),s+=2;continue}o("\\"),s+=1;continue}if(a==="`"){const u=/^`+/.exec(n.slice(s))[0],h=Ft(n,s+u.length,u);if(h<0){o(u),s+=u.length;continue}let g=n.slice(s+u.length,h).replace(/\n/g," ");g.length>2&&/^ .* $/.test(g)&&/[^ ]/.test(g)&&(g=g.slice(1,-1)),r.push({type:"code",value:g}),s=h+u.length;continue}if(a==="["||a==="!"&&n[s+1]==="["){const u=a==="!",h=hi(n,u?s+1:s,e,t,u);if(h){r.push(h.node),s=h.next;continue}}if(a==="<"){const u=Jn.exec(n.slice(s));if(u){r.push({type:"link",href:u[1],title:"",children:[{type:"text",value:u[1],bare:!1}]}),s+=u[0].length;continue}const h=Qn.exec(n.slice(s));if(h){r.push({type:"link",href:`mailto:${h[1]}`,title:"",children:[{type:"text",value:h[1],bare:!1}]}),s+=h[0].length;continue}const g=Yn.exec(n.slice(s));if(g&&Xn.has(g[2].toLowerCase())){r.push({type:"html",value:qt(g[0])}),s+=g[0].length;continue}o("<"),s+=1;continue}if(a===`
|
|
570
|
+
`){const u=r[r.length-1],h=t.breaks||u&&u.type==="text"&&/ {2,}$/.test(u.value);u&&u.type==="text"&&(u.value=u.value.replace(/[ \t]+$/,"")),h?r.push({type:"br"}):o(`
|
|
571
|
+
`),s+=1;continue}if(a==="*"||a==="_"||a==="~"&&t.gfm){const u=new RegExp(`^\\${a}+`).exec(n.slice(s))[0],h=n[s-1]||"",g=n[s+u.length]||"",p=di(a,u,h,g);r.push({type:"delim",char:a,count:u.length,canOpen:p.canOpen,canClose:p.canClose}),s+=u.length;continue}const l=/^[^\\`[<!*_~\n]+/.exec(n.slice(s)),c=l?l[0]:a;t.gfm&&!i?ui(r,c):o(c),s+=c.length}return r}function Ft(n,e,t){let i=n.indexOf(t,e);for(;i>=0;){const r=n[i-1],o=n[i+t.length];if(r!=="`"&&o!=="`")return i;i=n.indexOf(t,i+1)}return-1}function di(n,e,t,i){const r=t?t===`
|
|
572
|
+
`?`
|
|
573
|
+
`:t:"",o=i||"",s=!r||/\s/.test(r),a=!o||/\s/.test(o),l=!!r&&_t.test(r),c=!!o&&_t.test(o),u=!a&&(!c||s||l),h=!s&&(!l||a||c);return n==="_"?{canOpen:u&&(!h||l),canClose:h&&(!u||c)}:{canOpen:u,canClose:h}}function ui(n,e){let t=0;jt.lastIndex=0;let i;for(;i=jt.exec(e);){const r=i.index+i[1].length;r>t&&Dt(n,e.slice(t,r));const o=/^www\./i.test(i[2])?`http://${i[2]}`:i[2];n.push({type:"link",href:o,title:"",children:[{type:"text",value:i[2],bare:!1}]}),t=r+i[2].length}t<e.length&&Dt(n,e.slice(t))}function Dt(n,e){if(!e)return;const t=n[n.length-1];t&&t.type==="text"&&t.bare?t.value+=e:n.push({type:"text",value:e,bare:!0})}function hi(n,e,t,i,r){const o=fi(n,e);if(o<0)return null;const s=n.slice(e+1,o);let a=o+1,l=null,c="";if(n[a]==="("){const h=mi(n,a);if(!h)return null;l=h.href,c=h.title,a=h.next}else if(n[a]==="["){const h=n.indexOf("]",a+1);if(h<0)return null;const g=it(n.slice(a+1,h)||s),p=t.get(g);if(!p)return null;l=p.href,c=p.title,a=h+1}else{const h=t.get(it(s));if(!h)return null;l=h.href,c=h.title}if(r)return re(l)?{node:{type:"image",src:l,title:c,alt:pi(s)},next:a}:{node:{type:"text",value:`![${s}]`},next:a};const u=Pt(s,t,i,!0);return{node:{type:"link",href:l,title:c,children:u},next:a}}function pi(n){return typeof n=="string"?n.replace(/[*_~`]/g,""):""}function fi(n,e){let t=0;for(let i=e;i<n.length;i+=1){const r=n[i];if(r==="\\"){i+=1;continue}if(r==="`"){const o=/^`+/.exec(n.slice(i))[0],s=Ft(n,i+o.length,o);i=s<0?i+o.length-1:s+o.length-1;continue}if(r==="[")t+=1;else if(r==="]"){if(t-=1,t===0)return i}else if(r===`
|
|
574
|
+
`&&t===1&&n[i+1]===`
|
|
575
|
+
`)return-1}return-1}function mi(n,e){let t=e+1;for(;n[t]===" "||n[t]===`
|
|
576
|
+
`;)t+=1;let i="";if(n[t]==="<"){const s=n.indexOf(">",t+1);if(s<0)return null;i=n.slice(t+1,s).replace(/\\([\\<>])/g,"$1"),t=s+1}else{let s=0,a="";for(;t<n.length;){const l=n[t];if(l==="\\"&&n[t+1]){a+=n[t+1],t+=2;continue}if(l==="("&&(s+=1),l===")"){if(s===0)break;s-=1}if(/\s/.test(l)&&s===0)break;a+=l,t+=1}i=a}for(;n[t]===" "||n[t]===`
|
|
577
|
+
`;)t+=1;let r="";const o=n[t];if(o==='"'||o==="'"||o==="("){const s=o==="("?")":o,a=n.indexOf(s,t+1);if(a<0)return null;for(r=n.slice(t+1,a),t=a+1;n[t]===" "||n[t]===`
|
|
578
|
+
`;)t+=1}return n[t]!==")"?null:{href:i.trim(),title:r,next:t+1}}function gi(n){const e=[],t=[];for(const i of n){if(i.type!=="delim"){e.push(i);continue}const{char:r,canOpen:o,canClose:s}=i,a={type:"text",value:r.repeat(i.count),bare:!1};if(e.push(a),r==="~"&&i.count<2)continue;const l={char:r,count:i.count,canOpen:o,canClose:s,node:a};if(!s){o&&t.push(l);continue}for(;l.count>0;){const c=e.indexOf(l.node);if(c<0)break;let u=-1;for(let m=t.length-1;m>=0;m-=1){const x=t[m];if(x===l||x.char!==r||!x.canOpen||x.count<=0||r==="~"&&x.count<2)continue;const C=e.indexOf(x.node);if(!(C<0||C>=c)&&!(r!=="~"&&(x.canClose||l.canOpen)&&(x.count+l.count)%3===0&&!(x.count%3===0&&l.count%3===0))){u=m;break}}if(u<0)break;const h=t[u],g=r==="~"?2:Math.min(h.count,l.count)>=3?3:Math.min(h.count,l.count,2);if(g<=0)break;const p=e.slice(e.indexOf(h.node)+1,c);h.count-=g,l.count-=g,h.node.value=r.repeat(h.count),l.node.value=r.repeat(l.count);const f=ki(r,g,p);e.splice(c,1);const k=e.indexOf(h.node);h.node.value?e.splice(k+1,c-k-1,f):e.splice(k,c-k,f);for(let m=t.length-1;m>=0;m-=1)t[m]!==h&&(!t[m].count||e.indexOf(t[m].node)<0)&&t.splice(m,1);if(h.count<=0){const m=t.indexOf(h);m>=0&&t.splice(m,1)}}l.count>0&&l.canOpen&&e.indexOf(l.node)>=0&&t.push(l)}return e}function ki(n,e,t){return n==="~"?{type:"del",children:t}:e>=3?{type:"strong",children:[{type:"em",children:t}]}:e===2?{type:"strong",children:t}:{type:"em",children:t}}function ot(n,e,t){switch(n.t){case"p":return`<p>${Ne(n.raw,e,t)}</p>`;case"h":return`<h${n.level}>${Ne(n.raw,e,t)}</h${n.level}>`;case"hr":return"<hr>";case"code":return bi(n);case"html":return Si(qt(n.raw));case"quote":return`<blockquote>
|
|
579
|
+
${n.children.map(i=>ot(i,e,t)).join(`
|
|
580
|
+
`)}
|
|
581
|
+
</blockquote>`;case"ul":case"ol":{const i=n.t==="ol"&&n.start!==1?` start="${n.start}"`:"",r=n.items.map(o=>xi(o,n.loose,e,t)).join(`
|
|
582
|
+
`);return`<${n.t}${i}>
|
|
583
|
+
${r}
|
|
584
|
+
</${n.t}>`}case"table":return yi(n,e,t);default:return""}}function bi(n){const e=It(n.lang),t=e?X(e):"plaintext",i=t==="plaintext"?"":` data-k-lang="${t}"`,r=t==="plaintext"?"":` class="language-${t}"`;return`<pre${i}><code${r}>${st(n.text)}</code></pre>`}function xi(n,e,t,i){let r;const o=n.children;return!e&&o.length===1&&o[0].t==="p"?r=Ne(o[0].raw,t,i):(r=o.map(s=>ot(s,t,i)).join(`
|
|
585
|
+
`),e||(r=r.replace(/^<p>([\s\S]*?)<\/p>/,"$1"))),n.checked===null||n.checked===void 0?`<li>${r}</li>`:`<li>${n.checked?"☑":"☐"} ${r}</li>`}function yi(n,e,t){const i=(s,a,l)=>{const c=n.align[l],u=c&&c!=="left"?` style="text-align:${c}"`:"";return`<${s}${u}>${Ne(a,e,t)}</${s}>`},r=`<tr>${n.head.map((s,a)=>i("th",s,a)).join("")}</tr>`,o=n.rows.map(s=>`<tr>${s.map((a,l)=>i("td",a,l)).join("")}</tr>`);return o.length?`<table><thead>${r}</thead><tbody>${o.join("")}</tbody></table>`:`<table><thead>${r}</thead></table>`}function be(n,e,t){return n.map(i=>vi(i,e,t)).join("")}function vi(n,e,t){switch(n.type){case"text":return st(n.value).replace(/\u0001/g,"<br>");case"code":return`<code>${st(n.value)}</code>`;case"br":return"<br>";case"html":return n.value;case"em":return`<em>${be(n.children,e,t)}</em>`;case"strong":return`<strong>${be(n.children,e,t)}</strong>`;case"del":return`<del>${be(n.children,e,t)}</del>`;case"image":{const i=n.title?` title="${xe(n.title)}"`:"";return`<img src="${xe(n.src)}" alt="${xe(n.alt)}"${i}>`}case"link":{const i=re(n.href)?n.href:"#",r=n.title?` title="${xe(n.title)}"`:"",o=t.linkTarget?' target="_blank" rel="noopener noreferrer"':"";return`<a href="${xe(i)}"${r}${o}>${be(n.children,e,t)}</a>`}default:return""}}const wi=/<(script|style|iframe|object|embed|form|link|meta|base)\b[^>]*>[\s\S]*?<\/\1\s*>/gi,Ci=/<\/?(?:script|style|iframe|object|embed|form|link|meta|base)\b[^>]*>/gi;function Si(n){return String(n).replace(wi,"").replace(Ci,"")}const Ei=/\s(href|src)\s*=\s*("([^"]*)"|'([^']*)'|([^\s>]+))/gi;function qt(n){return String(n).replace(Ei,(e,t,i,r,o,s)=>re(r??o??s??"")?e:"")}const Li=/&(?![a-zA-Z][a-zA-Z0-9]{1,31};|#\d{1,7};|#[xX][0-9a-fA-F]{1,6};)/g;function st(n){return String(n??"").replace(Li,"&").replace(/</g,"<").replace(/>/g,">")}function xe(n){return String(n||"").replace(/&/g,"&").replace(/"/g,""").replace(/</g,"<").replace(/>/g,">")}const at=[["#07c160","微信绿"],["#2f6fed","科技蓝"],["#7c3aed","极光紫"],["#d53880","品红"],["#e53e3e","中国红"],["#ed8936","暮橙"],["#f6c344","明黄"],["#0f766e","松石绿"]],Mi=[["#1f2329","墨黑"],["#6b7280","深灰"],["#b8bec7","浅灰"],["#f2f3f5","云灰"],["#ffffff","纯白"],["#c00000","深红"],["#ff0000","正红"],["#ffc000","琥珀"],["#ffff00","柠黄"],["#00b050","草绿"],["#00b0f0","天蓝"],["#0070c0","海蓝"],["#7030a0","葡萄紫"],["#ff69b4","桃花粉"]],Ut=[["#fef08a","柠檬底"],["#dcfce7","薄荷底"],["#e0f2fe","天空底"],["#ede9fe","薰衣底"],["#ffe4e6","樱花底"],["#fff4e6","奶茶底"],["#f2f3f5","纸张灰"],["#1f2329","夜墨"]],lt=/^#([0-9a-f]{3}|[0-9a-f]{6})$/i;class zi{constructor(e){this.root=e,this.el=d("div.ke-pop",{hidden:!0}),this.anchor=null,this.onClose=null,e.appendChild(this.el),this.el.addEventListener("mousedown",t=>{/^(input|textarea|select)$/i.test(t.target.tagName)||t.preventDefault()}),this.docHandler=t=>{var i,r;this.el.hidden||this.el.contains(t.target)||(r=(i=t.target).closest)!=null&&r.call(i,".ke-btn[data-k-pop]")||this.close()},document.addEventListener("mousedown",this.docHandler,!0),this.keyHandler=t=>{t.key==="Escape"&&this.close()},document.addEventListener("keydown",this.keyHandler),this.resizeHandler=()=>{this.el.hidden||this.place()},window.addEventListener("resize",this.resizeHandler)}open(e,t,{align:i="start",onClose:r}={}){var a;this.el.textContent="";const o=t(l=>this.el.appendChild(l));o&&this.el.appendChild(o),this.el.hidden=!1,this.anchor=e,this.align=i,this.onClose=r,this.place(),this.el.classList.remove("ke-pop-in"),this.el.offsetWidth,this.el.classList.add("ke-pop-in");const s=[...this.el.querySelectorAll("[data-k-autofocus]")].find(l=>l.offsetParent!==null);(a=s==null?void 0:s.focus)==null||a.call(s)}place(){const e=this.anchor;if(!e)return;this.el.style.removeProperty("--ke-pop-max");const t=this.align,i=this.root.getBoundingClientRect(),r=e.getBoundingClientRect(),o=Math.max(0,-i.top),s=Math.min(i.height,window.innerHeight-i.top),a=this.el.getBoundingClientRect();let l=r.left-i.left;t==="center"&&(l=r.left-i.left+r.width/2-a.width/2),t==="end"&&(l=r.right-i.left-a.width),l=Math.max(8,Math.min(l,i.width-a.width-8));const c=r.top-i.top+r.height+8,u=r.top-i.top-8,h=Math.max(0,s-o-16),g=s-8-c,p=u-o,f=g>=320?Math.min(g,h):h,k=Math.max(180,Math.min(a.height,f));k<a.height&&this.el.style.setProperty("--ke-pop-max",`${Math.round(k)}px`);let m;k<=g?m=c:p>g&&k<=p?m=u-k:m=s-8-k,m=Math.max(o,Math.min(m,Math.max(o,s-8-k))),this.el.style.left=`${l}px`,this.el.style.top=`${m}px`}close(){if(this.el.hidden)return;this.el.hidden=!0,this.el.classList.remove("ke-pop-in"),this.el.textContent="",this.anchor=null;const e=this.onClose;this.onClose=null,e==null||e()}get isOpen(){return!this.el.hidden}destroy(){document.removeEventListener("mousedown",this.docHandler,!0),document.removeEventListener("keydown",this.keyHandler),window.removeEventListener("resize",this.resizeHandler),this.el.remove()}}function ee(n,e){const t=d("div.ke-panel-head",{},[d("span.ke-panel-title",{text:n})]);return e&&t.appendChild(e),d("div.ke-panel",{},[t])}function ye(n){return d("div.ke-panel-sect",{text:n})}function Wt(){return d("div.ke-panel-divider")}function Ti({languages:n,value:e,editing:t,onPick:i}){const r=ee(t?"代码块语言":"插入代码块");r.classList.add("ke-panel-wide","ke-code-panel");const o=d("span.ke-panel-note");r.querySelector(".ke-panel-head").appendChild(o);const s=d("input.ke-input.ke-sel-search",{type:"search",placeholder:"搜索语言,如 js / python","data-k-autofocus":""});r.appendChild(s);const a=d("div.ke-code-list");r.appendChild(a),r.appendChild(d("div.ke-panel-hint",{text:t?"切换后会立即重新高亮当前代码块":"插入后点「代码块」按钮可随时切换语言"}));let l=n;function c(){const u=s.value.trim().toLowerCase();if(l=u?n.filter(h=>`${h.label} ${h.hint} ${h.value}`.toLowerCase().includes(u)):n,o.textContent=u?`${l.length} / ${n.length} 种`:`${n.length} 种语言`,a.textContent="",!l.length){a.appendChild(d("div.ke-sel-tip",{},[d("span.ke-sel-tip-text",{text:`没有匹配「${s.value.trim()}」的语言`})]));return}l.forEach(h=>{const g=d("button.ke-sel-row",{type:"button",dataset:{kLang:h.value},onclick:()=>i(h.value)},[d("span.ke-sel-main",{},[d("span.ke-sel-label",{text:h.label}),d("span.ke-sel-desc",{text:h.hint})])]);h.value===e&&(g.classList.add("ke-is-active"),g.appendChild(d("span.ke-sel-check",{html:_("check")}))),a.appendChild(g)})}return s.addEventListener("input",c),s.addEventListener("keydown",u=>{u.key==="Enter"&&(u.preventDefault(),l.length&&i(l[0].value))}),c(),r}function Ai({insertMode:n="replace",accept:e="",maxText:t="",highlight:i=!0,onConvert:r,onImport:o}){const s=ee("导入 Markdown");s.classList.add("ke-panel-wide","ke-md-panel");const a=d("span.ke-panel-note",{text:"尚未选择文件"});s.querySelector(".ke-panel-head").appendChild(a);const l={text:"",name:"",mode:n,picked:!1},c=d("div.ke-tab-body"),u=d("div.ke-tab-body",{hidden:!0}),h=d("div.ke-tabs",{},[d("button.ke-tab",{type:"button",text:"选择文件"}),d("button.ke-tab",{type:"button",text:"粘贴文本"})]),g=E=>{[...h.children].forEach((z,$)=>z.classList.toggle("ke-is-active",$===E)),c.hidden=E!==0,u.hidden=E!==1,E===1&&x.focus()};h.children[0].addEventListener("click",()=>g(0)),h.children[1].addEventListener("click",()=>g(1));const p=d("input",{type:"file",accept:e,hidden:!0,style:{display:"none"}}),f=d("div.ke-md-file",{hidden:!0}),k=d("div.ke-drop",{},[d("span.ke-drop-ico",{html:_("upload")}),d("div.ke-drop-title",{text:"点击选择 .md 文件,或拖拽到此处"}),d("div.ke-drop-sub",{text:[t,"支持 .md / .markdown / .txt,自动识别 UTF-8 与 GBK"].filter(Boolean).join(" · ")})]);k.addEventListener("click",()=>p.click()),k.addEventListener("dragover",E=>{E.preventDefault(),k.classList.add("ke-is-over")}),k.addEventListener("dragleave",()=>k.classList.remove("ke-is-over")),k.addEventListener("drop",E=>{var $,M;E.preventDefault(),k.classList.remove("ke-is-over");const z=(M=($=E.dataTransfer)==null?void 0:$.files)==null?void 0:M[0];z&&m(z)}),p.addEventListener("change",()=>{var z;const E=(z=p.files)==null?void 0:z[0];p.value="",E&&m(E)});async function m(E){try{const z=await Xe(E);l.text=z,l.name=E.name||"",l.picked=!0,f.hidden=!1,f.textContent="",f.append(d("b",{text:E.name||"未命名"}),d("span",{text:`${W(E.size)} · ${z.length} 字符`})),A()}catch(z){l.text="",f.hidden=!1,f.textContent="",f.appendChild(d("span.ke-md-error",{text:`读取失败:${z.message}`})),ue()}}c.append(k,p,f);const x=d("textarea.ke-md-text",{placeholder:"# 标题\n\n正文段落,支持 **加粗**、列表、表格、```js 代码块 ...",spellcheck:"false"});u.appendChild(x);const C=[["replace","替换全文"],["append","追加文末"],["cursor","插入光标"]],w=d("div.ke-md-modes"),T={replace:"清空正文后导入(可撤销)",append:"保留正文,追加到末尾",cursor:"插入到当前光标位置"};C.forEach(([E,z])=>{const $=d("button.ke-md-mode",{type:"button",title:T[E],text:z});$.classList.toggle("ke-is-active",E===l.mode),$.addEventListener("click",()=>{l.mode=E,[...w.children].forEach(M=>M.classList.toggle("ke-is-active",M===$))}),w.appendChild($)});const L=d("div.ke-md-preview.ke-content"),b=d("div.ke-md-stats"),v=d("button.ke-btn-primary",{type:"button",text:"导入到正文",disabled:!0});let S=null;function A(){clearTimeout(S),S=setTimeout(ue,180)}function De(){const E=l.text;if(!E.trim())return{html:"",summary:null};try{return r(E)||{html:"",summary:null}}catch(z){return{html:"",summary:null,error:z}}}function ue(){const E=De(),z=!l.text.trim();if(v.disabled=z||!E.html||!!E.error,a.textContent=z?"尚未选择文件":`${l.text.length} 字符`,L.textContent="",b.textContent="",E.error){L.appendChild(d("div.ke-md-empty",{text:`转换失败:${E.error.message}`}));return}if(z){L.appendChild(d("div.ke-md-empty",{text:"选择文件或粘贴 Markdown 后,这里会显示转换预览"}));return}L.innerHTML=E.html,i&&At(L,{highlight:!0});const $=E.summary||{},M=[["标题",$.headings],["段落",$.paragraphs],["列表",$.lists],["代码块",$.codeBlocks],["引用",$.quotes],["表格",$.tables],["图片",$.images],["链接",$.links]].filter(([,ie])=>ie);M.forEach(([ie,Te])=>{b.appendChild(d("span.ke-md-stat",{},[d("b",{text:String(Te)}),` ${ie}`]))}),M.length||b.appendChild(d("span.ke-md-stat",{text:"未识别到块级结构,将按纯文本导入"}))}return x.addEventListener("input",()=>{l.text=x.value,l.name="",A()}),v.addEventListener("click",async()=>{if(!v.disabled){v.disabled=!0,v.textContent="导入中…";try{await o({text:l.text,name:l.name,mode:l.mode})}finally{v.textContent="导入到正文",v.disabled=!l.text.trim()}}}),s.append(h,d("div.ke-md-body",{},[c,u,d("div.ke-panel-sect",{text:"导入位置"}),w,d("div.ke-panel-sect",{text:"转换预览"}),L,b]),d("div.ke-panel-foot",{},[v,d("span.ke-panel-hint",{text:"转换后为可直接编辑的 HTML"})])),g(0),ue(),s}function $i({title:n,kind:e,colors:t,value:i,recents:r=[],onPick:o,onClear:s}){const a=e==="bg",l=d("button.ke-panel-reset",{type:"button",title:a?"清除高亮":"恢复默认文字色",text:a?"清除高亮":"恢复默认",onclick:()=>s?s():o(null)}),c=ee(n,l);return r.length&&(c.appendChild(ye("最近使用")),c.appendChild(ve(r.slice(0,8),i,o))),a?(c.appendChild(ye("推荐底色")),c.appendChild(ve(Ut.map(([u,h])=>[u,h]),i,o)),c.appendChild(ye("主题颜色")),c.appendChild(ve(at,i,o))):(c.appendChild(ye("主题颜色")),c.appendChild(ve(at,i,o)),c.appendChild(ye("标准颜色")),c.appendChild(ve(Mi,i,o))),c.appendChild(Wt()),c.appendChild(Ri(i,o)),c}function ve(n,e,t){const i=d("div.ke-sw-grid");return n.forEach(([r,o])=>{const s=d("button.ke-sw",{type:"button",title:`${o} ${r}`,"aria-label":o,style:{background:r}});e&<.test(e)&&r.toLowerCase()===String(e).toLowerCase()&&(s.classList.add("ke-is-active"),s.appendChild(d("span.ke-sw-check",{html:_("checkLight")}))),s.addEventListener("click",()=>t(r)),i.appendChild(s)}),i}function Ri(n,e){const t=lt.test(n||"")?n:"#07c160",i=d("input.ke-sw-picker",{type:"color",value:t,title:"自定义颜色"}),r=d("input.ke-input.ke-sw-hex",{type:"text",value:t,placeholder:"#000000",maxlength:7}),o=d("button.ke-btn-primary",{type:"button",text:"应用"}),s=()=>{const a=r.value.trim(),l=a.startsWith("#")?a:`#${a}`;if(!lt.test(l)){r.classList.add("ke-is-invalid");return}r.classList.remove("ke-is-invalid"),e(l)};return i.addEventListener("input",()=>{r.value=i.value}),i.addEventListener("change",s),o.addEventListener("click",s),r.addEventListener("keydown",a=>{a.key==="Enter"&&(a.preventDefault(),s())}),d("div.ke-panel-foot",{},[i,r,o])}function Hi(n,{value:e,onPick:t}){const i=ee("段落样式");return i.classList.add("ke-panel-wide"),n.forEach(r=>{const o=d("button.ke-hd-row",{type:"button",dataset:{kValue:r.value},onclick:()=>t(r.value)},[d("span.ke-hd-sample",{class:r.sampleClass||"",text:r.sample||r.label}),d("span.ke-hd-meta",{},[d("span.ke-hd-label",{text:r.label}),d("span.ke-hd-desc",{text:r.desc})])]);r.value===e&&o.classList.add("ke-is-active"),i.appendChild(o)}),i}function Bi(n,{value:e,onPick:t}){const i=ee("字号",d("span.ke-panel-note",{text:e?`${e}px`:"默认 17px"}));i.classList.add("ke-panel-wide");const r=d("div.ke-size-grid");return n.forEach(o=>{const s=d("button.ke-size-cell",{type:"button",text:String(o),onclick:()=>t(o)});s.style.fontSize=`${Math.min(20,10+o/6)}px`,Number(e)===o&&s.classList.add("ke-is-active"),r.appendChild(s)}),i.appendChild(r),i.appendChild(Wt()),i.appendChild(d("div.ke-panel-hint",{text:"仅作用于选中的文字;未选中时对新输入的文字生效"})),i}at.map(n=>n[0]),Ut.map(n=>n[0]);function Ni(n,{cols:e=10,rows:t=8}={}){const i=ee("插入表格",d("span.ke-panel-note",{text:"最大 10×8"})),r=d("div.ke-table-grid",{style:{gridTemplateColumns:`repeat(${e}, 18px)`}}),o=[];for(let l=0;l<t;l+=1)for(let c=0;c<e;c+=1){const u=d("span.ke-table-cell");u.dataset.r=String(l),u.dataset.c=String(c),o.push(u),r.appendChild(u)}i.appendChild(r);const s=d("div.ke-panel-hint",{text:"1 列 × 1 行"});i.appendChild(s);const a=(l,c)=>{o.forEach(u=>{const h=Number(u.dataset.r)<=l&&Number(u.dataset.c)<=c;u.classList.toggle("ke-is-on",h)}),s.textContent=`${c+1} 列 × ${l+1} 行`};return r.addEventListener("mousemove",l=>{const c=l.target.closest(".ke-table-cell");c&&a(Number(c.dataset.r),Number(c.dataset.c))}),r.addEventListener("click",l=>{const c=l.target.closest(".ke-table-cell");c&&n(Number(c.dataset.c)+1,Number(c.dataset.r)+1)}),r.addEventListener("mouseenter",()=>a(0,0)),a(0,0),i}function Oi(n,{onFiles:e,onUrl:t,multiple:i,hint:r,maxText:o}){const s=n==="image",a=ee(s?"插入图片":"插入视频");a.classList.add("ke-panel-wide","ke-panel-media");const l=d("div.ke-tab-body"),c=d("div.ke-tab-body",{hidden:!0}),u=d("div.ke-drop",{},[d("span.ke-drop-ico",{html:_("upload")}),d("div.ke-drop-title",{text:s?"点击选择图片,或拖拽到此处":"点击选择视频,或拖拽到此处"}),d("div.ke-drop-sub",{text:[o,r].filter(Boolean).join(" · ")})]),h=d("button.ke-btn-primary",{type:"button",text:s?"选择图片":"选择视频",onclick:()=>e(null)});u.addEventListener("click",()=>e(null)),u.addEventListener("dragover",b=>{b.preventDefault(),u.classList.add("ke-is-over")}),u.addEventListener("dragleave",()=>u.classList.remove("ke-is-over")),u.addEventListener("drop",b=>{var v,S;b.preventDefault(),u.classList.remove("ke-is-over"),(S=(v=b.dataTransfer)==null?void 0:v.files)!=null&&S.length&&e(b.dataTransfer.files)}),l.append(u,d("div.ke-panel-foot",{},[h,d("span.ke-panel-hint",{text:i?"可一次插入多张":"单文件大文件将自动分片上传"})]));const g=d("input.ke-input",{type:"url",placeholder:s?"https://example.com/photo.jpg":"https://example.com/video.mp4","data-k-autofocus":""}),p=d("input.ke-input",{type:"text",placeholder:s?"图片描述(可选,作为 alt)":"视频标题(可选)"}),f=d("div.ke-link-status",{text:"粘贴链接后自动校验可访问性"}),k=d("button.ke-btn-primary",{type:"button",text:"插入",disabled:!0});let m=null,x=0;const C=()=>{x+=1;const b=x;clearTimeout(m);const v=we(g.value);if(k.disabled=!v,f.className="ke-link-status",!v){f.textContent="请输入 http(s) 开头的链接";return}f.className="ke-link-status ke-is-checking",f.textContent="正在校验…",m=setTimeout(()=>_i(n,v,S=>{b===x&&(S?(f.className="ke-link-status ke-is-ok",f.textContent=s?"图片可访问 ✓":"视频可播放 ✓"):(f.className="ke-link-status ke-is-bad",f.textContent="未能自动加载(可能限制热链),不阻塞插入,发布前请自行确认"))}),350)};g.addEventListener("input",C),g.addEventListener("paste",()=>setTimeout(C,0));const w=()=>{const b=we(g.value);if(!b){g.classList.add("ke-is-invalid"),g.focus();return}t({url:b,name:p.value.trim()})};k.addEventListener("click",w),c.addEventListener("keydown",b=>{b.key==="Enter"&&(b.preventDefault(),w())}),c.append(d("div.ke-field",{},[d("span.ke-field-label",{text:"地址"}),g]),d("div.ke-field",{},[d("span.ke-field-label",{text:s?"描述":"标题"}),p]),f,d("div.ke-panel-foot",{},[k,d("span.ke-panel-hint",{text:"外链由源站提供,不占用上传配额"})]));const T=d("div.ke-tabs",{},[d("button.ke-tab",{type:"button",text:"本地上传"}),d("button.ke-tab",{type:"button",text:"网络链接"})]),L=b=>{[...T.children].forEach((v,S)=>v.classList.toggle("ke-is-active",S===b)),l.hidden=b!==0,c.hidden=b!==1,b===1&&g.focus()};return T.children[0].addEventListener("click",()=>L(0)),T.children[1].addEventListener("click",()=>L(1)),L(0),a.append(T,l,c),a}function _i(n,e,t){let i=!1;const r=o=>{i||(i=!0,t(o))};try{if(n==="image"){const o=new Image;o.onload=()=>r(!0),o.onerror=()=>r(!1),o.referrerPolicy="no-referrer",o.src=e}else{const o=document.createElement("video");o.preload="metadata",o.muted=!0,o.onloadedmetadata=()=>r(o.videoHeight>0||o.duration>0||Number.isFinite(o.duration)),o.onerror=()=>r(!1),o.src=e}}catch{r(!1)}}function ji({url:n="",text:e="",target:t=!1,onSubmit:i,onCancel:r,onRemove:o}){const s=d("input.ke-input",{type:"url",placeholder:"https://mp.weixin.qq.com/...",value:n,"data-k-autofocus":""}),a=d("input.ke-input",{type:"text",placeholder:"链接文字(留空使用 URL)",value:e}),l=d("input",{type:"checkbox"});l.checked=!!t;const c=ee(n?"编辑链接":"插入链接");c.classList.add("ke-panel-wide");const u=d("div",{},[d("div.ke-field",{},[d("span.ke-field-label",{text:"文字"}),a]),d("div.ke-field",{},[d("span.ke-field-label",{text:"地址"}),s]),d("label.ke-check",{},[l,"新窗口打开"]),d("div.ke-panel-foot",{},[o?d("button.ke-btn-ghost",{type:"button",text:"移除链接",style:{marginRight:"auto",color:"#e53e3e"},onclick:o}):null,d("button.ke-btn-ghost",{type:"button",text:"取消",onclick:r}),d("button.ke-btn-primary",{type:"button",text:"确定",onclick:()=>h()})])]),h=()=>{const g=we(s.value);if(!g){s.classList.add("ke-is-invalid"),s.focus();return}i({url:g,text:a.value.trim(),target:l.checked})};return u.addEventListener("keydown",g=>{g.key==="Enter"&&(g.preventDefault(),h())}),c.appendChild(u),c}function Ii(n){try{return new URL(n,window.location.href).host}catch{return String(n).slice(0,40)}}function Pi({title:n,note:e,searchable:t,width:i,remote:r,value:o,load:s,reload:a,linkOf:l,onPick:c,emptyText:u}){const h=ee(n);h.classList.add("ke-panel-wide","ke-panel-select"),i&&(h.style.width=`${Math.min(420,Math.max(200,Number(i)))}px`);const g=h.querySelector(".ke-panel-head"),p=d("span.ke-panel-note",{text:e||""});r&&g.appendChild(d("button.ke-panel-icon",{type:"button",title:"重新加载数据",html:_("retry"),onclick:()=>L(a||s,!0)})),g.appendChild(p);const f=d("div.ke-sel-body");h.appendChild(f);let k=[],m="",x=0;if(t){const b=d("input.ke-input.ke-sel-search",{type:"search",placeholder:"搜索…","data-k-autofocus":""});b.addEventListener("input",()=>{m=b.value.trim().toLowerCase(),w()}),h.insertBefore(b,f)}function C(b,v){if(f.textContent="",f.dataset.state=b,b==="loading"){for(let S=0;S<3;S+=1)f.appendChild(d("div.ke-sel-skel"));f.insertBefore(d("div.ke-sel-loading",{},[d("span.ke-spinner"),"数据加载中…"]),f.firstChild)}else b==="error"?f.appendChild(d("div.ke-sel-tip",{},[d("span.ke-sel-tip-text",{text:v||"数据加载失败"}),d("button.ke-btn-primary",{type:"button",text:"重试",onclick:()=>L(a||s,!0)})])):f.appendChild(d("div.ke-sel-tip",{},[d("span.ke-sel-tip-text",{text:v||u||"暂无数据"})]))}function w(){const b=m?k.filter(S=>`${S.label} ${S.desc} ${S.value} ${S.group}`.toLowerCase().includes(m)):k;if(p.textContent=e||(m?`${b.length} / ${k.length} 项`:`${k.length} 项`),f.textContent="",delete f.dataset.state,!b.length){C("empty",m?`没有匹配「${m}」的选项`:u||"暂无数据");return}let v=null;b.forEach(S=>{S.group&&S.group!==v&&(v=S.group,f.appendChild(d("div.ke-panel-sect",{text:v}))),f.appendChild(T(S))})}function T(b){const v=l?l(b):null,S=d("button.ke-sel-row",{type:"button",disabled:b.disabled||void 0,dataset:{kValue:b.value},title:b.disabled?"该项不可用":v&&v.mode==="open"?`打开 ${v.url}`:v?`插入链接:${v.url}`:b.title||"",onclick:()=>{b.disabled||c(b)}});return S.appendChild(d("span.ke-sel-main",{},[d("span.ke-sel-label",{text:b.label}),b.desc?d("span.ke-sel-desc",{text:b.desc}):null,v?d("span.ke-sel-link",{html:`${_("link")}<i>${Ii(v.url)}</i>`}):null])),o&&String(o)===String(b.value)&&(S.classList.add("ke-is-active"),S.appendChild(d("span.ke-sel-check",{html:_("check")}))),v&&S.classList.add("ke-has-link"),S}function L(b,v){x+=1;const S=x;C("loading"),Promise.resolve().then(()=>b({force:v})).then(A=>{S!==x||!h.isConnected||(k=Array.isArray(A)?A:[],k.length?w():C("empty"))}).catch(A=>{S!==x||!h.isConnected||C("error",A&&A.message?A.message:"数据加载失败")})}return L(s),h}function we(n){const e=String(n||"").trim();return e?/^(https?:|mailto:|tel:|#|\/)/i.test(e)?e:/^[\w-]+(\.[\w-]+)+/.test(e)?`https://${e}`:"":""}const Gt=new Set(["p","div","section","blockquote","ul","ol","li","table","thead","tbody","tfoot","tr","td","th","figure","figcaption","pre","h1","h2","h3","h4","h5","h6","hr","video"]);function ct(n,{indent:e=" "}={}){if(!n)return"";const i=new DOMParser().parseFromString(`<div>${n}</div>`,"text/html").body.firstChild,r=[],o=(a,l)=>{const c=l.replace(/\s+/g," ").trim();if(!c)return;const u=r[r.length-1];u&&u.depth===a&&u.inlineRun?u.text+=` ${c}`:r.push({depth:a,text:e.repeat(a)+c,inlineRun:!0})},s=(a,l)=>{[...a.childNodes].forEach(u=>{if(u.nodeType===3){const f=u.textContent.trim();f&&o(l,f);return}if(u.nodeType!==1)return;const h=u.tagName.toLowerCase();if(!Gt.has(h)){o(l,u.outerHTML);return}const g=[...u.querySelectorAll("*")].some(f=>Gt.has(f.tagName.toLowerCase()));if(h==="pre"){r.push({depth:l,text:e.repeat(l)+u.outerHTML.trim(),inlineRun:!1});return}if(!g||(h==="tr"||h==="figure"||h==="video")){r.push({depth:l,text:e.repeat(l)+Fi(u.outerHTML),inlineRun:!1});return}r.push({depth:l,text:e.repeat(l)+Di(u),inlineRun:!1}),s(u,l+1),r.push({depth:l,text:e.repeat(l)+`</${h}>`,inlineRun:!1})})};return s(i,0),r.map(a=>a.text).join(`
|
|
586
|
+
`)}function Fi(n){return n.replace(/\n\s+/g," ").replace(/\s{2,}/g," ").trim()}function Di(n){const e=[...n.attributes].map(t=>`${t.name}="${(t.value||"").replace(/"/g,""")}"`);return`<${n.tagName.toLowerCase()}${e.length?` ${e.join(" ")}`:""}>`}class qi{constructor(e){this.editor=e,this.open=!1,this.el=d("div.ke-source",{hidden:!0},[d("div.ke-source-bar",{},[d("span.ke-source-title",{text:"HTML 源码"}),d("span.ke-source-tip",{text:"可直接编辑,点击「应用」或退出源码模式即生效"}),d("span.ke-source-tail",{},[d("button.ke-btn",{type:"button",title:"格式化",html:_("format")+"<span>格式化</span>",onclick:()=>this.format()}),d("button.ke-btn",{type:"button",title:"复制全部",html:_("copy")+"<span>复制</span>",onclick:()=>this.copy()}),d("button.ke-btn",{type:"button",title:"应用修改",html:_("check")+"<span>应用</span>",onclick:()=>this.apply()}),d("button.ke-btn",{type:"button",title:"退出源码模式",html:_("close"),onclick:()=>e.exitSource()})])]),(this.code=d("pre.ke-source-code",{contenteditable:"true",spellcheck:"false",autocapitalize:"off",autocomplete:"off",wrap:"off"}),this.code.addEventListener("keydown",t=>{t.key==="Tab"&&(t.preventDefault(),document.execCommand("insertText",!1," ")),(t.ctrlKey||t.metaKey)&&t.key.toLowerCase()==="s"&&(t.preventDefault(),this.apply()),t.stopPropagation()}),this.code)])}get value(){return this.code.textContent}set value(e){this.code.textContent=e,this.code.scrollTop=0}show(e){this.value=ct(e),this.el.hidden=!1,this.open=!0,this.editor.scrollEl.hidden=!0}hide(){this.el.hidden=!0,this.open=!1,this.editor.scrollEl.hidden=!1}format(){this.value=ct(this.value),this.editor.toast.show("已格式化")}async copy(){var t;const e=this.value;try{(t=navigator.clipboard)!=null&&t.writeText?await navigator.clipboard.writeText(e):(this.code.focus(),document.execCommand("selectAll"),document.execCommand("copy")),this.editor.toast.show("源码已复制到剪贴板")}catch{this.editor.toast.error("复制失败,请手动选择复制")}}apply({silent:e=!1}={}){const t=this.value;try{return this.editor.setContent(t,{sanitize:!0,silent:!1}),e||this.editor.toast.show("源码已应用"),!0}catch(i){return this.editor.toast.error(`源码解析失败:${i.message}`),!1}}destroy(){this.el.remove()}}const dt=[{key:"mobile",label:"手机",width:375},{key:"pad",label:"平板",width:540},{key:"pc",label:"电脑",width:677}];class Ui{constructor(e){this.editor=e,this.device="pc",this.el=d("div.ke-preview",{hidden:!0},[d("div.ke-preview-bar",{},[d("span",{text:"预览"}),d("span.ke-source-tip",{text:"仅用于查看排版效果,内容不可编辑"}),d("span.ke-status-tail",{},dt.map(t=>d("button.ke-btn",{type:"button","data-k-device":t.key,text:t.label,onclick:()=>this.setDevice(t.key)})).concat([d("span.ke-tb-sep"),d("button.ke-btn",{type:"button",title:"关闭预览",html:_("close"),onclick:()=>e.closePreview()})]))]),(this.body=d("div.ke-preview-body",{},[d("div.ke-preview-frame",{style:{maxWidth:"677px"}},[d("div.ke-content.ke-preview-content")])]),this.frame=this.body.firstChild,this.content=this.frame.firstChild,this.body)])}setDevice(e){this.device=e;const t=dt.find(i=>i.key===e)||dt[2];this.frame.style.maxWidth=`${t.width}px`,this.frame.style.width=e==="mobile"?`${t.width}px`:"100%",this.el.querySelectorAll("[data-k-device]").forEach(i=>i.classList.toggle("ke-is-active",i.dataset.kDevice===e))}show(e){this.content.innerHTML=e,this.el.hidden=!1,this.setDevice(this.device)}hide(){this.el.hidden=!0,this.content.innerHTML=""}destroy(){this.el.remove()}}class Wi{constructor(e=null){this.owner=e,this.el=null}show(e,t="",i=2600){if(typeof document>"u")return;this.el||(this.el=d("div.ke-toasts"),document.body.appendChild(this.el));const r=d(`span.ke-toast${t?`.ke-is-${t}`:""}`,{text:e});this.el.appendChild(r),setTimeout(()=>{r.style.opacity="0",r.style.transition="opacity .2s",setTimeout(()=>r.remove(),220)},i)}error(e){this.show(e,"error",3600)}warn(e){this.show(e,"warn",3e3)}ok(e){this.show(e,"ok",2200)}destroy(){this.el&&!this.el.childElementCount&&this.el.remove(),this.el=null}}function Oe(n,e=document){const t=d("div.ke-lightbox",{tabindex:"-1"},[d("img",{src:n,alt:""})]),i=()=>{t.remove(),document.removeEventListener("keydown",r)},r=o=>{o.key==="Escape"&&i()};return t.addEventListener("click",i),document.addEventListener("keydown",r),e.body.appendChild(t),i}class Gi{constructor(e){this.editor=e,this.node=null,this.el=d("div.ke-bubble",{hidden:!0,contenteditable:"false"}),e.el.appendChild(this.el),this.el.addEventListener("mousedown",t=>t.preventDefault()),this.el.addEventListener("click",t=>this.onClick(t)),this.replaceInput=d("input",{type:"file",style:{display:"none"}}),this.replaceInput.addEventListener("change",()=>{var i;const t=(i=this.replaceInput.files)==null?void 0:i[0];this.replaceInput.value="",t&&this.node&&this.editor.media.replaceNode(this.node,t)}),e.el.appendChild(this.replaceInput),this.resizeEl=d("div.ke-img-resize",{hidden:!0,"aria-label":"拖动缩放图片",title:"拖动缩放图片",html:'<svg viewBox="0 0 10 10"><path d="M7 1 L9 3 M4 4 L6 6 M1 7 L3 9" stroke="currentColor" stroke-width="1.6" stroke-linecap="round"/></svg>'}),this.resizeTip=d("div.ke-img-resize-tip",{hidden:!0}),this.resizeEl.addEventListener("pointerdown",t=>this.onResizePointerDown(t)),e.el.appendChild(this.resizeEl),e.el.appendChild(this.resizeTip)}show(e){this.node=e;const t=e.dataset.kMedia==="video"?"video":"image";this.el.textContent="";const i=t==="image"?this.imageActions(e):this.videoActions(e);for(const r of i)r&&this.el.appendChild(r);this.el.hidden=!1,t==="image"&&this.attachResize(),this.position()}hide(){this.el.hidden=!0,this.detachResize(),this.node=null}attachResize(){var e;(e=this.node)!=null&&e.querySelector("img")&&(this.resizeEl.hidden=!1,this.positionHandle())}detachResize(){this.resizeEl.hidden=!0,this.resizeTip.hidden=!0}position(){if(!this.node||(this.positionHandle(),this.el.hidden))return;const e=this.editor.el.getBoundingClientRect(),t=this.node.getBoundingClientRect(),i=this.editor.scrollEl.getBoundingClientRect();if(!t.height&&!t.width)return this.hide();if(t.bottom<i.top||t.top>i.bottom)return this.hide();const r=this.el.getBoundingClientRect(),o=t.left-e.left+t.width/2,a=t.top-e.top<r.height+18,l=a?t.bottom-e.top+10:t.top-e.top-10;this.el.classList.toggle("ke-is-below",a);const c=r.width/2;this.el.style.left=`${Math.min(Math.max(o,c+8),Math.max(c+8,e.width-c-8))}px`,this.el.style.top=`${Math.max(6,l)}px`}positionHandle(){const e=this.node;if(!e||this.resizeEl.hidden)return;const t=e.querySelector("img");if(!t)return;const i=this.editor.el.getBoundingClientRect(),r=t.getBoundingClientRect();if(!r.width&&!r.height)return;const o=18,s=6;this.resizeEl.style.left=`${r.right-i.left-o-s}px`,this.resizeEl.style.top=`${r.bottom-i.top-o-s}px`}updateResizeTip(e){var r;if(this.resizeTip.hidden||!this.node)return;this.resizeTip.textContent=`${Math.round(e)}%`;const t=this.editor.el.getBoundingClientRect(),i=((r=this.node.querySelector("img"))==null?void 0:r.getBoundingClientRect())||this.node.getBoundingClientRect();this.resizeTip.style.left=`${i.left-t.left+i.width/2}px`,this.resizeTip.style.top=`${i.top-t.top-10}px`}onResizePointerDown(e){var c;if(e.button!=null&&e.button!==0)return;const t=(c=this.node)==null?void 0:c.querySelector("img");if(!t)return;e.preventDefault(),e.stopPropagation();const r=this.node.getBoundingClientRect().width,o=Kt(Zi(t,r),15,100),s=e.clientX;this.el.hidden=!0,this.resizeTip.hidden=!1,this.updateResizeTip(o);try{this.resizeEl.setPointerCapture(e.pointerId)}catch{}const a=u=>{const h=u.clientX-s,g=r?h/r*100:0,p=Kt(Math.round(o+g),15,100);t.style.width=`${p}%`,t.style.maxWidth="100%",this.updateResizeTip(p),this.positionHandle()},l=()=>{this.resizeEl.removeEventListener("pointermove",a),this.resizeEl.removeEventListener("pointerup",l),this.resizeEl.removeEventListener("pointercancel",l),this.resizeTip.hidden=!0,this.editor.commitHistory(),this.editor.refreshStatus(),this.el.hidden=!1,this.position()};this.resizeEl.addEventListener("pointermove",a),this.resizeEl.addEventListener("pointerup",l),this.resizeEl.addEventListener("pointercancel",l)}imageActions(e){const t=e.querySelector("img"),i=Ue(t),r=t&&parseFloat(getComputedStyle(t).borderRadius)>0,o=a=>{We(t,a),this.editor.commitHistory(),this.position()},s=a=>{t.style.width=a,We(t,Ue(t)),this.editor.commitHistory(),this.position()};return[te("alignLeft","左对齐",()=>o("left"),i==="left"),te("alignCenter","居中",()=>o("center"),i==="center"),te("alignRight","右对齐",()=>o("right"),i==="right"),Se(),Ce("30%","宽度 30%",()=>s("30%")),Ce("60%","宽度 60%",()=>s("60%")),Ce("100%","宽度 100%",()=>s("100%")),Se(),te("rounded","圆角",()=>Ki(t,e),r),te("preview","查看大图",()=>Vi(t)),te("upload","替换图片",()=>this.pick("image")),Se(),te("trash","删除",()=>this.remove())]}videoActions(){return[Ce("小","窄版",()=>this.setVideoWidth("60%")),Ce("大","宽版",()=>this.setVideoWidth("100%")),Se(),te("upload","替换视频",()=>this.pick("video")),Se(),te("trash","删除",()=>this.remove())]}pick(e){this.replaceInput.accept=e==="image"?this.editor.options.imageAccept:this.editor.options.videoAccept,this.replaceInput.click()}setVideoWidth(e){this.node&&(this.node.style.width=e,this.editor.commitHistory(),this.position())}remove(){if(!this.node)return;const e=this.editor.media.taskFromNode(this.node);if(e)this.editor.media.remove(e);else{const t=this.node.nextElementSibling;this.node.remove(),t&&this.editor.focus(),this.editor.commitHistory()}this.hide(),this.editor.refreshStatus()}onClick(){}destroy(){this.el.remove(),this.replaceInput.remove(),this.resizeEl.remove(),this.resizeTip.remove()}}function te(n,e,t,i=!1){const r=d("button",{type:"button",title:e,html:_(n)});return i&&r.classList.add("ke-is-active"),r.addEventListener("click",t),r}function Ce(n,e,t){const i=d("button",{type:"button",title:e,text:n});return i.addEventListener("click",t),i}const Se=()=>d("span.ke-sep");function Ki(n,e){if(!n)return;const t=parseFloat(getComputedStyle(n).borderRadius)>0;n.style.borderRadius=t?"0":"10px",e.dispatchEvent(new Event("change",{bubbles:!0}))}function Vi(n){n&&Oe(n.src)}function Kt(n,e,t){return Math.min(t,Math.max(e,n))}function Zi(n,e){var i,r;if(!e)return 100;const t=(r=(i=n==null?void 0:n.style)==null?void 0:i.width)==null?void 0:r.match(/^([\d.]+)%$/);return t?parseFloat(t[1]):n.getBoundingClientRect().width/e*100}const Xi=1e4;function Vt(n){if(Array.isArray(n))return n;if(!n||typeof n!="object")return[];for(const e of["items","list","data","rows","records","result"]){const t=n[e];if(Array.isArray(t))return t;if(t&&typeof t=="object"){const i=Vt(t);if(i.length)return i}}return[]}function _e(n,e){for(const t of e){const i=n[t];if(i!=null)return i}}function Yi(n,e){if(n==null)return null;if(typeof n=="string"||typeof n=="number"){const r=String(n);return{value:r,label:r,desc:"",url:"",group:"",html:"",disabled:!1,raw:n}}if(typeof n!="object")return null;const t=_e(n,["value","id","key","val","code"]),i=_e(n,["label","text","name","title"]);return{value:String(t===void 0?e:t),label:String(i===void 0||i===""?t===void 0?e:t:i),desc:String(_e(n,["desc","description","sub","subtitle","tip"])??""),url:String(_e(n,["url","href","link","jumpUrl","jump"])??""),group:String(n.group??""),html:String(n.html??""),disabled:!!n.disabled,raw:n}}function Ee(n){return Vt(n).map(Yi).filter(Boolean)}function ut(n={}){const e=n.position!==void 0?n.position:n.at,t=r=>Math.max(0,Math.floor(Number(r))),i=r=>typeof r=="object"&&r?r.before||r.after:r;if(typeof e=="number"&&Number.isFinite(e))return t(e);if(typeof e=="string"&&e){const r=e.toLowerCase();return r==="start"||r==="begin"||r==="first"?"start":r==="end"||r==="last"||r==="main"?"end":r==="tail"||r===":tail"||r==="right"?"tail":{before:e}}if(e&&typeof e=="object"){if(e.before)return{before:String(i(e))};if(e.after)return{after:String(i(e))}}return typeof n.index=="number"&&Number.isFinite(n.index)?t(n.index):n.before?{before:String(n.before)}:n.after?{after:String(n.after)}:null}function Zt(n){if(!n||typeof n!="object")return null;const e=String(n.name||"").trim();return e?{name:e,position:ut(n),type:n.type==="button"?"button":"select",title:n.title||n.text||e,text:n.text||"",placeholder:n.placeholder||n.text||"请选择",icon:n.icon||"",width:Number(n.width)>0?Number(n.width):0,searchable:!!n.searchable,note:n.note?String(n.note):"",emptyText:n.emptyText?String(n.emptyText):"",cache:n.cache!==!1,keepValue:n.keepValue!==!1,multiple:!1,options:n.options??null,load:typeof n.load=="function"?n.load:null,url:n.url?String(n.url):"",fetchOptions:n.fetchOptions&&typeof n.fetchOptions=="object"?n.fetchOptions:{},pick:typeof n.pick=="function"?n.pick:null,link:n.link??null,insert:n.insert===void 0?"auto":n.insert,onSelect:typeof n.onSelect=="function"?n.onSelect:null,onClick:typeof n.onClick=="function"?n.onClick:null,active:typeof n.active=="function"?n.active:null,enabled:typeof n.enabled=="function"?n.enabled:null}:null}function Xt(n){return Array.isArray(n)?n.map(Zt).filter(Boolean):[]}function Ji(){return{items:null,loaded:!1,loading:null,value:null,controller:null,error:"",gen:0,external:!1}}async function Qi(n,e,t){return n.load?Ee(await n.load(e)):n.url?Ee(await er(n,e,t)):Ee(n.options)}async function er(n,e,t){var l;const i=n.fetchOptions,r=i.fetch||(typeof fetch=="function"?fetch.bind(globalThis):null);if(!r)throw new Error("当前环境无 fetch,请改用 load 函数提供数据");(l=t.controller)==null||l.abort();const o=typeof AbortController=="function"?new AbortController:null;t.controller=o;const s=Number(i.timeout)>0?Number(i.timeout):Xi,a=setTimeout(()=>o==null?void 0:o.abort(),s);try{const c=await r(n.url,{method:i.method||"GET",headers:i.headers,body:i.body,credentials:i.credentials,signal:o?o.signal:void 0});if(!c||c.ok===!1)throw new Error(`接口返回 ${c&&c.status?c.status:"异常"}`);const u=i.parser?await i.parser(c):await c.json();return n.pick?n.pick(u,e):u}catch(c){throw c&&c.name==="AbortError"?new Error(`请求超时(${s}ms)或被取消`):c}finally{clearTimeout(a),t.controller===o&&(t.controller=null)}}function tr(n,e,t,{force:i=!1}={}){if(!i&&t.external&&t.items||!i&&n.cache&&t.items)return Promise.resolve(t.items);if(!i&&t.loading)return t.loading;const r=t.gen,o=Qi(n,e,t).then(s=>r!==t.gen?t.items:(t.items=s,t.loaded=!0,t.error="",s)).catch(s=>{if(r!==t.gen)return t.items;throw t.error=s&&s.message?s.message:String(s),s}).finally(()=>{t.loading===o&&(t.loading=null)});return t.loading=o,o}function nr(n,e){return n.gen+=1,n.items=Ee(e),n.loaded=!0,n.error="",n.external=!0,ht(n),n.loading=null,n.items}function ht(n){var e;(e=n.controller)==null||e.abort(),n.controller=null}function pt(n,e){return String(n).replace(/\{(\w+)\}/g,(t,i)=>{if(e[i]!==void 0&&e[i]!==null)return String(e[i]);const r=e.raw&&e.raw[i];return r==null?t:String(r)})}function ft(n,e,t){return typeof n=="function"?n(e,t):n}function Yt(n,e,t){const i=n.link;let r=null;if(typeof i=="function"?r=i(e,t):typeof i=="string"?r={url:i}:i&&typeof i=="object"?r=i:(i===!0||e.url)&&(r={url:e.url}),!r)return null;typeof r=="string"&&(r={url:r});const o=we(pt(String(ft(r.url,e,t)??""),e));if(!o||!re(o))return null;const s=ft(r.text,e,t),a=ft(r.title,e,t),l=r.mode==="open"?"open":"insert",c=r.target==="_self"||r.target===!1?"_self":"_blank";return{mode:l,url:o,text:s==null||s===""?e.label:pt(String(s),e),target:c,title:a?pt(String(a),e):""}}function Jt(n,e){n.commands.insertHTML(q(e))}async function ir(n,e,t,i){n.restoreSelection();const r=Yt(e,i,n),o={editor:n,item:i,link:r,insertLink:c=>Qt(n,{...r,...c}),insertHtml:c=>n.commands.insertHTML(String(c)),insertText:c=>Jt(n,c),open:(c,u)=>en(c||r&&r.url,u||r&&r.target)};let s="none",a=!1;e.onSelect&&(a=await e.onSelect(i,o)===!1),a||(s=rr(n,e,i,r)),e.keepValue&&(t.value=i);const l={name:e.name,item:i,link:r,action:s,editor:n};return n.emit("customselect",l),l}function rr(n,e,t,i){const r=e.insert;return r===!1||r==="none"?"none":i&&i.mode==="open"?(en(i.url,i.target),"open"):r==="link"||r==="auto"&&i?i?(Qt(n,i),"link"):"none":r==="html"||r==="auto"&&t.html?t.html?(n.commands.insertHTML(t.html),"html"):"none":(Jt(n,t.label),"text")}function Qt(n,e){n.commands.createLink({url:e.url,text:e.text,target:e.target!=="_self"})}function en(n,e="_blank"){!n||!re(n)||(e==="_self"?window.location.href=n:window.open(n,"_blank","noopener,noreferrer"))}const mt='<svg class="ke-caret" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><path d="m6 9 6 6 6-6"/></svg>',tn="keditor.toolbarScrollHint",or='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.1" stroke-linecap="round" stroke-linejoin="round"><path d="M8 7 4 12l4 5"/><path d="M16 7l4 5-4 5"/><path d="M4 12h16"/></svg>',gt=[{value:"p",label:"正文",desc:"默认段落 · 17px,正文内容都用它",sample:"正文示例文字",sampleClass:"s-body"},{value:"h1",label:"标题一",desc:"大标题 · 22px 加粗,全文主标题(建议只用一次)",sample:"标题一示例",sampleClass:"s-h1"},{value:"h2",label:"标题二",desc:"章节标题 · 20px 加粗,划分小节",sample:"标题二示例",sampleClass:"s-h2"},{value:"h3",label:"标题三",desc:"小标题 · 18px 加粗,章节内的层级",sample:"标题三示例",sampleClass:"s-h3"}],sr=[12,14,15,16,17,18,20,22,24,28,32],je=["undo","redo","|","heading","fontsize","|","bold","italic","underline","strike","|","foreColor","backColor","|","alignLeft","alignCenter","alignRight","alignJustify","|","ul","ol","quote","|","link","image","video","table","code","hr","clear",":tail","markdown","source","fullscreen"],nn={undo:{icon:"undo",title:"撤销 (⌘/Ctrl+Z)",run:n=>n.undo(),active:n=>!!n.canUndo,enabled:n=>n.canUndo},redo:{icon:"redo",title:"重做 (⌘/Ctrl+Shift+Z)",run:n=>n.redo(),active:n=>!!n.canRedo,enabled:n=>n.canRedo},bold:{glyph:["B","ke-glyph"],title:"加粗 (⌘/Ctrl+B)",cmd:"bold",active:n=>n.bold},italic:{glyph:["I","ke-glyph ke-glyph-i"],title:"斜体 (⌘/Ctrl+I)",cmd:"italic",active:n=>n.italic},underline:{glyph:["U","ke-glyph ke-glyph-u"],title:"下划线 (⌘/Ctrl+U)",cmd:"underline",active:n=>n.underline},strike:{glyph:["S","ke-glyph ke-glyph-s"],title:"删除线",cmd:"strike",active:n=>n.strikeThrough},alignLeft:{icon:"alignLeft",title:"左对齐",run:n=>n.commands.setAlign("left"),active:n=>n.align==="left"},alignCenter:{icon:"alignCenter",title:"居中",run:n=>n.commands.setAlign("center"),active:n=>n.align==="center"},alignRight:{icon:"alignRight",title:"右对齐",run:n=>n.commands.setAlign("right"),active:n=>n.align==="right"},alignJustify:{icon:"alignJustify",title:"两端对齐",run:n=>n.commands.setAlign("justify"),active:n=>n.align==="justify"},ul:{icon:"ul",title:"无序列表",run:n=>n.commands.toggleList("unordered"),active:n=>n.ul},ol:{icon:"ol",title:"有序列表",run:n=>n.commands.toggleList("ordered"),active:n=>n.ol},quote:{icon:"quote",title:"引用",run:n=>n.commands.toggleBlockquote(),active:n=>n.block==="blockquote"},link:{icon:"link",title:"插入链接",run:n=>n.toolbar.openLink(),active:n=>n.link,toggles:!0},image:{icon:"image",title:"图片(本地上传 / 网络链接)",run:n=>n.toolbar.openMedia("image"),toggles:!0},video:{icon:"video",title:"视频(本地上传 / 网络链接,支持分片上传)",run:n=>n.toolbar.openMedia("video"),toggles:!0},table:{icon:"table",title:"插入表格",run:n=>n.toolbar.openTable(),toggles:!0},code:{icon:"code",title:"代码块(选择语言并语法高亮)",run:n=>n.toolbar.openCode(),active:n=>n.inCode,toggles:!0},markdown:{icon:"markdown",text:"导入MD",title:"导入 Markdown 文件 / 粘贴 Markdown 文本,转为 HTML 显示(.md / .txt)",run:n=>n.toolbar.openMarkdown(),toggles:!0},hr:{icon:"hr",title:"分割线",run:n=>n.commands.insertDivider()},clear:{icon:"clear",title:"清除格式",run:n=>n.commands.clearFormat()},source:{icon:"source",title:"查看 / 编辑 HTML 源码(⌘/Ctrl+Shift+K)",text:"源码",run:n=>n.toggleSource(),active:n=>n.source},preview:{icon:"preview",title:"预览效果(手机 / 平板 / 电脑宽度)",text:"预览",run:n=>n.togglePreview(),active:n=>n.preview},fullscreen:{icon:"expand",title:"全屏编辑",text:"全屏",run:n=>n.toggleFullscreen(),active:n=>n.fullscreen},foreColor:{pop:"fore",title:"字体颜色",toggles:!0,swatch:"fore"},backColor:{pop:"back",title:"背景高亮色",toggles:!0,swatch:"back"}};class ar{constructor(e,t=je,i=[]){this.editor=e,this.buttons=new Map,this.custom=new Map,this.colorState={foreColor:"#3f3f3f",backColor:"#f6c344"},this.recent={foreColor:[],backColor:[]},this.el=e.tbEl;for(const r of i)this.registerCustom(r);this.build(t),this.setupScrollHints()}build(e){const t=d("div.ke-tb-group");this.el.appendChild(t),this.groupEl=t,this.tailEl=null;const i=()=>this.tailEl||t;for(const r of e){if(r==="|"){i().appendChild(d("span.ke-tb-sep"));continue}if(r===":tail"){this.tailEl=d("div.ke-tb-tail"),this.el.appendChild(this.tailEl);continue}if(this.custom.has(r)){const s=this.custom.get(r);s.button=this.buildCustomButton(s),i().appendChild(s.button);continue}if(r==="heading"){i().appendChild(this.buildHeading());continue}if(r==="fontsize"){i().appendChild(this.buildFontSize());continue}const o=nn[r];o&&i().appendChild(this.buildButton(r,o))}for(const[r,o]of this.custom)o.button||(o.button=this.buildCustomButton(o),this.insertButton(o.button,o.spec.position))}buildButton(e,t){const i=d("button.ke-btn",{type:"button",title:t.title,"data-k-item":e,onclick:r=>{var o;r.preventDefault(),t.pop?this.toggleColor(e,i):t.cmd?this.editor.commands.toggleMark(t.cmd):(o=t.run)==null||o.call(t,this.editor),t.toggles||this.editor.popover.close()}});if(t.icon&&(i.innerHTML=_(t.icon)),t.text&&i.appendChild(d("span.ke-btn-text",{text:t.text})),t.glyph){const[r,o]=t.glyph;i.appendChild(d("span",{class:o,text:r}))}if(t.swatch){const r=t.swatch==="fore"?this.colorState.foreColor:this.colorState.backColor,o=d("span",{class:t.swatch==="fore"?"ke-glyph ke-glyph-a":"ke-glyph ke-glyph-a ke-glyph-hl"});o.appendChild(d("span",{text:"A"})),i.appendChild(o),t.swatch==="fore"&&i.appendChild(d("span",{class:"ke-dot"})),this.paintButton(i,t.swatch,r),i.dataset.kPop=t.swatch==="fore"?"foreColor":"backColor"}return t.toggles&&!t.swatch&&(i.dataset.kPop=e),this.buttons.set(e,i),i}paintButton(e,t,i){!e||!i||e.style.setProperty(t==="fore"?"--ke-fore":"--ke-back",i)}openPop(e,t,i={}){this.editor.saveSelection(),this.editor.popover.open(e,t,{align:"start",...i,onClose:()=>{var r;e.classList.remove("ke-is-open"),(r=i.onClose)==null||r.call(i)}}),e.classList.add("ke-is-open")}togglePop(e,t,i,r={}){const o=this.editor.popover;if(o.isOpen&&o.anchor===t){o.close();return}this.openPop(t,i,r)}buildHeading(){const e=gt[0],t=d("button.ke-btn.ke-btn-label",{type:"button",title:"段落样式:正文 / 标题一 / 标题二 / 标题三","data-k-item":"heading",dataset:{kPop:"heading"},onclick:i=>{i.preventDefault(),this.togglePop("heading",t,()=>Hi(gt,{value:this.editor.getState().block,onPick:r=>{this.editor.restoreSelection(),this.editor.commands.setHeading(r),this.editor.popover.close(),this.editor.refresh()}}))}});return t.innerHTML=`<span class="ke-btn-text">${e.label}</span>${mt}`,this.headingEl=t,this.buttons.set("heading",t),t}buildFontSize(){const e=d("button.ke-btn.ke-btn-label",{type:"button",title:"字号","data-k-item":"fontsize",dataset:{kPop:"fontsize"},onclick:t=>{t.preventDefault(),this.togglePop("fontsize",e,()=>Bi(sr,{value:this.editor.getState().fontSize,onPick:i=>{this.editor.restoreSelection(),this.editor.commands.setFontSize(Number(i)),this.editor.popover.close(),this.editor.refresh()}}))}});return e.innerHTML=`<span class="ke-btn-text">字号</span>${mt}`,this.fontSizeEl=e,this.buttons.set("fontsize",e),e}registerCustom(e){const t=Zt(e);if(!t)return null;const i=this.custom.get(t.name),r={spec:t,rt:i?i.rt:Ji(),button:i?i.button:null};return this.custom.set(t.name,r),r}buildCustomButton(e){const{spec:t}=e,i=t.type==="select",r=d("button.ke-btn",{type:"button",class:i?"ke-btn-label ke-btn-custom":"ke-btn-custom",title:t.title,"data-k-item":t.name,dataset:{kPop:t.name,kCustom:t.name},onclick:o=>{o.preventDefault(),i?this.openCustom(t.name):this.runCustomButton(t)}});return t.icon&&(r.innerHTML=/</.test(t.icon)?t.icon:_(t.icon)),i?(r.appendChild(d("span.ke-btn-text",{text:t.text||t.placeholder})),r.insertAdjacentHTML("beforeend",mt)):t.text&&r.appendChild(d("span.ke-btn-text",{text:t.text})),this.syncCustomLabel(t.name,r),r}syncCustomLabel(e,t){const i=this.custom.get(e),r=t||(i==null?void 0:i.button);if(!i||!r)return;const{spec:o,rt:s}=i;if(o.type!=="select")return;const a=r.querySelector(".ke-btn-text");if(!a)return;const l=s.value;a.textContent=l?l.label:o.text||o.placeholder,r.title=l?`${o.title}:${l.label}`:o.title,r.classList.toggle("ke-has-value",!!l)}openCustom(e){const t=this.custom.get(e);if(!t)return;this.revealButton(t.button);const{spec:i,rt:r}=t,o=!!(i.load||i.url),s=({force:a}={})=>tr(i,this.editor,r,{force:a});this.togglePop(e,t.button,()=>Pi({title:i.title,note:i.note||"",searchable:i.searchable,width:i.width,remote:o,value:r.value?r.value.value:"",emptyText:i.emptyText,load:s,reload:s,linkOf:a=>Yt(i,a,this.editor),onPick:a=>this.pickCustom(e,a)}))}async pickCustom(e,t){const i=this.custom.get(e);if(i){this.editor.popover.close();try{await ir(this.editor,i.spec,i.rt,t)}catch(r){this.editor.reportError("custombutton",r)}this.syncCustomLabel(e),this.editor.refresh()}}async runCustomButton(e){this.editor.popover.close();try{e.onClick&&await e.onClick({editor:this.editor,name:e.name}),this.editor.emit("customclick",{name:e.name,editor:this.editor})}catch(t){this.editor.reportError("custombutton",t)}this.editor.refresh()}addButton(e,t={}){var o;const i=this.registerCustom(e);if(!i)return null;i.button&&i.button.remove(),i.button=this.buildCustomButton(i);const r=t.at!==void 0?t.at:ut(t)??i.spec.position;return this.insertButton(i.button,r,{withSep:r==null}),this.revealButton(i.button),(o=this.syncScrollHints)==null||o.call(this),i.button}buttonNodes(){const e=[];for(const t of[this.groupEl,this.tailEl])if(t)for(const i of t.children)i.dataset&&i.dataset.kItem&&e.push(i);return e}slotOf(e){const t={parent:this.groupEl||this.el,ref:null};if(e==="tail")return{parent:this.tailEl||this.groupEl||this.el,ref:null};if(e==null||e==="end")return t;if(e==="start"){const a=this.buttonNodes()[0];return a?{parent:a.parentElement,ref:a}:t}const i=this.buttonNodes();if(typeof e=="number"){const a=i[Math.max(0,Math.floor(e))];if(a)return{parent:a.parentElement,ref:a};const l=i[i.length-1];return l?{parent:l.parentElement,ref:null}:t}const r=!!(e&&typeof e=="object"&&e.after),o=typeof e=="string"?e:String((r?e.after:e.before)||""),s=i.find(a=>a.dataset.kItem===o);return s?{parent:s.parentElement,ref:r?s.nextElementSibling||null:s}:t}insertButton(e,t,{withSep:i}={}){const{parent:r,ref:o}=this.slotOf(t);!r||!e||(i&&!o&&r.appendChild(d("span.ke-tb-sep")),r.insertBefore(e,o||null))}moveButton(e,t){var r,o;const i=this.buttonNodes().find(s=>s.dataset.kItem===String(e));return i?(i.remove(),this.insertButton(i,t===void 0?((r=this.custom.get(String(e)))==null?void 0:r.spec.position)??null:t),this.revealButton(i),(o=this.syncScrollHints)==null||o.call(this),!0):!1}revealButton(e){const t=this.el;if(!t||!e||!e.isConnected)return;const i=t.scrollWidth-t.clientWidth;if(i<=1)return;const r=this.tailEl?this.tailEl.offsetWidth:0,o=e.offsetLeft,s=o+e.offsetWidth,a=t.scrollLeft+t.clientWidth-r;s>a-4?t.scrollLeft=Math.min(i,s-t.clientWidth+r+10):o<t.scrollLeft+4&&(t.scrollLeft=Math.max(0,o-10))}removeButton(e){var o,s,a,l;const t=this.custom.get(e);if(!t)return!1;ht(t.rt),this.editor.popover.anchor===t.button&&this.editor.popover.close();const i=(o=t.button)==null?void 0:o.previousElementSibling,r=(s=t.button)==null?void 0:s.nextElementSibling;return(a=t.button)==null||a.remove(),i&&i.classList.contains("ke-tb-sep")&&(!r||r.classList.contains("ke-tb-sep"))&&i.remove(),this.buttons.delete(e),this.custom.delete(e),(l=this.syncScrollHints)==null||l.call(this),!0}setButtonOptions(e,t){const i=this.custom.get(e);if(!i)return null;const r=nr(i.rt,t);return this.editor.popover.isOpen&&this.editor.popover.anchor===i.button&&(this.editor.popover.close(),this.openCustom(e)),r}getButtonValue(e){const t=this.custom.get(e);return t?t.rt.value:null}setButtonValue(e,t){const i=this.custom.get(e);if(!i)return null;const o=(i.rt.items||[]).find(s=>String(s.value)===String(t))||null;return i.rt.value=o,this.syncCustomLabel(e),o}toggleColor(e,t){const i=e==="foreColor"?"fore":"back";this.togglePop(e,t,()=>$i({title:i==="fore"?"字体颜色":"背景高亮色",kind:i,value:this.colorState[e],recents:this.recent[e],onPick:r=>this.applyColor(e,i,r,t),onClear:()=>this.applyColor(e,i,null,t)}),{onClose:()=>t.classList.remove("ke-is-active")})}applyColor(e,t,i,r){this.editor.restoreSelection(),i&&(this.colorState[e]=i,this.recent[e]=[i,...this.recent[e].filter(o=>o.toLowerCase()!==i.toLowerCase())].slice(0,8),this.paintButton(r,t,i)),this.editor.commands.setColor(t,i),this.editor.popover.close()}openCode(){const e=this.buttons.get("code"),t=ge(this.editor.root);this.togglePop("code",e,()=>Ti({languages:this.editor.codeLanguages(),value:t?ce(t)||"plaintext":this.editor.lastCodeLang,editing:!!t,onPick:i=>{this.editor.lastCodeLang=i,this.editor.popover.close(),this.editor.restoreSelection(),t?this.editor.commands.setCodeLanguage(i,t):this.editor.commands.insertCodeBlock("",i),this.editor.refresh()}}))}openMarkdown(){const e=this.buttons.get("markdown"),t=this.editor,i=t.options.markdown;this.togglePop("markdown",e,()=>Ai({insertMode:ke(i.insertMode),accept:Rt,maxText:i.maxSize?`单个文件上限 ${W(i.maxSize)}`:"",highlight:t.options.code.highlight!==!1,onConvert:r=>{const o=et(r,i);return{html:o,summary:tt(o)}},onImport:async({text:r,mode:o})=>(t.popover.close(),(await t.importMarkdown(r,{mode:o})).ok)}))}openTable(){const e=this.buttons.get("table");this.togglePop("table",e,()=>Ni((t,i)=>{this.editor.restoreSelection(),this.editor.commands.insertTable(t,i),this.editor.popover.close()}))}openLink(){const e=this.buttons.get("link"),t=this.editor.getState(),i=t.linkUrl;this.togglePop("link",e,()=>ji({url:i||"",text:i?"":t.selectionText||"",target:i?t.linkTarget:!0,onCancel:()=>this.editor.popover.close(),onRemove:i?()=>{this.editor.restoreSelection(),this.editor.commands.removeLink(),this.editor.popover.close()}:null,onSubmit:({url:r,text:o,target:s})=>{this.editor.restoreSelection(),this.editor.commands.createLink({url:we(r),text:o,target:s}),this.editor.popover.close()}}))}openMedia(e){const t=this.buttons.get(e),i=this.editor,r=i.options;this.togglePop(e,t,()=>Oi(e,{multiple:e==="image",maxText:`${e==="image"?"图片":"视频"}上限 ${lr(e==="image"?r.maxImageSize:r.maxVideoSize)}`,hint:e==="image"?"支持 PNG / JPG / GIF / WebP / SVG":"支持 MP4 / MOV / WebM,大文件自动分片",onFiles:o=>{i.popover.close(),o&&o.length?i.media.addFiles([...o]):i.media.pickFiles(e)},onUrl:({url:o,name:s})=>{i.popover.close(),i.restoreSelection(),i.media.insertFromUrl(e,o,s)}}))}refresh(e){var t;for(const[i,r]of this.buttons){const o=nn[i];if(!o)continue;const s=((t=o.active)==null?void 0:t.call(o,e))||!1;(r.dataset.kPop||!o.pop)&&r.classList.toggle("ke-is-active",s),o.enabled&&(r.disabled=!o.enabled(e))}for(const[i,r]of this.custom){const{spec:o,button:s}=r;s&&(o.active&&s.classList.toggle("ke-is-active",!!o.active(e,this.editor)),o.enabled&&(s.disabled=!o.enabled(e,this.editor)),o.type==="select"&&this.syncCustomLabel(i))}if(this.headingEl){const i=gt.find(o=>o.value===e.block),r=this.headingEl.querySelector(".ke-btn-text");r&&(r.textContent=i?i.label:"正文"),this.headingEl.title=i?`${i.label}:${i.desc}`:"段落样式"}if(this.fontSizeEl){const i=this.fontSizeEl.querySelector(".ke-btn-text");i&&(i.textContent=e.fontSize?`${e.fontSize}px`:"字号")}if(e.linkUrl){const i=this.buttons.get("link");i==null||i.classList.add("ke-is-active")}}setupScrollHints(){const e=this.el,t=this.editor.el;e.isConnected&&(this.scrollFades=d("div.ke-tb-fades",{"aria-hidden":"true"},[d("i.ke-tb-fade ke-tb-fade-l")]),e.insertAdjacentElement("afterend",this.scrollFades),this.syncScrollHints=()=>{if(!e.isConnected||!t.isConnected)return;const i=e.scrollWidth-e.clientWidth,r=i>1,o=e.scrollLeft;t.classList.toggle("ke-tb-scrollable",r),t.classList.toggle("ke-tb-can-l",r&&o>1),t.classList.toggle("ke-tb-can-r",r&&o<i-1),t.style.setProperty("--ke-tb-h",`${e.offsetHeight}px`),r&&!this.hintSettled&&this.showScrollHint()},this.onTbScroll=()=>{this.syncScrollHints(),this.hideScrollHint()},e.addEventListener("scroll",this.onTbScroll,{passive:!0}),typeof ResizeObserver<"u"&&(this.tbRO=new ResizeObserver(()=>this.syncScrollHints()),this.tbRO.observe(e)),this.onTbPointerDown=i=>{this.hideScrollHint(),this.startDragScroll(i)},e.addEventListener("pointerdown",this.onTbPointerDown),requestAnimationFrame(this.syncScrollHints))}startDragScroll(e){const t=this.el,i=this.editor.el;if(e.button!==0||e.pointerType!=="mouse"||t.scrollWidth<=t.clientWidth+1||e.target.closest("input, textarea, select"))return;const r=e.clientX,o=t.scrollLeft;let s=!1;const a=c=>{var h;const u=c.clientX-r;if(!s){if(Math.abs(u)<5)return;s=!0;try{t.setPointerCapture(e.pointerId)}catch{}i.classList.add("ke-tb-dragging"),(h=this.editor.popover)==null||h.close()}c.preventDefault(),t.scrollLeft=o-u},l=()=>{if(t.removeEventListener("pointermove",a),t.removeEventListener("pointerup",l),t.removeEventListener("pointercancel",l),i.classList.remove("ke-tb-dragging"),!s)return;try{t.releasePointerCapture(e.pointerId)}catch{}const c=g=>{g.preventDefault(),g.stopPropagation(),u()},u=()=>{clearTimeout(h),t.removeEventListener("click",c,!0)},h=setTimeout(u,400);t.addEventListener("click",c,!0)};t.addEventListener("pointermove",a),t.addEventListener("pointerup",l),t.addEventListener("pointercancel",l)}showScrollHint(){this.hintSettled=!0;let e=!1;try{e=localStorage.getItem(tn)==="1"}catch{}e||(this.hintEl=d("div.ke-tb-hint",{"aria-hidden":"true"},[d("span.ke-tb-hint-ico",{html:or}),d("span",{text:"工具栏可左右滑动"})]),this.editor.el.appendChild(this.hintEl),this.hintTimer=setTimeout(()=>this.hideScrollHint(),3800))}hideScrollHint(){this.hintTimer&&(clearTimeout(this.hintTimer),this.hintTimer=null);const e=this.hintEl;if(e){this.hintEl=null;try{localStorage.setItem(tn,"1")}catch{}e.classList.add("ke-is-out"),setTimeout(()=>e.remove(),260)}}destroy(){var i,r,o;const e=this.el;this.tbRO&&(this.tbRO.disconnect(),this.tbRO=null),this.hintTimer&&(clearTimeout(this.hintTimer),this.hintTimer=null),this.onTbScroll&&e.removeEventListener("scroll",this.onTbScroll),this.onTbPointerDown&&e.removeEventListener("pointerdown",this.onTbPointerDown);for(const s of this.custom.values())ht(s.rt);this.custom.clear(),(i=this.scrollFades)==null||i.remove(),(r=this.hintEl)==null||r.remove(),this.scrollFades=null,this.hintEl=null;const t=(o=this.editor)==null?void 0:o.el;t&&(t.classList.remove("ke-tb-scrollable","ke-tb-can-l","ke-tb-can-r","ke-tb-dragging"),t.style.removeProperty("--ke-tb-h")),e.innerHTML="",this.buttons.clear()}}function lr(n){if(!n)return"不限";const e=n/1024/1024;return e>=1?`${Math.round(e)}MB`:`${Math.round(n/1024)}KB`}function P(n){const e=window.getSelection();if(!e||e.rangeCount===0)return null;const t=e.getRangeAt(0);return n.contains(t.commonAncestorContainer)?t:null}function rn(n){const e=window.getSelection();if(!e||e.rangeCount===0)return null;const t=e.getRangeAt(0);if(!n.contains(t.startContainer))return null;let i=0;return document.createTreeWalker(n,NodeFilter.SHOW_TEXT,{acceptNode(s){return s===t.startContainer?NodeFilter.FILTER_ACCEPT:(i+=s.textContent.length,NodeFilter.FILTER_SKIP)}}).nextNode()?i+t.startOffset:t.startContainer===n?0:null}function cr(n,e){if(e==null)return;const t=window.getSelection();let i=Math.max(0,e);const r=document.createTreeWalker(n,NodeFilter.SHOW_TEXT);let o=r.nextNode(),s=null;for(;o;){const a=o.textContent.length;if(i<=a){try{t.setBaseAndExtent(o,i,o,i)}catch{}return}i-=a,s=o,o=r.nextNode()}if(s)try{t.setBaseAndExtent(s,s.textContent.length,s,s.textContent.length)}catch{}}function oe(n,e,{inline:t=!1,selectAfter:i=!0}={}){n.focus();const r=P(n);if(!r)return n.appendChild(e),Ie(n),e;if(r.collapsed||r.deleteContents(),t)r.insertNode(e);else{const a=se(r.startContainer,n);!a||a===n?n.appendChild(e):a.after(e)}const o=document.createRange();o.setStartAfter(e),o.collapse(!0);const s=window.getSelection();return s.removeAllRanges(),s.addRange(o),Ie(n),i&&s.rangeCount===0&&n.focus(),e}function Ie(n){const e=n.lastElementChild;if(!e){n.appendChild(document.createElement("p"));return}if(/^(IMG|VIDEO|IFRAME)$/.test(e.tagName)||e.dataset.kmedia!==void 0){const t=document.createElement("p");t.appendChild(document.createElement("br")),n.appendChild(t)}}function se(n,e){let t=n;for(;t&&t!==e;){if(t.nodeType===1&&/^(P|DIV|H[1-6]|LI|BLOCKQUOTE|PRE|SECTION|TD|TH)$/.test(t.tagName))return t;t=t.parentNode}return null}class dr{constructor(e){this.editor=e,this.root=e.root}exec(e,t=null){this.editor.focus(),document.execCommand("styleWithCSS",!1,!0),document.execCommand("defaultParagraphSeparator",!1,"p");const i=document.execCommand(e,!1,t);return this.editor.afterEdit(),i}queryState(e){try{return document.queryCommandState(e)}catch{return!1}}queryValue(e){try{return document.queryCommandValue(e)}catch{return""}}hasSelection(){const e=P(this.root);return!!(e&&!e.collapsed)}toggleMark(e){const i={bold:"bold",italic:"italic",underline:"underline",strike:"strikeThrough"}[e];i&&(this.exec(i),this.root.querySelectorAll('span[style=""]').forEach(r=>r.replaceWith(...r.childNodes)))}setFontSize(e){this.editor.focus(),document.execCommand("styleWithCSS",!1,!1);const t=`__ke_fs_${qe()}__`;this.root.setAttribute("data-ke-marker",t),document.execCommand("fontSize",!1,"7"),this.root.removeAttribute("data-ke-marker"),this.root.querySelectorAll('font[size="7"]').forEach(i=>{const r=document.createElement("span");for(r.style.fontSize=`${e}px`;i.firstChild;)r.appendChild(i.firstChild);i.replaceWith(r)}),this.root.querySelectorAll("span").forEach(i=>{/xx-large/i.test(i.style.fontSize)&&(i.style.fontSize=`${e}px`)}),document.execCommand("styleWithCSS",!1,!0),this.editor.afterEdit()}setColor(e,t){this.editor.focus(),document.execCommand("styleWithCSS",!1,!0),t||(t=e==="fore"?"#3f3f3f":"transparent"),document.execCommand(e==="fore"?"foreColor":"hiliteColor",!1,t)||document.execCommand(e==="fore"?"foreColor":"backColor",!1,t),e==="back"&&t==="transparent"&&this.root.querySelectorAll('[style*="background-color"]').forEach(r=>{/background-color:\s*transparent|rgba\(0, 0, 0, 0\)/i.test(r.getAttribute("style")||"")&&(r.style.backgroundColor="",r.getAttribute("style").trim()||r.replaceWith(...r.childNodes))}),this.editor.afterEdit()}setAlign(e){var l,c;const t=(l=this.editor.bubble)==null?void 0:l.node;if(t&&((c=t.dataset)==null?void 0:c.kMedia)==="image"&&e!=="justify"){const u=t.querySelector("img");if(u){We(u,e),this.editor.commitHistory(),this.editor.bubble.position();return}}const r={left:"justifyLeft",center:"justifyCenter",right:"justifyRight",justify:"justifyFull"}[e];if(!r)return;this.editor.focus();const o=P(this.root),s=se((o==null?void 0:o.commonAncestorContainer)||this.root,this.root);document.execCommand("styleWithCSS",!1,!0),document.execCommand(r);const a=s||this.root.firstElementChild;a&&/^(FIGURE|DIV|VIDEO)/.test(a.tagName||"")&&(a.style.textAlign=e),this.editor.afterEdit()}toggleList(e){this.exec(e==="ordered"?"insertOrderedList":"insertUnorderedList")}setHeading(e){const t=e?`<${e}>`:"<p>";this.exec("formatBlock",t)}toggleBlockquote(){const e=P(this.root),t=se((e==null?void 0:e.commonAncestorContainer)||this.root,this.root);t&&t.tagName==="BLOCKQUOTE"?this.exec("formatBlock","<p>"):this.exec("formatBlock","<blockquote>")}createLink({url:e,text:t="",target:i=!1}){var a,l;this.editor.focus();const r=P(this.root),o=r&&!r.collapsed,s=t||(o?r.toString():e);if(o)document.execCommand("createLink",!1,e),(l=(a=r.commonAncestorContainer.parentElement)==null?void 0:a.closest)==null||l.call(a,"a"),this.root.querySelectorAll(`a[href="${hr(e)}"]`).forEach(c=>{i?(c.setAttribute("target","_blank"),c.setAttribute("rel","noopener noreferrer")):c.removeAttribute("target")});else{const c=d("a",{href:e},[s]);i&&(c.setAttribute("target","_blank"),c.setAttribute("rel","noopener noreferrer")),oe(this.root,c,{inline:!0})}this.editor.afterEdit()}removeLink(){const e=P(this.root);ur(e,this.root).forEach(i=>i.replaceWith(...i.childNodes)),this.editor.afterEdit()}insertTable(e,t){const i=document.createElement("table"),r=document.createElement("tbody");for(let o=0;o<t;o+=1){const s=document.createElement("tr");for(let a=0;a<e;a+=1){const l=document.createElement(o===0?"th":"td");l.innerHTML="<br>",s.appendChild(l)}r.appendChild(s)}i.appendChild(r),oe(this.root,i),this.exec("insertHTML",""),this.editor.afterEdit()}insertCodeBlock(e="",t){const i=document.createElement("pre"),r=document.createElement("code");return r.textContent=e||"// 在这里输入代码",i.appendChild(r),Ve(i,t||this.editor.lastCodeLang),He(i),oe(this.root,i),this.editor.afterEdit(),this.placeCaretIn(i),i}setCodeLanguage(e,t){const i=t||ge(this.root);if(!i)return null;const r=Ve(i,e);return He(i,{caret:!0}),this.editor.afterEdit(),r}placeCaretIn(e){const t=Re(e),i=document.createRange();i.selectNodeContents(t),i.collapse(!1);const r=window.getSelection();r.removeAllRanges(),r.addRange(i)}currentCodeLang(){const e=ge(this.root);return e?ce(e):""}insertDivider(){const e=document.createElement("hr");oe(this.root,e),this.editor.afterEdit()}insertHTML(e,{clean:t=!0}={}){const i=t?ae(e):e;this.editor.focus();const r=P(this.root);if(r){r.deleteContents();const o=document.createElement("div");o.innerHTML=i,o.querySelectorAll("pre").forEach(l=>{(l.querySelector("code")||l.hasAttribute("data-k-lang"))&&He(l)});const s=document.createDocumentFragment();for(;o.firstChild;)s.appendChild(o.firstChild);const a=s.lastChild;if(r.insertNode(s),a){const l=document.createRange();l.setStartAfter(a.nodeType===3?a:a.lastChild||a),l.collapse(!0);const c=window.getSelection();c.removeAllRanges(),c.addRange(l)}}else this.root.insertAdjacentHTML("beforeend",i);this.editor.afterEdit()}clearFormat(){if(this.editor.focus(),this.hasSelection()){document.execCommand("removeFormat"),document.execCommand("unlink");const e=P(this.root),t=se(e==null?void 0:e.commonAncestorContainer,this.root);t&&/^(H[1-6]|BLOCKQUOTE|PRE)$/.test(t.tagName)&&this.exec("formatBlock","<p>"),this.stripInlineStylesInRange(e)}else{const e=P(this.root),t=se((e==null?void 0:e.commonAncestorContainer)||this.root,this.root);if(t){const i=t.innerHTML,r=document.createElement("p");r.innerHTML=ae(i,{allowEmpty:!0}),r.innerHTML=r.innerHTML.replace(/<(?!br|img)[^>]+>/gi,""),t.replaceWith(r)}}this.editor.afterEdit()}stripInlineStylesInRange(e){if(!e)return;const t=[],i=document.createTreeWalker(e.commonAncestorContainer,NodeFilter.SHOW_ELEMENT);let r=i.currentNode;for(;r;)e.intersectsNode(r)&&r.nodeType===1&&t.push(r),r=i.nextNode();t.forEach(o=>{o!==this.root&&(o.removeAttribute("style"),/^(SPAN|FONT)$/.test(o.tagName)&&!o.attributes.length&&o.replaceWith(...o.childNodes))})}currentBlock(){var i;const e=P(this.root),t=se((e==null?void 0:e.commonAncestorContainer)||this.root,this.root);return((i=t==null?void 0:t.tagName)==null?void 0:i.toLowerCase())||"p"}currentFontSize(){const e=P(this.root);if(!e)return"";let t=e.startContainer;for(;t&&t!==this.root;){if(t.nodeType===1&&t.style.fontSize)return t.style.fontSize.replace("px","");t=t.parentNode}return""}}function ur(n,e){var s,a,l;if(!n)return[];const t=new Set;let r=n.startContainer.nodeType===1&&((a=(s=n.startContainer).querySelector)==null?void 0:a.call(s,"a"))||n.startContainer;for(;r&&r!==e;)r.tagName==="A"&&t.add(r),r=r.parentNode;try{(l=n.querySelectorAll)==null||l.call(n,"a").forEach(c=>t.add(c))}catch{}const o=n.commonAncestorContainer;return o.nodeType===1&&o.querySelectorAll("a").forEach(c=>n.intersectsNode(c)?t.add(c):null),[...t]}function hr(n){var e;return(e=window.CSS)!=null&&e.escape?CSS.escape(n):String(n).replace(/["\\]/g,"\\$&")}class pr{constructor(e,{limit:t=60,delay:i=400}={}){this.root=e,this.limit=t,this.delay=i,this.stack=[],this.index=-1,this.timer=null,this.locked=!1,this.lastHtml=e.innerHTML}snapshot(e=!1){clearTimeout(this.timer);const t=()=>{const i=this.root.innerHTML;if(i===this.lastHtml)return;this.lastHtml=i;const r={html:i,offset:rn(this.root)};this.stack=this.stack.slice(0,this.index+1),this.stack.push(r),this.stack.length>this.limit&&this.stack.shift(),this.index=this.stack.length-1};e?t():this.timer=setTimeout(t,this.delay)}flush(){clearTimeout(this.timer),this.snapshot(!0)}apply(e,t){this.locked=!0,this.root.innerHTML=e,this.lastHtml=e,t!=null&&cr(this.root,t),this.locked=!1}canUndo(){return this.index>0}canRedo(){return this.index>=0&&this.index<this.stack.length-1}undo(){if(!this.canUndo())return!1;clearTimeout(this.timer),this.index-=1;const e=this.stack[this.index];return this.apply(e.html,this.currentOffset(e,"undo")),this.lastHtml=e.html,!0}redo(){if(!this.canRedo())return!1;const e=this.stack[this.index+1];return this.index+=1,this.apply(e.html,this.currentOffset(e,"redo")),this.lastHtml=e.html,!0}currentOffset(e){const t=rn(this.root);return e.offset}reset(e){clearTimeout(this.timer),this.stack=[{html:e,offset:0}],this.index=0,this.lastHtml=e}destroy(){clearTimeout(this.timer),this.stack=[]}}const fr=/\.(jpe?g|png|gif|webp|bmp|svg|avif)$/i,mr=/\.(mp4|mov|webm|m4v|ogv|avi|mkv)$/i;class gr{constructor(e){this.editor=e,this.options=e.options,this.tasks=new Map,this.input=null}kindOf(e){const t=String(e.type||""),i=String(e.name||"");return t.startsWith("image/")||fr.test(i)?"image":t.startsWith("video/")||mr.test(i)?"video":null}check(e,t){if(!t)return`不支持的文件类型:${e.name||"剪贴板内容"}`;const i=t==="image"?this.options.maxImageSize:this.options.maxVideoSize;return i&&e.size>i?`${e.name} 超出大小限制(${W(i)})`:null}pickFiles(e){this.input||(this.input=d("input",{type:"file",multiple:!0,style:{display:"none"}}),this.input.addEventListener("change",()=>{const t=[...this.input.files||[]];this.input.value="",this.addFiles(t)}),document.body.appendChild(this.input)),this.input.accept=e==="image"?this.options.imageAccept:this.options.videoAccept,this.input.multiple=e==="image",this.input.click()}async addFiles(e){const t=[];for(const i of e){const r=this.kindOf(i),o=this.check(i,r);o?this.editor.toast.warn(o):t.push({file:i,kind:r})}for(const i of t)await this.upload(i.file,i.kind);return t.length}async upload(e,t){const i=t==="image"?this.createImageHolder():this.createVideoHolder();this.editor.focus(),oe(this.editor.root,i);const r={id:i.dataset.kId,file:e,kind:t,holder:i,ctrl:new AbortController,previewUrl:URL.createObjectURL(e)};this.tasks.set(r.id,r),this.decorateHolder(r);const o=i.querySelector("[data-k-preview]");return o&&(o.src=r.previewUrl),this.runUpload(r)}async runUpload(e){const t=this.editor,{holder:i,file:r,kind:o}=e;t.emit("uploadstart",{file:r,kind:o}),t.refreshStatus();let s=r;try{o==="image"&&(s=await sn(r,this.options.image));const a=await t.uploader.upload(s,{signal:e.ctrl.signal,onProgress:(c,u)=>this.updateProgress(i,c,u,s,e)}),l=typeof a=="string"?{url:a}:a;if(!(l!=null&&l.url))throw new Error("上传结果缺少 url");return this.finish(e,{...l,size:s.size}),t.emit("uploaddone",{file:r,kind:o,url:l.url}),l}catch(a){return(a==null?void 0:a.name)==="AbortError"?(this.remove(e),t.emit("uploadcancel",{file:r,kind:o}),null):(this.fail(e,a),t.emit("uploaderror",{file:r,kind:o,error:a}),t.toast.error((a==null?void 0:a.message)||"上传失败"),null)}finally{Ie(t.root),t.commitHistory(),t.refreshStatus()}}createImageHolder(){const e=d("figure",{"data-k-media":"image","data-k-id":qe("m"),"data-k-state":"uploading",contenteditable:"false"}),t=d("div.ke-media-holder",{},[d("img",{"data-k-preview":"",alt:"",style:{display:"none"}}),d("div.ke-media-name",{text:"图片上传中…"}),on()]);return t.appendChild(this.actionRow()),e.appendChild(t),e}createVideoHolder(){const e=d("div.ke-video-card",{"data-k-media":"video","data-k-id":qe("m"),"data-k-state":"uploading",contenteditable:"false"}),t=d("div.ke-video-body",{},[d("div.ke-video-head",{},[d("span",{text:"视频上传中…"}),d("span.ke-video-size",{text:""})]),on()]);return t.appendChild(this.actionRow()),e.appendChild(t),e}actionRow(){const e=this;return d("div",{"data-k-actions":"",style:{display:"flex",alignItems:"center",gap:"8px",width:"100%",marginTop:"2px"},onclick:t=>{const i=t.target.closest("[data-k-id]"),r=i&&e.tasks.get(i.dataset.kId);r&&(t.target.matches(".ke-media-cancel")?(r.ctrl.abort(),e.remove(r)):t.target.matches(".ke-media-retry")&&(r.ctrl=new AbortController,e.resetHolder(r),e.runUpload(r)))}},[d("button.ke-media-cancel",{type:"button",text:"取消"})])}decorateHolder(e){const{holder:t,file:i}=e,r=t.querySelector(".ke-media-name");r&&(r.textContent=`${i.name||"未命名"}(${W(i.size)})`);const o=t.querySelector(".ke-video-size");o&&(o.textContent=W(i.size));const s=t.querySelector(".ke-video-head span");s&&e.kind==="video"&&(s.textContent=`${i.name||"视频"} 上传中…`)}resetHolder(e){const t=e.holder;t.dataset.kState="uploading";const i=t.querySelector(".ke-progress i");i&&(i.style.width="0%",i.style.background="");const r=t.querySelector(".ke-media-pct");r&&(r.textContent="0%");const o=t.querySelector("[data-k-actions]");o&&(o.innerHTML='<button class="ke-media-cancel" type="button">取消</button>'),this.decorateHolder(e)}updateProgress(e,t,i,r,o){const s=Math.max(0,Math.min(100,Math.round((t||0)*100))),a=e.querySelector(".ke-progress i");a&&(a.style.width=`${s}%`);const l=e.querySelector(".ke-media-pct");l&&(l.textContent=`${s}%`),o&&this.editor.emit("uploadprogress",{file:o.file,kind:o.kind,percent:s,info:i});const c=e.querySelector(".ke-media-meta");if(!c)return;let u=c.querySelector("[data-k-chunks]");u||(u=d("span",{"data-k-chunks":"",style:{color:"#8a8f99",fontSize:"12px"}}),c.insertBefore(u,c.firstChild)),(i==null?void 0:i.chunks)>1?u.textContent=`${i.chunks} 片 · ${W(i.loaded)}/${W(i.total||r.size)}`:i!=null&&i.speed&&(u.textContent=`${W(i.speed)}/s`)}finish(e,t){const{holder:i,kind:r,file:o}=e,s=t.url;if(i.dataset.kState="done",i.dataset.kUrl=s,i.innerHTML="",r==="image"){const a=d("img",{src:s,alt:kr(o),"data-k-name":o.name||"",draggable:"false"});a.addEventListener("dblclick",()=>Oe(a.src)),i.appendChild(a)}else{const a=d("video",{src:s,controls:"",playsinline:"",preload:"metadata","data-k-name":o.name||""}),l=d("div.ke-video-body",{},[d("div.ke-video-head",{},[d("span",{text:o.name||"视频"}),d("span.ke-video-size",{text:W(t.size||o.size)})]),a]);i.appendChild(l)}e.previewUrl&&URL.revokeObjectURL(e.previewUrl),this.tasks.delete(e.id),this.editor.refreshStatus()}fail(e,t){const i=e.holder;i.dataset.kState="error";const r=i.querySelector(".ke-progress i");r&&(r.style.background="#e53e3e");const o=i.querySelector("[data-k-actions]");o&&(o.innerHTML="",o.appendChild(d("span.ke-media-error",{text:(t==null?void 0:t.message)||"上传失败",style:{marginRight:"auto",fontSize:"12px"}})),o.appendChild(d("button.ke-media-retry",{type:"button",text:"重试"})),o.appendChild(d("button.ke-media-cancel",{type:"button",text:"移除"})))}remove(e){var t;(t=e.holder)==null||t.remove(),e.previewUrl&&URL.revokeObjectURL(e.previewUrl),this.tasks.delete(e.id),Ie(this.editor.root),this.editor.refreshStatus()}taskFromNode(e){var i;const t=(i=e==null?void 0:e.closest)==null?void 0:i.call(e,"[data-k-id]");return t?this.tasks.get(t.dataset.kId):null}cancelAll(){for(const e of[...this.tasks.values()])e.ctrl.abort(),this.remove(e)}insertFromUrl(e,t,i=""){const r=e==="image"?this.insertImageUrl(t,i):this.insertVideoUrl(t,i||"网络视频");return this.editor.toast.ok(e==="image"?"已插入网络图片":"已插入网络视频"),this.editor.emit("insertmedia",{kind:e,url:t,node:r}),r}insertImageUrl(e,t=""){const i=d("img",{src:e,alt:t||"",draggable:"false"});i.addEventListener("dblclick",()=>Oe(i.src));const r=d("figure",{"data-k-media":"image","data-k-state":"done","data-k-url":e,contenteditable:"false"},[i]);return oe(this.editor.root,r),this.editor.commitHistory(),r}insertVideoUrl(e,t="视频"){const i=d("video",{src:e,controls:"",playsinline:"",preload:"metadata"}),r=d("div.ke-video-card",{"data-k-media":"video","data-k-state":"done","data-k-url":e,contenteditable:"false"},[d("div.ke-video-body",{},[d("div.ke-video-head",{},[d("span",{text:t})]),i])]);return oe(this.editor.root,r),this.editor.commitHistory(),r}destroy(){var e;this.cancelAll(),(e=this.input)==null||e.remove(),this.input=null}}function kr(n){return String(n.name||"").replace(/\.[^.]+$/,"")}function on(){return d("div.ke-media-meta",{},[d("div.ke-progress",{},[d("i",{style:{width:"0%"}})]),d("span.ke-media-pct",{text:"0%"})])}async function sn(n,e={}){var s,a;const t=e==null?void 0:e.compress;if(!t||!/^image\/(jpeg|jpg|png|webp)$/i.test(n.type))return n;const{maxWidth:i=1440,quality:r=.85,minSize:o=300*1024}=typeof t=="object"?t:{};if(n.size<o)return n;try{const l=await createImageBitmap(n);if(l.width<=i)return(s=l.close)==null||s.call(l),n;const c=document.createElement("canvas");c.width=i,c.height=Math.round(l.height*i/l.width),c.getContext("2d").drawImage(l,0,0,c.width,c.height),(a=l.close)==null||a.call(l);const u=await new Promise(h=>c.toBlob(h,"image/jpeg",r));return!u||u.size>=n.size?n:new File([u],String(n.name).replace(/\.\w+$/,".jpg"),{type:"image/jpeg",lastModified:n.lastModified})}catch{return n}}function kt(n){return`${ln(n.size)}-${br(n.lastModified)}-${xr(n.name)}`}async function an(n){var a;if(!((a=globalThis.crypto)!=null&&a.subtle))return kt(n);const e=256*1024,t=[n.slice(0,e)];n.size>e&&t.push(n.slice(n.size-e));const i=new Uint8Array(t.reduce((l,c)=>l+c.size,0));let r=0;for(const l of t){const c=new Uint8Array(await l.arrayBuffer());i.set(c,r),r+=c.length}const o=await crypto.subtle.digest("SHA-256",i);return`${Array.from(new Uint8Array(o)).map(l=>l.toString(16).padStart(2,"0")).join("").slice(0,24)}-${ln(n.size)}`}const ln=n=>Number(n).toString(16),br=n=>Number(n||0).toString(16),xr=n=>String(n).replace(/[^\w.-]/g,"").slice(0,24);function yr(n="fast"){return n==="strong"||n==="sha256"?an:typeof n=="function"?n:async e=>kt(e)}const vr=1024*1024;class Pe{constructor(e,t={}){if(!e||typeof e.upload!="function")throw new Error("[KEditor] 普通上传的 uploader 需要提供 upload() 方法(或直接给一个接口地址 / 上传函数),参见 docs/upload-adapter.md");this.adapter=e,this.mode="normal",this.options=t}async upload(e,t={}){const{onProgress:i,signal:r}=t,o=Date.now(),s=(c,u)=>{const h=(Date.now()-o)/1e3;i==null||i(c,{percent:Math.round(c*100),loaded:u,total:e.size,chunks:1,uploadedChunks:c>=1?1:0,speed:h>0?u/h:0,mode:"normal"})};s(0,0);const a=await this.adapter.upload(e,{signal:r,onProgress:(c,u)=>s(u?Math.min(1,c/u):0,c)}),l=typeof a=="string"?a:a==null?void 0:a.url;if(!l)throw new Error('[KEditor] 普通上传接口未返回 url:期望响应形如 { "url": "https://…" }');return s(1,e.size),{url:l,chunks:1,mode:"normal",size:e.size,name:e.name,key:typeof a=="object"?a.key:void 0,raw:a}}destroy(){var e,t;(t=(e=this.adapter).destroy)==null||t.call(e)}}class bt{constructor(e,t={}){if(!e||typeof e.put!="function"&&typeof e.upload!="function")throw new Error("[KEditor] 分片上传的 uploader 需要提供 put() 方法,参见 docs/upload-adapter.md");this.adapter=e,this.simple=typeof e.put=="function"?null:new Pe(e,t),this.mode="chunk",this.chunkSize=Math.max(64*1024,t.chunkSize||vr),this.concurrency=Math.max(1,t.concurrency||3),this.retries=t.retries===void 0?2:Math.max(0,t.retries),this.retryDelay=t.retryDelay??600,this.fingerprint=yr(t.fingerprint||"fast"),this.slice=t.slice,this.completeOnUrl=t.completeOnUrl===void 0?!!e.completeOnUrl:!!t.completeOnUrl}async upload(e,t={}){var A,De,ue,E,z,$;if(this.simple)return this.simple.upload(e,t);const{onProgress:i,onChunk:r,signal:o}=t,s=Math.max(1,Math.ceil(e.size/this.chunkSize)),a={name:e.name||"blob",size:e.size,type:e.type||Cr(e.name),lastModified:e.lastModified||0,fingerprint:await this.fingerprint(e),chunkSize:this.chunkSize,totalChunks:s},l=await((De=(A=this.adapter).init)==null?void 0:De.call(A,a,{signal:o}))||{};if(l.url)return i==null||i(1,{percent:100,loaded:e.size,total:e.size,chunks:s,instant:!0,mode:"chunk"}),{url:l.url,instant:!0,chunks:0,mode:"chunk",size:e.size,name:a.name,key:l.key};const c=l.uploadId||a.fingerprint,u=new Set((l.uploadedChunks||l.uploaded||[]).map(Number));let h=0;for(const M of u)h+=Math.min(this.chunkSize,e.size-M*this.chunkSize);const g=[];for(let M=0;M<s;M+=1)u.has(M)||g.push(M);const p=new Array(s);let f=u.size,k="";const m=Date.now(),x=()=>{const M=(Date.now()-m)/1e3;i==null||i(e.size?h/e.size:1,{percent:Math.min(100,Math.round(h/Math.max(1,e.size)*100)),loaded:h,total:e.size,chunks:s,uploadedChunks:f,speed:M>0?h/M:0,mode:"chunk"})};x();let C=0;const w=async()=>{for(;C<g.length&&!k;){if(o!=null&&o.aborted)throw new DOMException("已取消上传","AbortError");const M=g[C++],ie=this.slice?this.slice(e,M,this.chunkSize):e.slice(M*this.chunkSize,(M+1)*this.chunkSize);let Te=0;for(;;)try{const N=await this.adapter.put({uploadId:c,index:M,total:s,chunkSize:this.chunkSize,blob:ie,file:e,meta:a,signal:o,size:ie.size});if(N!=null&&N.url&&(p[M]=N),N!=null&&N.url&&this.completeOnUrl){k=N.url,f=s,h=e.size,x();break}h+=ie.size,f+=1,r==null||r({index:M,total:s,size:ie.size}),x();break}catch(N){if((N==null?void 0:N.name)==="AbortError")throw N;if(Te+=1,Te>this.retries)throw new Error(`分片 ${M+1}/${s} 上传失败:${(N==null?void 0:N.message)||N}`);await wr(this.retryDelay*Te,o)}}},T=Array.from({length:Math.max(1,Math.min(this.concurrency,g.length))},w),L=await Promise.allSettled(T),b=k?null:L.find(M=>M.status==="rejected");if(b)throw await((E=(ue=this.adapter).abort)==null?void 0:E.call(ue,{uploadId:c,meta:a,error:b.reason}).catch(()=>{})),b.reason;const v=k?{url:k}:await(($=(z=this.adapter).complete)==null?void 0:$.call(z,{uploadId:c,meta:a,total:s,uploaded:f,chunkResults:p,file:e}))||{},S=v.url;if(!S)throw new Error(this.completeOnUrl?'[KEditor] 上传结束但接口未返回 url:分片上传要求接口在处理分片时返回 { "url": "…" }':"[KEditor] uploader.complete() 未返回 url");return{url:S,chunks:s,mode:"chunk",size:e.size,name:a.name,key:v.key,poster:v.poster,duration:v.duration,raw:v}}destroy(){var e,t,i;(e=this.simple)==null||e.destroy(),(i=(t=this.adapter).destroy)==null||i.call(t)}}const wr=(n,e)=>new Promise((t,i)=>{const r=setTimeout(()=>{e==null||e.removeEventListener("abort",o),t()},n),o=()=>{clearTimeout(r),i(new DOMException("已取消上传","AbortError"))};e==null||e.addEventListener("abort",o,{once:!0})});function Cr(n=""){var i;const e=(i=String(n).split(".").pop())==null?void 0:i.toLowerCase();return{jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",mp4:"video/mp4",mov:"video/quicktime",webm:"video/webm",m4v:"video/x-m4v"}[e]||"application/octet-stream"}function cn(n){return{simple:!0,async upload(e,t={}){const i=await n(Sr(e),t);return typeof i=="string"?{url:i}:i}}}function Sr(n,e="blob",t=n.type){return n instanceof File?n:new File([n],e,{type:t})}const Fe=n=>new Promise(e=>setTimeout(e,n)),dn=(n,e=.4)=>n*(1-e+Math.random()*e*2);function xt(n={}){const{latency:e=160,speed:t=12,onEvent:i=null,reuseObjectUrl:r=!0,failFirstChunk:o=!1}=n,s=new Map,a=new Map,l=new Map;let c=o;const u=(p,f)=>i==null?void 0:i(p,{...f,at:Date.now()}),h=(p,f)=>{let k=l.get(f.fingerprint);if(!k||!r){const m=p instanceof File?p:new File([p],f.name,{type:f.type});k=URL.createObjectURL(m),l.set(f.fingerprint,k)}return k},g=(p,f)=>s.set(p.fingerprint,{url:f,name:p.name,size:p.size,type:p.type});return{name:"mock",async init(p){u("init",p),await Fe(120);const f=s.get(p.fingerprint);if(f)return u("instant",{name:p.name,url:f.url}),{url:f.url,key:p.fingerprint,instant:!0};const k=a.get(p.fingerprint)||new Set;return a.set(p.fingerprint,k),{uploadId:p.fingerprint,uploadedChunks:[...k]}},async put({uploadId:p,index:f,total:k,size:m,blob:x}){if(c&&f===0){c=!1,u("chunk-error",{index:f,total:k,message:"mock: 模拟首个分片网络异常"});const T=new Error("mock: 模拟首个分片网络异常");throw T.retryable=!0,T}const C=Math.max(40,dn(e+m/(t*1024/8)/8,.35));await Fe(C);const w=a.get(p)||new Set;return w.add(f),a.set(p,w),u("chunk",{index:f,total:k,size:m,blobSize:x==null?void 0:x.size}),{etag:`${p}-${f}`}},async complete({uploadId:p,meta:f,file:k}){await Fe(140);const m=h(k,f);return g(f,m),a.delete(p),u("complete",{name:f.name,url:m,chunks:f.totalChunks,size:f.size}),{url:m,key:f.fingerprint}},async upload(p,f={}){var T,L;const k={name:p.name||"blob",size:p.size,type:p.type||"application/octet-stream",fingerprint:`${p.name||"blob"}|${p.size}|${p.lastModified||0}`},m=s.get(k.fingerprint);if(m)return(T=f.onProgress)==null||T.call(f,p.size,p.size),u("instant",{name:k.name,url:m.url}),{url:m.url,key:k.fingerprint,instant:!0};const x=Math.max(140,dn(e*2+p.size/(t*1024/8)/6,.3)),C=6;for(let b=1;b<=C;b+=1)await Fe(x/C),(L=f.onProgress)==null||L.call(f,Math.round(p.size*b/C),p.size);const w=h(p,k);return g(k,w),u("upload",{name:k.name,url:w,size:k.size}),{url:w,key:k.fingerprint}},async abort({uploadId:p}){u("abort",{uploadId:p})},list:()=>[...s.entries()].map(([p,f])=>({key:p,...f})),reset:()=>{s.clear(),a.clear()}}}function Er(n){if(!n||typeof n!="object")return"";const e=n.url||n.fileUrl||n.src;return typeof e=="string"?e.trim():""}const Lr=["initUrl","chunkUrl","completeUrl","abortUrl"];function yt(n={}){const{url:e,fieldName:t="file",headers:i={},withCredentials:r=!1,parse:o=m=>(m==null?void 0:m.data)||m||{},pickUrl:s=Er,chunkUrlFor:a}=n,l=Lr.filter(m=>n[m]);if(l.length)throw new Error(`[KEditor] 分片上传已改为「单接口」模式:请删除 httpAdapter 的 ${l.join(" / ")},只保留 url。服务端在处理分片时返回 { "url": "…" } 即代表上传成功。`);if(!e)throw new Error('[KEditor] httpAdapter 缺少接口地址:httpAdapter({ url: "/api/upload" })');const c=n.mode||"formdata",u=n.method||(c==="formdata"?"POST":"PUT"),h=m=>{const x=(typeof s=="function"?s(m):"")||"";return x?{...m&&typeof m=="object"?m:{},url:x}:m||{}},g=()=>typeof i=="function"?i()||{}:i||{},p=async(m,x={})=>{const C=await fetch(m,{credentials:r?"include":"same-origin",...x});if(!C.ok)throw new Error(`HTTP ${C.status} ${C.statusText}`);const w=await C.text();if(!w)return{};try{return o(JSON.parse(w))}catch{throw new Error(`服务端返回非 JSON 数据:${w.slice(0,80)}`)}},f=(m,x)=>`${m}${m.includes("?")?"&":"?"}${x.map(([C,w])=>`${C}=${encodeURIComponent(w)}`).join("&")}`,k=async({target:m,body:x,name:C,index:w,total:T,meta:L,signal:b})=>{if(c==="formdata"){const A=new FormData;return A.append(t,x,w===void 0?C:`${C}.part${w}`),A.append("filename",C),A.append("fileSize",String(L.size)),L.identifier&&A.append("identifier",L.identifier),w!==void 0&&(A.append("index",String(w)),A.append("total",String(T)),A.append("chunkSize",String(L.chunkSize))),h(await p(m,{method:u,body:A,signal:b,headers:g()}))}const v=w===void 0?[["filename",C],["fileSize",L.size]]:[["identifier",L.identifier],["index",w],["total",T],["filename",C]],S=w===void 0?{"Content-Type":"application/octet-stream"}:{"Content-Type":"application/octet-stream","X-Chunk-Index":String(w)};return h(await p(f(m,v),{method:u,body:x,signal:b,headers:{...S,...g()}}))};return{name:"http",completeOnUrl:!0,url:e,async upload(m,x={}){return k({target:e,body:m,name:m.name||"file",meta:{size:m.size,identifier:""},signal:x.signal})},async put({index:m,total:x,blob:C,meta:w,signal:T}){const L=typeof a=="function"?a({index:m,total:x}):e;return k({target:L,body:C,name:w.name,index:m,total:x,meta:{size:w.size,chunkSize:w.chunkSize,identifier:w.fingerprint},signal:T})}}}const Mr=["chunkSize","concurrency","retries","retryDelay","fingerprint","completeOnUrl","slice"],un=n=>n instanceof Pe||n instanceof bt;function hn(n,e){if(n==null||n==="mock")return xt({});if(typeof n=="string"){if(!/^(https?:)?\/\//.test(n)&&!n.startsWith("/"))throw new Error(`[KEditor] 无法识别的${e}配置:${n}(接口地址请以 / 或 http(s):// 开头)`);return yt({url:n})}if(typeof n=="function")return cn(n);if(typeof n=="object")return typeof n.upload=="function"||typeof n.put=="function"?n:n.type==="mock"?xt(n):yt(n);throw new Error(`[KEditor] 无法识别的${e}配置:${typeof n}`)}function pn(n,e){const t={...n||{}};if(e&&typeof e=="object")for(const i of Mr)e[i]!==void 0&&(t[i]=e[i]);return t}function fn(n,e={}){return un(n)?n:new Pe(hn(n,"普通上传"),pn(e,n))}function mn(n,e={}){return un(n)?n:new bt(hn(n,"分片上传"),pn(e,n))}class gn{constructor(e,t,i={}){this.normal=e||null,this.chunk=t||null,this.mode=["auto","normal","chunk"].includes(i.mode)?i.mode:"auto",this.chunkThreshold=Math.max(0,Number(i.chunkThreshold??5*1024*1024)||0),i.mode==="chunk"&&!this.chunk&&console.warn('[KEditor] upload.mode = "chunk" 但未配置 chunkUploader,已回退为普通上传')}pick(e){return this.chunk?this.normal?this.mode==="normal"?"normal":this.mode==="chunk"||((e==null?void 0:e.size)||0)>=this.chunkThreshold?"chunk":"normal":"chunk":"normal"}uploaderFor(e){return this.pick(e)==="chunk"?this.chunk:this.normal}async upload(e,t={}){const i=this.uploaderFor(e);if(!i)throw new Error("[KEditor] 未配置上传接口:请设置 uploader(普通上传)或 chunkUploader(分片上传)");return{...await i.upload(e,t),mode:i.mode}}destroy(){var e,t;(e=this.normal)==null||e.destroy(),(t=this.chunk)==null||t.destroy()}}function zr(n={}){const e=n.upload||{},t=fn(n.uploader,e),i=n.chunkUploader?mn(n.chunkUploader,e):null;return{normal:t,chunk:i,pipeline:new gn(t,i,e)}}function kn(n){const e=[],t=[];for(const i of n)($t(i)?e:t).push(i);return{docs:e,media:t}}async function bn(n,e){for(const t of e)await n.importMarkdown(t);return e.length}function Tr(n){n.root.addEventListener("paste",async e=>{if(n.readOnly||!n.options.paste.enabled)return;const t=e.clipboardData;if(!t)return;e.preventDefault();const i=Ar(t);if(i.length){const{docs:s,media:a}=kn(i);if(s.length&&await bn(n,s),!a.length)return;n.options.paste.uploadFiles?(await n.media.addFiles(a),n.toast.show(`已上传 ${a.length} 个文件`)):n.toast.warn("当前配置不允许粘贴上传文件");return}const r=t.getData("text/html"),o=t.getData("text/plain");if(r&&n.options.paste.clean){let s=St(r)?Et(r):r;s=ae(s,{allowEmpty:!0}),n.options.paste.localizeImages&&(s=await Hr(n,s)),n.commands.insertHTML(s,{clean:!1}),St(r)&&n.toast.show("已清理 Word/WPS 格式")}else if(o){const s=o.split(/\r?\n/).map(a=>`<p>${q(a)||"<br>"}</p>`).join("");n.commands.insertHTML(s,{clean:!1})}})}function Ar(n){var t,i;const e=[];if((t=n.items)!=null&&t.length){for(const r of n.items)if(r.kind==="file"){const o=r.getAsFile();o&&e.push(xn(o,e.length))}}return!e.length&&((i=n.files)!=null&&i.length)&&e.push(...Array.from(n.files).map((r,o)=>xn(r,o))),e}function xn(n,e){if(n.name&&n.name!=="image.png")return n;const t=(n.type.split("/")[1]||"png").replace("jpeg","jpg").replace("+xml",""),i=new Date().toISOString().slice(11,19).replace(/:/g,"");return new File([n],`pasted-${i}-${e}.${t}`,{type:n.type,lastModified:n.lastModified})}function $r(n){const e=n.root;let t=0;const i=r=>{var o;return Array.from(((o=r.dataTransfer)==null?void 0:o.types)||[]).includes("Files")};e.addEventListener("dragenter",r=>{!i(r)||n.readOnly||(r.preventDefault(),t+=1,n.el.classList.add("ke-is-dragover"))}),e.addEventListener("dragover",r=>{!i(r)||n.readOnly||(r.preventDefault(),r.dataTransfer.dropEffect="copy")}),e.addEventListener("dragleave",r=>{i(r)&&(t=Math.max(0,t-1),t===0&&n.el.classList.remove("ke-is-dragover"))}),e.addEventListener("drop",async r=>{if(!i(r)||n.readOnly)return;r.preventDefault(),t=0,n.el.classList.remove("ke-is-dragover"),Rr(n,r);const o=[...r.dataTransfer.files||[]];if(!o.length)return;const{docs:s,media:a}=kn(o);if(s.length&&await bn(n,s),a.length&&n.options.paste.uploadFiles){const l=await n.media.addFiles(a);l&&n.toast.show(`已上传 ${l} 个文件`)}})}function Rr(n,e){let t=null;if(document.caretRangeFromPoint)t=document.caretRangeFromPoint(e.clientX,e.clientY);else if(document.caretPositionFromPoint){const i=document.caretPositionFromPoint(e.clientX,e.clientY);i&&(t=document.createRange(),t.setStart(i.offsetNode,i.offset),t.collapse(!0))}if(t&&n.root.contains(t.commonAncestorContainer)){const i=window.getSelection();i.removeAllRanges(),i.addRange(t)}else n.focus()}async function Hr(n,e){const t=new DOMParser().parseFromString(`<div>${e}</div>`,"text/html"),i=[...t.body.querySelectorAll("img")].filter(r=>/^https?:/i.test(r.getAttribute("src")||""));for(const r of i)try{const o=await fetch(r.src,{mode:"cors"});if(!o.ok)continue;const s=await o.blob(),a=new File([s],r.alt||`remote-${Date.now()}.jpg`,{type:s.type||"image/jpeg"}),l=await n.media.upload(a,"image");r.remove(),l!=null&&l.url&&n.toast.show("外链图片已本地化")}catch{}return t.body.innerHTML.trim()}function Br(n){const e=Ke(n.languages),t=X(n.defaultLanguage);return e.some(i=>i.value===t)?t:e[0].value}const yn=1024,Le=1024*yn,ne={value:"",placeholder:"开始撰写内容,支持拖拽 / 粘贴图片与视频…",height:0,minHeight:320,code:{languages:[],defaultLanguage:"plaintext",highlight:!0},markdown:{insertMode:"replace",maxSize:5*Le,gfm:!0,breaks:!1,linkTarget:!1,frontMatter:!0},primaryColor:"#07c160",paperWidth:677,paperMode:"fluid",paperGap:24,paperMaxWidth:0,toolbar:je,customButtons:[],hideToolbar:!1,hideStatusbar:!1,readOnly:!1,autofocus:!1,maxLength:0,wordCount:!0,sanitize:!0,historyLimit:60,uploader:"mock",chunkUploader:"mock",upload:{mode:"auto",chunkThreshold:5*Le,chunkSize:Le,concurrency:3,retries:2,fingerprint:"fast"},image:{compress:{maxWidth:1440,quality:.85,minSize:300*yn}},maxImageSize:20*Le,maxVideoSize:512*Le,imageAccept:"image/png,image/jpeg,image/gif,image/webp,image/bmp,image/svg+xml,image/avif",videoAccept:"video/mp4,video/quicktime,video/webm,video/x-m4v,video/ogg",paste:{enabled:!0,clean:!0,uploadFiles:!0,localizeImages:!1},onChange:null,onReady:null,onError:null,onUpload:null,beforeUpload:null,toolbarFloat:!1};let Nr=0;class Me{constructor(e,t={}){Cn(),this.options=jr(t),this.id=`ke-${Nr+=1}`,this.lastCodeLang=Br(this.options.code),this.el=_r(e,this.id),this.el.__keditor__=this;const i=this.el.innerHTML;this.emitters=new Map,this.domListeners=[],this.destroyed=!1,this.sourceMode=!1,this.previewMode=!1,this.fullscreen=!1,this.readOnly=!1,this.buildDOM(),this.toast=new Wi,this.popover=new zi(this.el),this.commands=new dr(this);const r=zr(this.options);this.uploaders={normal:r.normal,chunk:r.chunk},this.uploader=r.pipeline,this.media=Or(this),this.history=new pr(this.root,{limit:this.options.historyLimit}),this.toolbar=new ar(this,this.options.toolbar,this.options.customButtons),this.source=new qi(this),this.previewPanel=new Ui(this),this.bubble=new Gi(this),this.mainEl.append(this.source.el,this.previewPanel.el),this.applyTheme(),this.setContent(this.options.value||i,{sanitize:this.options.sanitize,silent:!0}),this.bindEvents(),this.setReadOnly(this.options.readOnly),this.refresh(),this.refreshStatus(),this.history.reset(this.root.innerHTML),queueMicrotask(()=>{var o,s;this.destroyed||(this.emit("ready",{editor:this}),(s=(o=this.options).onReady)==null||s.call(o,this),this.options.autofocus&&this.focus())})}buildDOM(){this.el.classList.add("ke"),this.el.id=this.el.id||this.id,this.el.innerHTML="",this.tbEl=d("div.ke-tb",{role:"toolbar","aria-label":"编辑器工具栏"}),this.scrollEl=d("div.ke-scroll"),this.paperEl=d("div.ke-paper"),this.root=d("div.ke-content",{contenteditable:this.readOnly?"false":"true",role:"textbox","aria-multiline":"true",spellcheck:"false","data-placeholder":this.options.placeholder,"data-ke-root":""}),this.root.style.minHeight=`${this.options.minHeight}px`,this.paperEl.appendChild(this.root),this.scrollEl.appendChild(this.paperEl),this.mainEl=d("div.ke-main",{},[this.scrollEl]),this.statusEl=Fr(this),this.dropzoneEl=d("div.ke-dropzone",{},[d("span",{text:"松开即可上传(分片传输)"})]),this.options.hideToolbar||this.el.appendChild(this.tbEl),this.el.appendChild(this.mainEl),this.options.hideStatusbar||this.el.appendChild(this.statusEl),this.el.appendChild(this.dropzoneEl),this.paperEl.style.setProperty("--ke-min-height",`${this.options.minHeight}px`),this.applyHeight(),this.applyPaper()}applyHeight(){const e=ze(this.options.height);return e>0?(this.scrollEl.style.height=`${e}px`,this.scrollEl.style.maxHeight=`${e}px`):(this.scrollEl.style.height="",this.scrollEl.style.maxHeight=""),this.el.classList.toggle("ke-is-auto",e===0),e}setHeight(e){return this.options.height=ze(e),this.applyHeight()}heightOptions(){return{height:ze(this.options.height),auto:ze(this.options.height)===0}}applyPaper(){const{paperWidth:e,paperMode:t,paperGap:i,paperMaxWidth:r}=this.options;this.paperEl.style.setProperty("--ke-paper",`${e}px`),this.paperEl.style.setProperty("--ke-paper-gap",`${i}px`),r>0?this.paperEl.style.setProperty("--ke-paper-max",`${r}px`):this.paperEl.style.removeProperty("--ke-paper-max"),this.paperEl.classList.toggle("ke-is-fluid",t!=="fixed")}setPaper(e={}){return e.width!==void 0&&(this.options.paperWidth=pe(Number(e.width)||0,200,8e3)),e.mode!==void 0&&(this.options.paperMode=e.mode==="fixed"?"fixed":"fluid"),e.gap!==void 0&&(this.options.paperGap=pe(Number(e.gap)||0,0,600)),e.maxWidth!==void 0&&(this.options.paperMaxWidth=Math.max(0,Number(e.maxWidth)||0)),this.applyPaper(),{...this.paperOptions()}}paperOptions(){const{paperWidth:e,paperMode:t,paperGap:i,paperMaxWidth:r}=this.options;return{width:e,mode:t,gap:i,maxWidth:r}}applyTheme(){this.options.primaryColor&&this.el.style.setProperty("--ke-primary",this.options.primaryColor)}bindEvents(){const e=Sn(()=>this.emitChange(),160);this.bind(this.root,"input",t=>{this.history.snapshot(),this.refreshStatus(),this.togglePlaceholder(),this.queueCodeHighlight(t),e(),this.enforceMaxLength()}),this.bind(this.root,"compositionstart",()=>{this.composing=!0}),this.bind(this.root,"compositionend",t=>{this.composing=!1,this.queueCodeHighlight(t)}),this.bind(this.root,"keydown",t=>this.handleKeydown(t)),this.bind(this.root,"blur",()=>{this.history.flush(),this.el.classList.remove("ke-is-focus"),this.emit("blur")}),this.bind(this.root,"focus",()=>{this.el.classList.add("ke-is-focus"),this.emit("focus")}),this.bind(this.root,"click",t=>this.handleContentClick(t)),this.bind(this.root,"dblclick",t=>{const i=t.target.closest("img");i&&this.root.contains(i)&&Oe(i.src)}),Tr(this),$r(this),this.selectionHandler=()=>{!this.root.contains(document.activeElement)&&document.activeElement!==this.root||(this.refresh(),this.syncBubble())},document.addEventListener("selectionchange",this.selectionHandler),this.scrollHandler=()=>this.bubble.position(),this.bind(this.scrollEl,"scroll",this.scrollHandler),window.addEventListener("resize",this.scrollHandler)}bind(e,t,i){return e.addEventListener(t,i),this.domListeners.push({node:e,type:t,handler:i}),i}handleKeydown(e){const t=e.metaKey||e.ctrlKey,i=e.key.toLowerCase();if(t&&i==="z"){e.preventDefault(),e.shiftKey?this.redo():this.undo();return}if(t&&i==="y"){e.preventDefault(),this.redo();return}if(t&&["b","i","u"].includes(i)){e.preventDefault(),this.commands.toggleMark({b:"bold",i:"italic",u:"underline"}[i]),this.refresh();return}if(t&&e.shiftKey&&i==="k"){e.preventDefault(),this.toggleSource();return}if(t&&i==="k"){e.preventDefault(),this.toolbar.openLink();return}if(t&&i==="s"){e.preventDefault(),this.emit("save",{html:this.getHTML()});return}if(e.key==="Escape"){this.popover.close(),this.bubble.hide(),this.previewMode&&this.closePreview();return}(e.key==="Backspace"||e.key==="Delete")&&this.bubble.node&&(e.preventDefault(),this.bubble.remove())}handleContentClick(e){const t=e.target.closest("[data-k-media]");if(t&&this.root.contains(t)){this.selectMedia(t);return}this.clearMediaSelection(),this.bubble.hide()}selectMedia(e){this.clearMediaSelection(),e.classList.add("ke-is-selected-media"),this.bubble.show(e),this.refreshStatus()}clearMediaSelection(){this.root.querySelectorAll(".ke-is-selected-media").forEach(e=>e.classList.remove("ke-is-selected-media")),this.bubble.hide()}syncBubble(){!this.bubble.node||!this.root.contains(this.bubble.node)?this.bubble.hide():this.bubble.position()}getState(){var a,l,c;const e=P(this.root),t=se((e==null?void 0:e.commonAncestorContainer)||this.root,this.root),i=e?Dr(e,this.root):null,r=(a=this.bubble)==null?void 0:a.node,o=r&&((l=r.dataset)==null?void 0:l.kMedia)==="image"?r.querySelector("img"):null,s=o?Ue(o):qr(e,t);return{bold:this.queryState("bold"),italic:this.queryState("italic"),underline:this.queryState("underline"),strikeThrough:this.queryState("strikeThrough"),ul:this.queryState("insertUnorderedList"),ol:this.queryState("insertOrderedList"),align:s,block:((c=t==null?void 0:t.tagName)==null?void 0:c.toLowerCase())||"p",fontSize:this.commands.currentFontSize(),linkUrl:i?i.getAttribute("href"):"",linkTarget:i?i.getAttribute("target")==="_blank":!1,selectionText:e?e.toString():"",canUndo:this.history.canUndo(),canRedo:this.history.canRedo(),source:this.sourceMode,preview:this.previewMode,fullscreen:this.fullscreen,readOnly:this.readOnly,inCode:!!ge(this.root)}}queryState(e){var t;if(!this.root.contains(((t=window.getSelection())==null?void 0:t.anchorNode)||null))return!1;try{return document.queryCommandState(e)}catch{return!1}}refresh(){if(!this.destroyed)try{this.toolbar.refresh(this.getState())}catch{}}refreshStatus(){const e=this.statusApi;e&&e.update(this.counts())}counts(){const e=Lt(this.root.innerHTML);return{chars:e.replace(/\s/g,"").length,words:Ur(e),images:this.root.querySelectorAll("img").length,videos:this.root.querySelectorAll('[data-k-media="video"] video, video').length,uploading:this.media?this.media.tasks.size:0}}togglePlaceholder(){const e=!this.root.textContent.trim()&&!this.root.querySelector("img,video,hr,table,iframe");this.root.classList.toggle("ke-is-empty",e)}enforceMaxLength(){var i,r;const e=this.options.maxLength;if(!e)return;const{chars:t}=this.counts();t>e?(this.toast.warn(`已超过建议字数 ${e}`),(i=this.statusEl)==null||i.classList.add("ke-is-over")):(r=this.statusEl)==null||r.classList.remove("ke-is-over")}getHTML({clean:e=!0}={}){const t=this.root.innerHTML;return e===!1?t:wn(t,{keepHighlight:e==="preview"})}getText(){return Lt(this.root.innerHTML)}getJSON(){return{html:this.getHTML(),text:this.getText(),counts:this.counts()}}setContent(e,{sanitize:t=this.options.sanitize,silent:i=!1}={}){const r=ae(e||"<p><br></p>",{allowEmpty:!0});return this.root.innerHTML=r||"<p><br></p>",this.highlightCode(),this.afterEdit({silent:i}),i||this.history.snapshot(!0),this.togglePlaceholder(),this}appendHTML(e){const t=document.createRange();t.selectNodeContents(this.root),t.collapse(!1);const i=window.getSelection();return i.removeAllRanges(),i.addRange(t),this.commands.insertHTML(e),this}clear(){return this.media.cancelAll(),this.setContent("<p><br></p>"),this.focus(),this}afterEdit({silent:e=!1}={}){this.history.snapshot(),this.refreshStatus(),this.togglePlaceholder(),e||this.emitChange()}commitHistory(){this.history.snapshot(!0),this.refreshStatus(),this.emitChange()}emitChange(){var e,t;this.emit("change",{html:this.getHTML(),text:this.getText()}),(t=(e=this.options).onChange)==null||t.call(e,this.getHTML(),this)}focus(){if(this.readOnly||this.sourceMode)return this.sourceMode&&this.source.code.focus(),this;this.root.focus();const e=window.getSelection();if(!e||e.rangeCount===0||!this.root.contains(e.anchorNode)){const t=document.createRange(),i=this.root.firstElementChild||this.root;t.selectNodeContents(i),t.collapse(!1),e.removeAllRanges(),e.addRange(t)}return this}blur(){return this.root.blur(),this}saveSelection(){const e=P(this.root);return this.savedRange=e?e.cloneRange():null,this}restoreSelection(){this.root.focus();const e=window.getSelection();return this.savedRange&&this.root.contains(this.savedRange.startContainer)&&this.root.contains(this.savedRange.endContainer)?(e.removeAllRanges(),e.addRange(this.savedRange),this):this.focus()}setReadOnly(e){return this.readOnly=!!e,this.root.setAttribute("contenteditable",this.readOnly?"false":"true"),this.el.classList.toggle("ke-is-readonly",this.readOnly),this.refresh(),this}undo(){return this.history.flush(),this.history.undo()?(this.afterEdit({silent:!1}),this.refresh(),this):(this.toast.show("没有可撤销的操作"),this)}redo(){return this.history.redo()?(this.afterEdit(),this.refresh(),this):(this.toast.show("没有可重做的操作"),this)}codeLanguages(){return Ke(this.options.code.languages)}highlightCode(){return At(this.root,{highlight:this.options.code.highlight!==!1})}insertCode(e="",t){return this.commands.insertCodeBlock(e,t)}setCodeLanguage(e,t){return this.commands.setCodeLanguage(e,t)}getCodeLanguage(){return this.commands.currentCodeLang()}queueCodeHighlight(e){if(e!=null&&e.isComposing||this.composing)return;const t=ge(this.root);t&&(clearTimeout(this.codeTimer),this.codeTimer=setTimeout(()=>{this.codeTimer=null,this.destroyed||He(t,{caret:!0})},140))}markdownOptions(){const{insertMode:e,maxSize:t}=this.options.markdown;return{insertMode:ke(e),maxSize:t,auto:e==="replace"}}async importMarkdown(e,{mode:t=this.options.markdown.insertMode,silent:i=!1}={}){if(this.readOnly)return this.toast.warn("只读模式不能导入内容"),{ok:!1,reason:"readonly"};const r=ke(t);let o="",s="";try{if(typeof e=="string")o=e;else if(e&&typeof e.arrayBuffer=="function"){s=e.name||"";const c=this.options.markdown.maxSize;if(c&&e.size>c)throw new Error(`${s||"文件"} 超出大小限制(${W(c)})`);o=await Xe(e)}else if(e&&typeof e.content=="string")o=e.content,s=e.name||"";else throw new Error("导入内容必须是 Markdown 文本或文件");const a=et(o,this.options.markdown);if(!a.trim())throw new Error("没有解析到可用内容");r==="replace"?this.setContent(a):(r==="append"&&this.moveCaretToEnd(),this.commands.insertHTML(a),this.highlightCode()),this.focus(),this.history.snapshot(!0);const l=tt(a);return i||this.toast.show(`已导入${s?` ${s}`:" Markdown"}(${l.paragraphs+l.headings} 个段落)`),this.emit("markdownimport",{mode:r,name:s,summary:l,chars:o.length}),{ok:!0,html:a,summary:l,mode:r,chars:o.length,name:s}}catch(a){return this.reportError("markdown",a),{ok:!1,reason:"error",error:a,name:s}}}setMarkdown(e,t={}){return this.importMarkdown(e,{mode:"replace",...t})}insertMarkdown(e,t={}){return this.importMarkdown(e,{mode:"cursor",...t})}appendMarkdown(e,t={}){return this.importMarkdown(e,{mode:"append",...t})}moveCaretToEnd(){const e=document.createRange();e.selectNodeContents(this.root),e.collapse(!1);const t=window.getSelection();return t.removeAllRanges(),t.addRange(e),this}upload(e,t=this.media.kindOf(e)){if(!t)throw new Error("[KEditor] 不支持的文件类型");return this.media.upload(e,t)}insertImage(e,t=""){return this.media.insertImageUrl(e,t)}insertVideo(e,t="视频"){return this.media.insertVideoUrl(e,t)}cancelUploads(){return this.media.cancelAll(),this}addButton(e,t){return this.toolbar.addButton(e,t)}moveButton(e,t){return this.toolbar.moveButton(e,t)}removeButton(e){return this.toolbar.removeButton(e)}setButtonOptions(e,t){return this.toolbar.setButtonOptions(e,t)}getButtonValue(e){return this.toolbar.getButtonValue(e)}setButtonValue(e,t){return this.toolbar.setButtonValue(e,t)}reportError(e,t){var o,s,a;const i=t&&t.message?t.message:String(t),r={type:e,error:t instanceof Error?t:new Error(i),message:i};return(o=this.toast)==null||o.error(i),this.emit("error",r),(a=(s=this.options).onError)==null||a.call(s,r),this}toggleSource(){return this.sourceMode?this.exitSource():this.enterSource(),this.sourceMode}enterSource(){this.sourceMode||(this.history.flush(),this.sourceMode=!0,this.el.classList.add("ke-is-source"),this.clearMediaSelection(),this.source.show(this.getHTML({clean:!0})),this.previewPanel.hide(),this.previewMode=!1,this.refresh(),this.emit("sourcechange",{mode:"source"}))}exitSource(){this.sourceMode&&(this.source.apply({silent:!0}),this.sourceMode=!1,this.el.classList.remove("ke-is-source"),this.source.hide(),this.focus(),this.refresh(),this.emit("sourcechange",{mode:"visual"}))}togglePreview(){return this.previewMode?this.closePreview():this.openPreview(),this.previewMode}openPreview(){this.previewMode=!0,this.previewPanel.show(Wr(this.getHTML({clean:"preview"}))),this.refresh()}closePreview(){this.previewMode=!1,this.previewPanel.hide(),this.refresh()}toggleFullscreen(){return this.fullscreen=!this.fullscreen,this.el.classList.toggle("ke-is-fullscreen",this.fullscreen),document.body.style.overflow=this.fullscreen?"hidden":"",this.refresh(),this.fullscreen}on(e,t){return this.addListener(e,t)}off(e,t){return this.removeListener(e,t)}emit(e,t={}){var r,o,s,a;const i=this.emitters.get(e)||[];for(const l of i)try{l(t)}catch(c){(o=(r=this.options).onError)==null||o.call(r,c)}return e.startsWith("upload")&&((a=(s=this.options).onUpload)==null||a.call(s,{stage:e,...t})),this}addListener(e,t){return this.emitters.has(e)||this.emitters.set(e,[]),this.emitters.get(e).push(t),()=>this.removeListener(e,t)}removeListener(e,t){const i=this.emitters.get(e)||[],r=i.indexOf(t);return r>=0&&i.splice(r,1),this}get element(){return this.root}get editorElement(){return this.el}destroy(){var e;if(!this.destroyed){this.destroyed=!0,this.media.destroy(),(e=this.uploader)==null||e.destroy(),clearTimeout(this.codeTimer),this.history.destroy(),this.popover.destroy(),this.source.destroy(),this.previewPanel.destroy(),this.bubble.destroy(),this.toolbar.destroy(),this.toast.destroy();for(const{node:t,type:i,handler:r}of this.domListeners)t.removeEventListener(i,r);document.removeEventListener("selectionchange",this.selectionHandler),this.scrollEl.removeEventListener("scroll",this.scrollHandler),window.removeEventListener("resize",this.scrollHandler),this.fullscreen&&(document.body.style.overflow=""),this.el.__keditor__===this&&(this.el.__keditor__=null),this.el.innerHTML="",this.el.classList.remove("ke","ke-is-fullscreen","ke-is-readonly"),this.el.removeAttribute("style"),this.emitters.clear()}}static create(e,t){return new Me(e,t)}}function Or(n){const e=new gr(n),t=e.upload.bind(e);return e.upload=async(i,r)=>{const o=n.options.beforeUpload;let s=i;return o&&(s=await o(i,r),s===!1)?null:t(s,r)},e.replaceNode=async(i,r)=>{const o=i.dataset.kMedia==="video"?"video":"image",s=document.createRange();s.setStartBefore(i),s.collapse(!0);const a=window.getSelection();a.removeAllRanges(),a.addRange(s);const l=await e.upload(r,o);return i.remove(),n.commitHistory(),l},e}function _r(n,e){if(typeof n=="string"){const t=document.querySelector(n);if(!t)throw new Error(`[KEditor] 找不到挂载节点:${n}`);return t}if(n instanceof HTMLElement)return n;if((n==null?void 0:n.$el)instanceof HTMLElement)return n.$el;throw new Error(`[KEditor] 无效的挂载目标(${typeof n})`)}function ze(n){if(n===""||n===null||n===void 0||n==="auto")return 0;const e=Number(n);return!Number.isFinite(e)||e<=0?0:pe(Math.round(e),0,4e3)}function jr(n){var r;const e={...ne,...n};e.image={...ne.image,...n.image||{}},e.paste={...ne.paste,...n.paste||{}},e.upload={...ne.upload,...n.upload||{}};const t=n.uploader!==void 0,i=n.chunkUploader!==void 0;return t&&!i&&(e.chunkUploader=null),!t&&i&&((r=n.upload)==null?void 0:r.mode)===void 0&&(e.upload.mode="chunk"),e.code={...ne.code,...n.code||{}},e.markdown={...ne.markdown,...n.markdown||{}},e.markdown.insertMode=ke(e.markdown.insertMode),e.markdown.maxSize=Math.max(0,Number(e.markdown.maxSize)||0),e.customButtons=Xt(n.customButtons),Array.isArray(n.toolbar)&&(e.toolbar=n.toolbar),n.toolbar===!1&&(e.toolbar=[]),n.toolbar===!0&&(e.toolbar=je),e.customButtons.length&&n.toolbar!==!1&&(e.toolbar=Pr(e.toolbar,e.customButtons)),e.height=ze(e.height),e.paperWidth=pe(Number(e.paperWidth)||ne.paperWidth,200,8e3),e.paperMode=e.paperMode==="fixed"?"fixed":"fluid",e.paperGap=Number.isFinite(Number(e.paperGap))?pe(Number(e.paperGap),0,600):ne.paperGap,e.paperMaxWidth=Math.max(0,Number(e.paperMaxWidth)||0),e}const Ir=n=>n!=="|"&&n!==":tail";function Pr(n,e){const t=[...n],i=[];for(const r of e)if(!t.includes(r.name)){if(r.position==null){i.push(r.name);continue}t.splice(vn(t,r.position),0,r.name)}return i.length&&t.splice(vn(t,null),0,"|",...i),t}function vn(n,e){const t=(()=>{const s=n.indexOf(":tail");return s<0?n.length:s})();if(e==null||e==="end")return t;if(e==="start")return 0;if(e==="tail")return n.length;if(typeof e=="number"){let s=0;for(let a=0;a<n.length;a++)if(Ir(n[a])){if(s===Math.max(0,Math.floor(e)))return a;s++}return t}const i=!!(e&&typeof e=="object"&&e.after),r=String(typeof e=="string"?e:(i?e.after:e.before)||""),o=n.indexOf(r);return o<0?t:i?o+1:o}function Fr(n){const e=d("b",{text:"0"}),t=d("b",{text:"0"}),i=d("b",{text:"0"}),r=d("b",{text:"0"}),o=d("span.ke-chip",{hidden:!0}),s=d("span.ke-status-hint",{text:"支持拖拽 / 粘贴上传,Ctrl/⌘ + S 保存"}),a=d("span.ke-status-tail"),l=d("div.ke-status",{},[d("span",{},["字数 ",e," · ",t," 词"]),d("span",{},["图片 ",i," · 视频 ",r]),o,s,a]),c={update:u=>{e.textContent=String(u.chars),t.textContent=String(u.words),i.textContent=String(u.images),r.textContent=String(u.videos),u.uploading>0?(o.hidden=!1,o.className="ke-chip ke-is-busy",o.textContent=`${u.uploading} 个上传进行中`):o.hidden=!0},addExtra:u=>a.appendChild(u)};return n.statusApi=c,n.options.wordCount||(l.style.display="none"),l}function Dr(n,e){var r;let t=n==null?void 0:n.commonAncestorContainer;if(!t||!e.contains(t))return null;t.nodeType===3&&(t=t.parentElement);const i=(r=t==null?void 0:t.closest)==null?void 0:r.call(t,"a");return i&&e.contains(i)?i:null}function qr(n,e){var r,o;const t=e||(n==null?void 0:n.commonAncestorContainer),i=[t,t==null?void 0:t.parentElement].filter(s=>s&&s.nodeType===1);for(const s of i){const a=(r=s.style)==null?void 0:r.textAlign;if(a)return a==="-webkit-justify"?"justify":a;const l=(o=s.getAttribute)==null?void 0:o.call(s,"align");if(l)return l}try{if(document.queryCommandState("justifyCenter"))return"center";if(document.queryCommandState("justifyRight"))return"right";if(document.queryCommandState("justifyFull"))return"justify"}catch{}return"left"}function Ur(n){const e=(n.match(/[\u4e00-\u9fa5\u3040-\u30ff]/g)||[]).length,t=(n.match(/[a-zA-Z0-9'’-]+/g)||[]).length;return e+t}function wn(n,{keepHighlight:e=!1}={}){const i=new DOMParser().parseFromString(`<div>${n}</div>`,"text/html").body.firstChild;return i.querySelectorAll("[contenteditable]").forEach(r=>r.removeAttribute("contenteditable")),i.querySelectorAll("[data-k-id]").forEach(r=>r.removeAttribute("data-k-id")),i.querySelectorAll("[data-k-state]").forEach(r=>r.removeAttribute("data-k-state")),i.querySelectorAll("[data-ke-marker]").forEach(r=>r.removeAttribute("data-ke-marker")),i.querySelectorAll("[data-placeholder]").forEach(r=>r.removeAttribute("data-placeholder")),i.querySelectorAll(".ke-is-selected-media").forEach(r=>r.classList.remove("ke-is-selected-media")),e||Un(i),i.querySelectorAll('[data-k-state="uploading"], [data-k-state="error"]').forEach(r=>r.remove()),i.innerHTML.trim()}function Wr(n){const t=new DOMParser().parseFromString(`<div>${n}</div>`,"text/html").body.firstChild;return t.querySelectorAll("[data-k-media]").forEach(i=>{i.removeAttribute("data-k-media"),i.removeAttribute("data-k-url")}),t.innerHTML}const Gr="1.0.8";function vt(n,e={}){return new Me(n,e)}const Kr=vt;function Vr(n,e={}){const t=typeof n=="string"?document.querySelector(n):n;return t!=null&&t.__keditor__&&t.__keditor__.destroy(),vt(t,e)}y.ChunkUploader=bt,y.DEFAULT_TOOLBAR=je,y.KEditor=Me,y.LANGUAGES=fe,y.MARKDOWN_ACCEPT=Rt,y.SimpleUploader=Pe,y.UploadPipeline=gn,y.cleanWordHtml=Et,y.create=vt,y.createChunkUploader=mn,y.createSimpleUploader=fn,y.default=Me,y.defaults=ne,y.escapeHtml=q,y.exportHtml=wn,y.fastFingerprint=kt,y.formatHtml=ct,y.highlightCode=Ae,y.httpAdapter=yt,y.isCodeBlock=$e,y.isMarkdownFile=$t,y.isSafeUrl=re,y.languageLabel=_n,y.listLanguages=Ke,y.markdownSummary=tt,y.markdownToHtml=et,y.maybeCompress=sn,y.mockAdapter=xt,y.mount=Kr,y.normalizeCustomButtons=Xt,y.normalizeInsertMode=ke,y.normalizeItems=Ee,y.normalizeLang=X,y.normalizePosition=ut,y.readMarkdownFile=Xe,y.replace=Vr,y.sanitizeHtml=ae,y.simpleAdapter=cn,y.strongFingerprint=an,y.version=Gr,Object.defineProperties(y,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});
|