kyle-editor 1.0.8 → 1.0.10

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.
@@ -221,13 +221,13 @@
221
221
  .ke-md-panel {
222
222
  width: 372px; max-width: calc(100vw - 24px);
223
223
  display: flex; flex-direction: column; padding-bottom: 0;
224
- max-height: var(--ke-pop-max, 560px);
224
+ max-height: var(--ke-pop-max, 480px);
225
225
  }
226
226
  .ke-md-panel .ke-panel-head, .ke-md-panel .ke-tabs { flex: none; }
227
227
  .ke-md-panel .ke-tabs { margin-bottom: 0; }
228
228
  /* 中间区滚动、底部按钮常驻:窗口再矮也能点到「导入到正文」 */
229
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; }
230
+ .ke-md-panel .ke-panel-foot { flex: none; margin: 10px 0 30px; }
231
231
  .ke-md-text {
232
232
  width: 100%; min-height: 118px; max-height: 190px; padding: 10px 11px; border: 1px solid var(--ke-line);
233
233
  border-radius: 8px; background: #fbfcfd; color: #1f2329; font-size: 12.5px; line-height: 1.7; resize: vertical;
@@ -583,4 +583,4 @@ ${n.children.map(i=>ot(i,e,t)).join(`
583
583
  ${r}
584
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
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,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}function xe(n){return String(n||"").replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}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&&lt.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,"&quot;")}"`);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"}})});
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,"&quot;")}"`);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():P(this.root)||this.restoreSelection(),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.10";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"}})});