kyle-editor 1.0.6 → 1.0.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +0 -8
- package/dist/keditor.cjs +1 -1
- package/dist/keditor.es.js +1 -1
- package/dist/keditor.umd.js +1 -1
- package/dist/keditor.umd.min.js +1 -1
- package/package.json +1 -3
- package/docs/api.md +0 -365
- package/docs/index.md +0 -8
- package/docs/integration.md +0 -347
- package/docs/upload-adapter.md +0 -186
- package/imgs/img.png +0 -0
- package/imgs/img_1.png +0 -0
- package/imgs/img_2.png +0 -0
- package/imgs/img_3.png +0 -0
package/README.md
CHANGED
|
@@ -6,14 +6,6 @@
|
|
|
6
6
|
- 版式:677px 正文版心、17px/1.75 行距,与公众号观感一致;**宽屏下版心自动生长**,两侧留白恒定,不会留出一大块空白
|
|
7
7
|
- 安全:标签/属性白名单净化,拦截 `on*`、`javascript:`、`script/iframe`
|
|
8
8
|
|
|
9
|
-

|
|
10
|
-

|
|
11
|
-

|
|
12
|
-

|
|
13
|
-
|
|
14
|
-
## 文档
|
|
15
|
-
* [快速开始](docs/index.md)
|
|
16
|
-
|
|
17
9
|
## 功能
|
|
18
10
|
|
|
19
11
|
| 分类 | 能力 |
|
package/dist/keditor.cjs
CHANGED
package/dist/keditor.es.js
CHANGED
package/dist/keditor.umd.js
CHANGED
package/dist/keditor.umd.min.js
CHANGED
|
@@ -480,4 +480,4 @@
|
|
|
480
480
|
`)}function gt(o){return o.replace(/\n\s+/g," ").replace(/\s{2,}/g," ").trim()}function bt(o){const e=[...o.attributes].map(t=>`${t.name}="${(t.value||"").replace(/"/g,""")}"`);return`<${o.tagName.toLowerCase()}${e.length?` ${e.join(" ")}`:""}>`}class xt{constructor(e){this.editor=e,this.open=!1,this.el=l("div.ke-source",{hidden:!0},[l("div.ke-source-bar",{},[l("span.ke-source-title",{text:"HTML 源码"}),l("span.ke-source-tip",{text:"可直接编辑,点击「应用」或退出源码模式即生效"}),l("span.ke-source-tail",{},[l("button.ke-btn",{type:"button",title:"格式化",html:M("format")+"<span>格式化</span>",onclick:()=>this.format()}),l("button.ke-btn",{type:"button",title:"复制全部",html:M("copy")+"<span>复制</span>",onclick:()=>this.copy()}),l("button.ke-btn",{type:"button",title:"应用修改",html:M("check")+"<span>应用</span>",onclick:()=>this.apply()}),l("button.ke-btn",{type:"button",title:"退出源码模式",html:M("close"),onclick:()=>e.exitSource()})])]),(this.code=l("pre.ke-source-code",{contenteditable:"true",spellcheck:"false",autocapitalize:"off",autocomplete:"off",wrap:"off"}),this.code.addEventListener("keydown",t=>{t.key==="Tab"&&(t.preventDefault(),document.execCommand("insertText",!1," ")),(t.ctrlKey||t.metaKey)&&t.key.toLowerCase()==="s"&&(t.preventDefault(),this.apply()),t.stopPropagation()}),this.code)])}get value(){return this.code.textContent}set value(e){this.code.textContent=e,this.code.scrollTop=0}show(e){this.value=ae(e),this.el.hidden=!1,this.open=!0,this.editor.scrollEl.hidden=!0}hide(){this.el.hidden=!0,this.open=!1,this.editor.scrollEl.hidden=!1}format(){this.value=ae(this.value),this.editor.toast.show("已格式化")}async copy(){var t;const e=this.value;try{(t=navigator.clipboard)!=null&&t.writeText?await navigator.clipboard.writeText(e):(this.code.focus(),document.execCommand("selectAll"),document.execCommand("copy")),this.editor.toast.show("源码已复制到剪贴板")}catch{this.editor.toast.error("复制失败,请手动选择复制")}}apply({silent:e=!1}={}){const t=this.value;try{return this.editor.setContent(t,{sanitize:!0,silent:!1}),e||this.editor.toast.show("源码已应用"),!0}catch(i){return this.editor.toast.error(`源码解析失败:${i.message}`),!1}}destroy(){this.el.remove()}}const le=[{key:"mobile",label:"手机",width:375},{key:"pad",label:"平板",width:540},{key:"pc",label:"电脑",width:677}];class yt{constructor(e){this.editor=e,this.device="pc",this.el=l("div.ke-preview",{hidden:!0},[l("div.ke-preview-bar",{},[l("span",{text:"预览"}),l("span.ke-source-tip",{text:"仅用于查看排版效果,内容不可编辑"}),l("span.ke-status-tail",{},le.map(t=>l("button.ke-btn",{type:"button","data-k-device":t.key,text:t.label,onclick:()=>this.setDevice(t.key)})).concat([l("span.ke-tb-sep"),l("button.ke-btn",{type:"button",title:"关闭预览",html:M("close"),onclick:()=>e.closePreview()})]))]),(this.body=l("div.ke-preview-body",{},[l("div.ke-preview-frame",{style:{maxWidth:"677px"}},[l("div.ke-content.ke-preview-content")])]),this.frame=this.body.firstChild,this.content=this.frame.firstChild,this.body)])}setDevice(e){this.device=e;const t=le.find(i=>i.key===e)||le[2];this.frame.style.maxWidth=`${t.width}px`,this.frame.style.width=e==="mobile"?`${t.width}px`:"100%",this.el.querySelectorAll("[data-k-device]").forEach(i=>i.classList.toggle("ke-is-active",i.dataset.kDevice===e))}show(e){this.content.innerHTML=e,this.el.hidden=!1,this.setDevice(this.device)}hide(){this.el.hidden=!0,this.content.innerHTML=""}destroy(){this.el.remove()}}class vt{constructor(e=null){this.owner=e,this.el=null}show(e,t="",i=2600){if(typeof document>"u")return;this.el||(this.el=l("div.ke-toasts"),document.body.appendChild(this.el));const n=l(`span.ke-toast${t?`.ke-is-${t}`:""}`,{text:e});this.el.appendChild(n),setTimeout(()=>{n.style.opacity="0",n.style.transition="opacity .2s",setTimeout(()=>n.remove(),220)},i)}error(e){this.show(e,"error",3600)}warn(e){this.show(e,"warn",3e3)}ok(e){this.show(e,"ok",2200)}destroy(){this.el&&!this.el.childElementCount&&this.el.remove(),this.el=null}}function J(o,e=document){const t=l("div.ke-lightbox",{tabindex:"-1"},[l("img",{src:o,alt:""})]),i=()=>{t.remove(),document.removeEventListener("keydown",n)},n=r=>{r.key==="Escape"&&i()};return t.addEventListener("click",i),document.addEventListener("keydown",n),e.body.appendChild(t),i}class wt{constructor(e){this.editor=e,this.node=null,this.el=l("div.ke-bubble",{hidden:!0,contenteditable:"false"}),e.el.appendChild(this.el),this.el.addEventListener("mousedown",t=>t.preventDefault()),this.el.addEventListener("click",t=>this.onClick(t)),this.replaceInput=l("input",{type:"file",style:{display:"none"}}),this.replaceInput.addEventListener("change",()=>{var i;const t=(i=this.replaceInput.files)==null?void 0:i[0];this.replaceInput.value="",t&&this.node&&this.editor.media.replaceNode(this.node,t)}),e.el.appendChild(this.replaceInput),this.resizeEl=l("div.ke-img-resize",{hidden:!0,"aria-label":"拖动缩放图片",title:"拖动缩放图片",html:'<svg viewBox="0 0 10 10"><path d="M7 1 L9 3 M4 4 L6 6 M1 7 L3 9" stroke="currentColor" stroke-width="1.6" stroke-linecap="round"/></svg>'}),this.resizeTip=l("div.ke-img-resize-tip",{hidden:!0}),this.resizeEl.addEventListener("pointerdown",t=>this.onResizePointerDown(t)),e.el.appendChild(this.resizeEl),e.el.appendChild(this.resizeTip)}show(e){this.node=e;const t=e.dataset.kMedia==="video"?"video":"image";this.el.textContent="";const i=t==="image"?this.imageActions(e):this.videoActions(e);for(const n of i)n&&this.el.appendChild(n);this.el.hidden=!1,t==="image"&&this.attachResize(),this.position()}hide(){this.el.hidden=!0,this.detachResize(),this.node=null}attachResize(){var e;(e=this.node)!=null&&e.querySelector("img")&&(this.resizeEl.hidden=!1,this.positionHandle())}detachResize(){this.resizeEl.hidden=!0,this.resizeTip.hidden=!0}position(){if(!this.node||(this.positionHandle(),this.el.hidden))return;const e=this.editor.el.getBoundingClientRect(),t=this.node.getBoundingClientRect(),i=this.editor.scrollEl.getBoundingClientRect();if(!t.height&&!t.width)return this.hide();if(t.bottom<i.top||t.top>i.bottom)return this.hide();const n=this.el.getBoundingClientRect(),r=t.left-e.left+t.width/2,a=t.top-e.top<n.height+18,c=a?t.bottom-e.top+10:t.top-e.top-10;this.el.classList.toggle("ke-is-below",a);const d=n.width/2;this.el.style.left=`${Math.min(Math.max(r,d+8),Math.max(d+8,e.width-d-8))}px`,this.el.style.top=`${Math.max(6,c)}px`}positionHandle(){const e=this.node;if(!e||this.resizeEl.hidden)return;const t=e.querySelector("img");if(!t)return;const i=this.editor.el.getBoundingClientRect(),n=t.getBoundingClientRect();if(!n.width&&!n.height)return;const r=18,s=6;this.resizeEl.style.left=`${n.right-i.left-r-s}px`,this.resizeEl.style.top=`${n.bottom-i.top-r-s}px`}updateResizeTip(e){var n;if(this.resizeTip.hidden||!this.node)return;this.resizeTip.textContent=`${Math.round(e)}%`;const t=this.editor.el.getBoundingClientRect(),i=((n=this.node.querySelector("img"))==null?void 0:n.getBoundingClientRect())||this.node.getBoundingClientRect();this.resizeTip.style.left=`${i.left-t.left+i.width/2}px`,this.resizeTip.style.top=`${i.top-t.top-10}px`}onResizePointerDown(e){var d;if(e.button!=null&&e.button!==0)return;const t=(d=this.node)==null?void 0:d.querySelector("img");if(!t)return;e.preventDefault(),e.stopPropagation();const n=this.node.getBoundingClientRect().width,r=Ee(Et(t,n),15,100),s=e.clientX;this.el.hidden=!0,this.resizeTip.hidden=!1,this.updateResizeTip(r);try{this.resizeEl.setPointerCapture(e.pointerId)}catch{}const a=h=>{const p=h.clientX-s,u=n?p/n*100:0,k=Ee(Math.round(r+u),15,100);t.style.width=`${k}%`,t.style.maxWidth="100%",this.updateResizeTip(k),this.positionHandle()},c=()=>{this.resizeEl.removeEventListener("pointermove",a),this.resizeEl.removeEventListener("pointerup",c),this.resizeEl.removeEventListener("pointercancel",c),this.resizeTip.hidden=!0,this.editor.commitHistory(),this.editor.refreshStatus(),this.el.hidden=!1,this.position()};this.resizeEl.addEventListener("pointermove",a),this.resizeEl.addEventListener("pointerup",c),this.resizeEl.addEventListener("pointercancel",c)}imageActions(e){const t=e.querySelector("img"),i=oe(t),n=t&&parseFloat(getComputedStyle(t).borderRadius)>0,r=a=>{ne(t,a),this.editor.commitHistory(),this.position()},s=a=>{t.style.width=a,ne(t,oe(t)),this.editor.commitHistory(),this.position()};return[B("alignLeft","左对齐",()=>r("left"),i==="left"),B("alignCenter","居中",()=>r("center"),i==="center"),B("alignRight","右对齐",()=>r("right"),i==="right"),V(),_("30%","宽度 30%",()=>s("30%")),_("60%","宽度 60%",()=>s("60%")),_("100%","宽度 100%",()=>s("100%")),V(),B("rounded","圆角",()=>Ct(t,e),n),B("preview","查看大图",()=>St(t)),B("upload","替换图片",()=>this.pick("image")),V(),B("trash","删除",()=>this.remove())]}videoActions(){return[_("小","窄版",()=>this.setVideoWidth("60%")),_("大","宽版",()=>this.setVideoWidth("100%")),V(),B("upload","替换视频",()=>this.pick("video")),V(),B("trash","删除",()=>this.remove())]}pick(e){this.replaceInput.accept=e==="image"?this.editor.options.imageAccept:this.editor.options.videoAccept,this.replaceInput.click()}setVideoWidth(e){this.node&&(this.node.style.width=e,this.editor.commitHistory(),this.position())}remove(){if(!this.node)return;const e=this.editor.media.taskFromNode(this.node);if(e)this.editor.media.remove(e);else{const t=this.node.nextElementSibling;this.node.remove(),t&&this.editor.focus(),this.editor.commitHistory()}this.hide(),this.editor.refreshStatus()}onClick(){}destroy(){this.el.remove(),this.replaceInput.remove(),this.resizeEl.remove(),this.resizeTip.remove()}}function B(o,e,t,i=!1){const n=l("button",{type:"button",title:e,html:M(o)});return i&&n.classList.add("ke-is-active"),n.addEventListener("click",t),n}function _(o,e,t){const i=l("button",{type:"button",title:e,text:o});return i.addEventListener("click",t),i}const V=()=>l("span.ke-sep");function Ct(o,e){if(!o)return;const t=parseFloat(getComputedStyle(o).borderRadius)>0;o.style.borderRadius=t?"0":"10px",e.dispatchEvent(new Event("change",{bubbles:!0}))}function St(o){o&&J(o.src)}function Ee(o,e,t){return Math.min(t,Math.max(e,o))}function Et(o,e){var i,n;if(!e)return 100;const t=(n=(i=o==null?void 0:o.style)==null?void 0:i.width)==null?void 0:n.match(/^([\d.]+)%$/);return t?parseFloat(t[1]):o.getBoundingClientRect().width/e*100}const Lt=new Set(["a","abbr","b","blockquote","br","code","col","colgroup","dd","del","div","dl","dt","em","figcaption","figure","font","h1","h2","h3","h4","h5","h6","hr","i","img","ins","kbd","li","mark","ol","p","pre","s","samp","section","small","span","strong","sub","sup","table","tbody","td","tfoot","th","thead","tr","u","ul","video","source"]),Mt=new Set(["style","class"]),zt={A:["href","title","target","rel"],IMG:["src","alt","title","width","height"],VIDEO:["src","poster","controls","loop","muted","playsinline","preload","width","height"],SOURCE:["src","type"],FONT:["size","color"],TD:["colspan","rowspan"],TH:["colspan","rowspan"],OL:["start"],LI:["value"]},Tt=["data-k-","data-keditor-"],At=/^(?:https?:|mailto:|tel:|blob:|\/|#|\.{1,2}\/|[^:]*$)/i,Ht=/^data:image\/(?:png|jpe?g|gif|webp|svg\+xml);/i;function Y(o){if(!o)return!1;const e=String(o).trim().replace(/\s+/g,"");return/^(javascript|vbscript|file|about):/i.test(e)?!1:e.startsWith("data:")?Ht.test(e):At.test(e)}function Bt(o){const e=[];for(const t of String(o).split(";")){const i=t.indexOf(":");if(i<0)continue;const n=t.slice(0,i).trim().toLowerCase(),r=t.slice(i+1).trim();!n||!r||/^[a-z-]+$/.test(n)&&(n.startsWith("mso-")||n.startsWith("-mso-")||/expression|javascript:|behavior:|url\(\s*['"]?\s*(javascript|data):/i.test(r)||e.push(`${n}:${r}`))}return e.join(";")}function $t(o){return String(o).split(/\s+/).filter(e=>/^[\w-]+$/.test(e)&&!/^(script|javascript)/i.test(e)).join(" ")}function Rt(o,e,t){const i=e.toLowerCase();return i.startsWith("on")?!1:Mt.has(i)||Tt.some(r=>i.startsWith(r))?!0:(zt[o]||[]).includes(i)}function K(o,{allowEmpty:e=!1}={}){if(!o)return e?"":"<p><br></p>";const i=new DOMParser().parseFromString(`<div>${o}</div>`,"text/html").body.firstChild;Le(i);const n=i.innerHTML.trim();return!n&&!e?"<p><br></p>":n}function Le(o){const e=Array.from(o.childNodes);for(const t of e){if(t.nodeType===8){t.remove();continue}if(t.nodeType===3)continue;if(t.nodeType!==1){t.remove();continue}const i=t.tagName;if(!Lt.has(i.toLowerCase())){if(i==="SCRIPT"||i==="STYLE"||i==="IFRAME"||i==="OBJECT"||i==="EMBED"||i==="FORM"||i==="LINK"||i==="META"){t.remove();continue}const n=t.parentNode;for(;t.firstChild;)n.insertBefore(t.firstChild,t);n.removeChild(t);continue}for(const n of Array.from(t.attributes)){if(!Rt(i,n.name,n.value)){t.removeAttribute(n.name);continue}const r=n.name.toLowerCase();if(r==="style")t.setAttribute("style",Bt(n.value));else if(r==="class"){const s=$t(n.value);s?t.setAttribute("class",s):t.removeAttribute("class")}else(r==="href"||r==="src"||r==="poster")&&(Y(n.value)||t.removeAttribute(n.name))}i==="A"&&t.getAttribute("target")==="_blank"&&t.setAttribute("rel","noopener noreferrer"),(t.getAttribute("href")===""||!t.getAttribute("href"))&&i==="A"&&t.removeAttribute("href"),Le(t)}}const Ot={1:10,2:13,3:16,4:18,5:24,6:32,7:48};function Me(o){return/urn:schemas-microsoft-com|class=["']?Mso|ProgID|w:val=/i.test(o)}function ze(o){const e=new DOMParser().parseFromString(`<div>${o}</div>`,"text/html"),t=e.body.firstChild;return t.querySelectorAll("*").forEach(i=>{const n=i.tagName.toLowerCase();if(n.startsWith("o:")||n.startsWith("w:")||n==="style"||n==="script"||n==="link"||n==="meta"){i.remove();return}if(n==="img"){const r=Number(i.getAttribute("width")||0),s=Number(i.getAttribute("height")||0);(r&&r<=3||s&&s<=3)&&i.remove();return}if(n==="font"){const r=Ot[Number(i.getAttribute("size"))],s=e.createElement("span"),a=[];for(r&&a.push(`font-size:${r}px`),i.color&&a.push(`color:${i.color}`),a.length&&s.setAttribute("style",a.join(";"));i.firstChild;)s.appendChild(i.firstChild);i.replaceWith(s);return}for(const r of Array.from(i.attributes)){const s=r.name.toLowerCase();(s.startsWith("mso-")||s==="class"||s.startsWith("_")||s.startsWith("w:")||s.startsWith("o:")||s==="lang"||s==="dir")&&i.removeAttribute(r.name)}}),t.innerHTML}function ce(o){return String(o).replace(/[&<>"']/g,e=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[e])}function Te(o){const e=new DOMParser().parseFromString(`<div>${o}</div>`,"text/html");return e.body.querySelectorAll("style,script").forEach(t=>t.remove()),e.body.innerHTML=e.body.innerHTML.replace(/<\/(p|div|h[1-6]|li|blockquote|pre|tr)>/gi,`
|
|
481
481
|
`),e.body.textContent.replace(/\u00a0/g," ").replace(/\n{3,}/g,`
|
|
482
482
|
|
|
483
|
-
`).trim()}const Pt=1e4;function Ae(o){if(Array.isArray(o))return o;if(!o||typeof o!="object")return[];for(const e of["items","list","data","rows","records","result"]){const t=o[e];if(Array.isArray(t))return t;if(t&&typeof t=="object"){const i=Ae(t);if(i.length)return i}}return[]}function Z(o,e){for(const t of e){const i=o[t];if(i!=null)return i}}function Nt(o,e){if(o==null)return null;if(typeof o=="string"||typeof o=="number"){const n=String(o);return{value:n,label:n,desc:"",url:"",group:"",html:"",disabled:!1,raw:o}}if(typeof o!="object")return null;const t=Z(o,["value","id","key","val","code"]),i=Z(o,["label","text","name","title"]);return{value:String(t===void 0?e:t),label:String(i===void 0||i===""?t===void 0?e:t:i),desc:String(Z(o,["desc","description","sub","subtitle","tip"])??""),url:String(Z(o,["url","href","link","jumpUrl","jump"])??""),group:String(o.group??""),html:String(o.html??""),disabled:!!o.disabled,raw:o}}function G(o){return Ae(o).map(Nt).filter(Boolean)}function de(o={}){const e=o.position!==void 0?o.position:o.at,t=n=>Math.max(0,Math.floor(Number(n))),i=n=>typeof n=="object"&&n?n.before||n.after:n;if(typeof e=="number"&&Number.isFinite(e))return t(e);if(typeof e=="string"&&e){const n=e.toLowerCase();return n==="start"||n==="begin"||n==="first"?"start":n==="end"||n==="last"||n==="main"?"end":n==="tail"||n===":tail"||n==="right"?"tail":{before:e}}if(e&&typeof e=="object"){if(e.before)return{before:String(i(e))};if(e.after)return{after:String(i(e))}}return typeof o.index=="number"&&Number.isFinite(o.index)?t(o.index):o.before?{before:String(o.before)}:o.after?{after:String(o.after)}:null}function He(o){if(!o||typeof o!="object")return null;const e=String(o.name||"").trim();return e?{name:e,position:de(o),type:o.type==="button"?"button":"select",title:o.title||o.text||e,text:o.text||"",placeholder:o.placeholder||o.text||"请选择",icon:o.icon||"",width:Number(o.width)>0?Number(o.width):0,searchable:!!o.searchable,note:o.note?String(o.note):"",emptyText:o.emptyText?String(o.emptyText):"",cache:o.cache!==!1,keepValue:o.keepValue!==!1,multiple:!1,options:o.options??null,load:typeof o.load=="function"?o.load:null,url:o.url?String(o.url):"",fetchOptions:o.fetchOptions&&typeof o.fetchOptions=="object"?o.fetchOptions:{},pick:typeof o.pick=="function"?o.pick:null,link:o.link??null,insert:o.insert===void 0?"auto":o.insert,onSelect:typeof o.onSelect=="function"?o.onSelect:null,onClick:typeof o.onClick=="function"?o.onClick:null,active:typeof o.active=="function"?o.active:null,enabled:typeof o.enabled=="function"?o.enabled:null}:null}function Be(o){return Array.isArray(o)?o.map(He).filter(Boolean):[]}function jt(){return{items:null,loaded:!1,loading:null,value:null,controller:null,error:"",gen:0,external:!1}}async function Ft(o,e,t){return o.load?G(await o.load(e)):o.url?G(await Dt(o,e,t)):G(o.options)}async function Dt(o,e,t){var c;const i=o.fetchOptions,n=i.fetch||(typeof fetch=="function"?fetch.bind(globalThis):null);if(!n)throw new Error("当前环境无 fetch,请改用 load 函数提供数据");(c=t.controller)==null||c.abort();const r=typeof AbortController=="function"?new AbortController:null;t.controller=r;const s=Number(i.timeout)>0?Number(i.timeout):Pt,a=setTimeout(()=>r==null?void 0:r.abort(),s);try{const d=await n(o.url,{method:i.method||"GET",headers:i.headers,body:i.body,credentials:i.credentials,signal:r?r.signal:void 0});if(!d||d.ok===!1)throw new Error(`接口返回 ${d&&d.status?d.status:"异常"}`);const h=i.parser?await i.parser(d):await d.json();return o.pick?o.pick(h,e):h}catch(d){throw d&&d.name==="AbortError"?new Error(`请求超时(${s}ms)或被取消`):d}finally{clearTimeout(a),t.controller===r&&(t.controller=null)}}function It(o,e,t,{force:i=!1}={}){if(!i&&t.external&&t.items||!i&&o.cache&&t.items)return Promise.resolve(t.items);if(!i&&t.loading)return t.loading;const n=t.gen,r=Ft(o,e,t).then(s=>n!==t.gen?t.items:(t.items=s,t.loaded=!0,t.error="",s)).catch(s=>{if(n!==t.gen)return t.items;throw t.error=s&&s.message?s.message:String(s),s}).finally(()=>{t.loading===r&&(t.loading=null)});return t.loading=r,r}function qt(o,e){return o.gen+=1,o.items=G(e),o.loaded=!0,o.error="",o.external=!0,he(o),o.loading=null,o.items}function he(o){var e;(e=o.controller)==null||e.abort(),o.controller=null}function pe(o,e){return String(o).replace(/\{(\w+)\}/g,(t,i)=>{if(e[i]!==void 0&&e[i]!==null)return String(e[i]);const n=e.raw&&e.raw[i];return n==null?t:String(n)})}function ue(o,e,t){return typeof o=="function"?o(e,t):o}function $e(o,e,t){const i=o.link;let n=null;if(typeof i=="function"?n=i(e,t):typeof i=="string"?n={url:i}:i&&typeof i=="object"?n=i:(i===!0||e.url)&&(n={url:e.url}),!n)return null;typeof n=="string"&&(n={url:n});const r=W(pe(String(ue(n.url,e,t)??""),e));if(!r||!Y(r))return null;const s=ue(n.text,e,t),a=ue(n.title,e,t),c=n.mode==="open"?"open":"insert",d=n.target==="_self"||n.target===!1?"_self":"_blank";return{mode:c,url:r,text:s==null||s===""?e.label:pe(String(s),e),target:d,title:a?pe(String(a),e):""}}function Re(o,e){o.commands.insertHTML(ce(e))}async function Ut(o,e,t,i){o.restoreSelection();const n=$e(e,i,o),r={editor:o,item:i,link:n,insertLink:d=>Oe(o,{...n,...d}),insertHtml:d=>o.commands.insertHTML(String(d)),insertText:d=>Re(o,d),open:(d,h)=>Pe(d||n&&n.url,h||n&&n.target)};let s="none",a=!1;e.onSelect&&(a=await e.onSelect(i,r)===!1),a||(s=Wt(o,e,i,n)),e.keepValue&&(t.value=i);const c={name:e.name,item:i,link:n,action:s,editor:o};return o.emit("customselect",c),c}function Wt(o,e,t,i){const n=e.insert;return n===!1||n==="none"?"none":i&&i.mode==="open"?(Pe(i.url,i.target),"open"):n==="link"||n==="auto"&&i?i?(Oe(o,i),"link"):"none":n==="html"||n==="auto"&&t.html?t.html?(o.commands.insertHTML(t.html),"html"):"none":(Re(o,t.label),"text")}function Oe(o,e){o.commands.createLink({url:e.url,text:e.text,target:e.target!=="_self"})}function Pe(o,e="_blank"){!o||!Y(o)||(e==="_self"?window.location.href=o:window.open(o,"_blank","noopener,noreferrer"))}const fe='<svg class="ke-caret" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><path d="m6 9 6 6 6-6"/></svg>',Ne="keditor.toolbarScrollHint",_t='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.1" stroke-linecap="round" stroke-linejoin="round"><path d="M8 7 4 12l4 5"/><path d="M16 7l4 5-4 5"/><path d="M4 12h16"/></svg>',me=[{value:"p",label:"正文",desc:"默认段落 · 17px,正文内容都用它",sample:"正文示例文字",sampleClass:"s-body"},{value:"h1",label:"标题一",desc:"大标题 · 22px 加粗,全文主标题(建议只用一次)",sample:"标题一示例",sampleClass:"s-h1"},{value:"h2",label:"标题二",desc:"章节标题 · 20px 加粗,划分小节",sample:"标题二示例",sampleClass:"s-h2"},{value:"h3",label:"标题三",desc:"小标题 · 18px 加粗,章节内的层级",sample:"标题三示例",sampleClass:"s-h3"}],Vt=[12,14,15,16,17,18,20,22,24,28,32],Q=["undo","redo","|","heading","fontsize","|","bold","italic","underline","strike","|","foreColor","backColor","|","alignLeft","alignCenter","alignRight","alignJustify","|","ul","ol","quote","|","link","image","video","table","code","hr","clear",":tail","source","fullscreen"],je={undo:{icon:"undo",title:"撤销 (⌘/Ctrl+Z)",run:o=>o.undo(),active:o=>!!o.canUndo,enabled:o=>o.canUndo},redo:{icon:"redo",title:"重做 (⌘/Ctrl+Shift+Z)",run:o=>o.redo(),active:o=>!!o.canRedo,enabled:o=>o.canRedo},bold:{glyph:["B","ke-glyph"],title:"加粗 (⌘/Ctrl+B)",cmd:"bold",active:o=>o.bold},italic:{glyph:["I","ke-glyph ke-glyph-i"],title:"斜体 (⌘/Ctrl+I)",cmd:"italic",active:o=>o.italic},underline:{glyph:["U","ke-glyph ke-glyph-u"],title:"下划线 (⌘/Ctrl+U)",cmd:"underline",active:o=>o.underline},strike:{glyph:["S","ke-glyph ke-glyph-s"],title:"删除线",cmd:"strike",active:o=>o.strikeThrough},alignLeft:{icon:"alignLeft",title:"左对齐",run:o=>o.commands.setAlign("left"),active:o=>o.align==="left"},alignCenter:{icon:"alignCenter",title:"居中",run:o=>o.commands.setAlign("center"),active:o=>o.align==="center"},alignRight:{icon:"alignRight",title:"右对齐",run:o=>o.commands.setAlign("right"),active:o=>o.align==="right"},alignJustify:{icon:"alignJustify",title:"两端对齐",run:o=>o.commands.setAlign("justify"),active:o=>o.align==="justify"},ul:{icon:"ul",title:"无序列表",run:o=>o.commands.toggleList("unordered"),active:o=>o.ul},ol:{icon:"ol",title:"有序列表",run:o=>o.commands.toggleList("ordered"),active:o=>o.ol},quote:{icon:"quote",title:"引用",run:o=>o.commands.toggleBlockquote(),active:o=>o.block==="blockquote"},link:{icon:"link",title:"插入链接",run:o=>o.toolbar.openLink(),active:o=>o.link,toggles:!0},image:{icon:"image",title:"图片(本地上传 / 网络链接)",run:o=>o.toolbar.openMedia("image"),toggles:!0},video:{icon:"video",title:"视频(本地上传 / 网络链接,支持分片上传)",run:o=>o.toolbar.openMedia("video"),toggles:!0},table:{icon:"table",title:"插入表格",run:o=>o.toolbar.openTable(),toggles:!0},code:{icon:"code",title:"代码块",run:o=>o.commands.insertCodeBlock()},hr:{icon:"hr",title:"分割线",run:o=>o.commands.insertDivider()},clear:{icon:"clear",title:"清除格式",run:o=>o.commands.clearFormat()},source:{icon:"source",title:"查看 / 编辑 HTML 源码(⌘/Ctrl+Shift+K)",text:"源码",run:o=>o.toggleSource(),active:o=>o.source},preview:{icon:"preview",title:"预览效果(手机 / 平板 / 电脑宽度)",text:"预览",run:o=>o.togglePreview(),active:o=>o.preview},fullscreen:{icon:"expand",title:"全屏编辑",text:"全屏",run:o=>o.toggleFullscreen(),active:o=>o.fullscreen},foreColor:{pop:"fore",title:"字体颜色",toggles:!0,swatch:"fore"},backColor:{pop:"back",title:"背景高亮色",toggles:!0,swatch:"back"}};class Kt{constructor(e,t=Q,i=[]){this.editor=e,this.buttons=new Map,this.custom=new Map,this.colorState={foreColor:"#3f3f3f",backColor:"#f6c344"},this.recent={foreColor:[],backColor:[]},this.el=e.tbEl;for(const n of i)this.registerCustom(n);this.build(t),this.setupScrollHints()}build(e){const t=l("div.ke-tb-group");this.el.appendChild(t),this.groupEl=t,this.tailEl=null;const i=()=>this.tailEl||t;for(const n of e){if(n==="|"){i().appendChild(l("span.ke-tb-sep"));continue}if(n===":tail"){this.tailEl=l("div.ke-tb-tail"),this.el.appendChild(this.tailEl);continue}if(this.custom.has(n)){const s=this.custom.get(n);s.button=this.buildCustomButton(s),i().appendChild(s.button);continue}if(n==="heading"){i().appendChild(this.buildHeading());continue}if(n==="fontsize"){i().appendChild(this.buildFontSize());continue}const r=je[n];r&&i().appendChild(this.buildButton(n,r))}for(const[n,r]of this.custom)r.button||(r.button=this.buildCustomButton(r),this.insertButton(r.button,r.spec.position))}buildButton(e,t){const i=l("button.ke-btn",{type:"button",title:t.title,"data-k-item":e,onclick:n=>{var r;n.preventDefault(),t.pop?this.toggleColor(e,i):t.cmd?this.editor.commands.toggleMark(t.cmd):(r=t.run)==null||r.call(t,this.editor),t.toggles||this.editor.popover.close()}});if(t.icon&&(i.innerHTML=M(t.icon)),t.text&&i.appendChild(l("span.ke-btn-text",{text:t.text})),t.glyph){const[n,r]=t.glyph;i.appendChild(l("span",{class:r,text:n}))}if(t.swatch){const n=t.swatch==="fore"?this.colorState.foreColor:this.colorState.backColor,r=l("span",{class:t.swatch==="fore"?"ke-glyph ke-glyph-a":"ke-glyph ke-glyph-a ke-glyph-hl"});r.appendChild(l("span",{text:"A"})),i.appendChild(r),t.swatch==="fore"&&i.appendChild(l("span",{class:"ke-dot"})),this.paintButton(i,t.swatch,n),i.dataset.kPop=t.swatch==="fore"?"foreColor":"backColor"}return t.toggles&&!t.swatch&&(i.dataset.kPop=e),this.buttons.set(e,i),i}paintButton(e,t,i){!e||!i||e.style.setProperty(t==="fore"?"--ke-fore":"--ke-back",i)}openPop(e,t,i={}){this.editor.saveSelection(),this.editor.popover.open(e,t,{align:"start",...i,onClose:()=>{var n;e.classList.remove("ke-is-open"),(n=i.onClose)==null||n.call(i)}}),e.classList.add("ke-is-open")}togglePop(e,t,i,n={}){const r=this.editor.popover;if(r.isOpen&&r.anchor===t){r.close();return}this.openPop(t,i,n)}buildHeading(){const e=me[0],t=l("button.ke-btn.ke-btn-label",{type:"button",title:"段落样式:正文 / 标题一 / 标题二 / 标题三","data-k-item":"heading",dataset:{kPop:"heading"},onclick:i=>{i.preventDefault(),this.togglePop("heading",t,()=>ct(me,{value:this.editor.getState().block,onPick:n=>{this.editor.restoreSelection(),this.editor.commands.setHeading(n),this.editor.popover.close(),this.editor.refresh()}}))}});return t.innerHTML=`<span class="ke-btn-text">${e.label}</span>${fe}`,this.headingEl=t,this.buttons.set("heading",t),t}buildFontSize(){const e=l("button.ke-btn.ke-btn-label",{type:"button",title:"字号","data-k-item":"fontsize",dataset:{kPop:"fontsize"},onclick:t=>{t.preventDefault(),this.togglePop("fontsize",e,()=>dt(Vt,{value:this.editor.getState().fontSize,onPick:i=>{this.editor.restoreSelection(),this.editor.commands.setFontSize(Number(i)),this.editor.popover.close(),this.editor.refresh()}}))}});return e.innerHTML=`<span class="ke-btn-text">字号</span>${fe}`,this.fontSizeEl=e,this.buttons.set("fontsize",e),e}registerCustom(e){const t=He(e);if(!t)return null;const i=this.custom.get(t.name),n={spec:t,rt:i?i.rt:jt(),button:i?i.button:null};return this.custom.set(t.name,n),n}buildCustomButton(e){const{spec:t}=e,i=t.type==="select",n=l("button.ke-btn",{type:"button",class:i?"ke-btn-label ke-btn-custom":"ke-btn-custom",title:t.title,"data-k-item":t.name,dataset:{kPop:t.name,kCustom:t.name},onclick:r=>{r.preventDefault(),i?this.openCustom(t.name):this.runCustomButton(t)}});return t.icon&&(n.innerHTML=/</.test(t.icon)?t.icon:M(t.icon)),i?(n.appendChild(l("span.ke-btn-text",{text:t.text||t.placeholder})),n.insertAdjacentHTML("beforeend",fe)):t.text&&n.appendChild(l("span.ke-btn-text",{text:t.text})),this.syncCustomLabel(t.name,n),n}syncCustomLabel(e,t){const i=this.custom.get(e),n=t||(i==null?void 0:i.button);if(!i||!n)return;const{spec:r,rt:s}=i;if(r.type!=="select")return;const a=n.querySelector(".ke-btn-text");if(!a)return;const c=s.value;a.textContent=c?c.label:r.text||r.placeholder,n.title=c?`${r.title}:${c.label}`:r.title,n.classList.toggle("ke-has-value",!!c)}openCustom(e){const t=this.custom.get(e);if(!t)return;this.revealButton(t.button);const{spec:i,rt:n}=t,r=!!(i.load||i.url),s=({force:a}={})=>It(i,this.editor,n,{force:a});this.togglePop(e,t.button,()=>kt({title:i.title,note:i.note||"",searchable:i.searchable,width:i.width,remote:r,value:n.value?n.value.value:"",emptyText:i.emptyText,load:s,reload:s,linkOf:a=>$e(i,a,this.editor),onPick:a=>this.pickCustom(e,a)}))}async pickCustom(e,t){const i=this.custom.get(e);if(i){this.editor.popover.close();try{await Ut(this.editor,i.spec,i.rt,t)}catch(n){this.editor.reportError("custombutton",n)}this.syncCustomLabel(e),this.editor.refresh()}}async runCustomButton(e){this.editor.popover.close();try{e.onClick&&await e.onClick({editor:this.editor,name:e.name}),this.editor.emit("customclick",{name:e.name,editor:this.editor})}catch(t){this.editor.reportError("custombutton",t)}this.editor.refresh()}addButton(e,t={}){var r;const i=this.registerCustom(e);if(!i)return null;i.button&&i.button.remove(),i.button=this.buildCustomButton(i);const n=t.at!==void 0?t.at:de(t)??i.spec.position;return this.insertButton(i.button,n,{withSep:n==null}),this.revealButton(i.button),(r=this.syncScrollHints)==null||r.call(this),i.button}buttonNodes(){const e=[];for(const t of[this.groupEl,this.tailEl])if(t)for(const i of t.children)i.dataset&&i.dataset.kItem&&e.push(i);return e}slotOf(e){const t={parent:this.groupEl||this.el,ref:null};if(e==="tail")return{parent:this.tailEl||this.groupEl||this.el,ref:null};if(e==null||e==="end")return t;if(e==="start"){const a=this.buttonNodes()[0];return a?{parent:a.parentElement,ref:a}:t}const i=this.buttonNodes();if(typeof e=="number"){const a=i[Math.max(0,Math.floor(e))];if(a)return{parent:a.parentElement,ref:a};const c=i[i.length-1];return c?{parent:c.parentElement,ref:null}:t}const n=!!(e&&typeof e=="object"&&e.after),r=typeof e=="string"?e:String((n?e.after:e.before)||""),s=i.find(a=>a.dataset.kItem===r);return s?{parent:s.parentElement,ref:n?s.nextElementSibling||null:s}:t}insertButton(e,t,{withSep:i}={}){const{parent:n,ref:r}=this.slotOf(t);!n||!e||(i&&!r&&n.appendChild(l("span.ke-tb-sep")),n.insertBefore(e,r||null))}moveButton(e,t){var n,r;const i=this.buttonNodes().find(s=>s.dataset.kItem===String(e));return i?(i.remove(),this.insertButton(i,t===void 0?((n=this.custom.get(String(e)))==null?void 0:n.spec.position)??null:t),this.revealButton(i),(r=this.syncScrollHints)==null||r.call(this),!0):!1}revealButton(e){const t=this.el;if(!t||!e||!e.isConnected)return;const i=t.scrollWidth-t.clientWidth;if(i<=1)return;const n=this.tailEl?this.tailEl.offsetWidth:0,r=e.offsetLeft,s=r+e.offsetWidth,a=t.scrollLeft+t.clientWidth-n;s>a-4?t.scrollLeft=Math.min(i,s-t.clientWidth+n+10):r<t.scrollLeft+4&&(t.scrollLeft=Math.max(0,r-10))}removeButton(e){var r,s,a,c;const t=this.custom.get(e);if(!t)return!1;he(t.rt),this.editor.popover.anchor===t.button&&this.editor.popover.close();const i=(r=t.button)==null?void 0:r.previousElementSibling,n=(s=t.button)==null?void 0:s.nextElementSibling;return(a=t.button)==null||a.remove(),i&&i.classList.contains("ke-tb-sep")&&(!n||n.classList.contains("ke-tb-sep"))&&i.remove(),this.buttons.delete(e),this.custom.delete(e),(c=this.syncScrollHints)==null||c.call(this),!0}setButtonOptions(e,t){const i=this.custom.get(e);if(!i)return null;const n=qt(i.rt,t);return this.editor.popover.isOpen&&this.editor.popover.anchor===i.button&&(this.editor.popover.close(),this.openCustom(e)),n}getButtonValue(e){const t=this.custom.get(e);return t?t.rt.value:null}setButtonValue(e,t){const i=this.custom.get(e);if(!i)return null;const r=(i.rt.items||[]).find(s=>String(s.value)===String(t))||null;return i.rt.value=r,this.syncCustomLabel(e),r}toggleColor(e,t){const i=e==="foreColor"?"fore":"back";this.togglePop(e,t,()=>at({title:i==="fore"?"字体颜色":"背景高亮色",kind:i,value:this.colorState[e],recents:this.recent[e],onPick:n=>this.applyColor(e,i,n,t),onClear:()=>this.applyColor(e,i,null,t)}),{onClose:()=>t.classList.remove("ke-is-active")})}applyColor(e,t,i,n){this.editor.restoreSelection(),i&&(this.colorState[e]=i,this.recent[e]=[i,...this.recent[e].filter(r=>r.toLowerCase()!==i.toLowerCase())].slice(0,8),this.paintButton(n,t,i)),this.editor.commands.setColor(t,i),this.editor.popover.close()}openTable(){const e=this.buttons.get("table");this.togglePop("table",e,()=>ht((t,i)=>{this.editor.restoreSelection(),this.editor.commands.insertTable(t,i),this.editor.popover.close()}))}openLink(){const e=this.buttons.get("link"),t=this.editor.getState(),i=t.linkUrl;this.togglePop("link",e,()=>ft({url:i||"",text:i?"":t.selectionText||"",target:i?t.linkTarget:!0,onCancel:()=>this.editor.popover.close(),onRemove:i?()=>{this.editor.restoreSelection(),this.editor.commands.removeLink(),this.editor.popover.close()}:null,onSubmit:({url:n,text:r,target:s})=>{this.editor.restoreSelection(),this.editor.commands.createLink({url:W(n),text:r,target:s}),this.editor.popover.close()}}))}openMedia(e){const t=this.buttons.get(e),i=this.editor,n=i.options;this.togglePop(e,t,()=>pt(e,{multiple:e==="image",maxText:`${e==="image"?"图片":"视频"}上限 ${Gt(e==="image"?n.maxImageSize:n.maxVideoSize)}`,hint:e==="image"?"支持 PNG / JPG / GIF / WebP / SVG":"支持 MP4 / MOV / WebM,大文件自动分片",onFiles:r=>{i.popover.close(),r&&r.length?i.media.addFiles([...r]):i.media.pickFiles(e)},onUrl:({url:r,name:s})=>{i.popover.close(),i.restoreSelection(),i.media.insertFromUrl(e,r,s)}}))}refresh(e){var t;for(const[i,n]of this.buttons){const r=je[i];if(!r)continue;const s=((t=r.active)==null?void 0:t.call(r,e))||!1;(n.dataset.kPop||!r.pop)&&n.classList.toggle("ke-is-active",s),r.enabled&&(n.disabled=!r.enabled(e))}for(const[i,n]of this.custom){const{spec:r,button:s}=n;s&&(r.active&&s.classList.toggle("ke-is-active",!!r.active(e,this.editor)),r.enabled&&(s.disabled=!r.enabled(e,this.editor)),r.type==="select"&&this.syncCustomLabel(i))}if(this.headingEl){const i=me.find(r=>r.value===e.block),n=this.headingEl.querySelector(".ke-btn-text");n&&(n.textContent=i?i.label:"正文"),this.headingEl.title=i?`${i.label}:${i.desc}`:"段落样式"}if(this.fontSizeEl){const i=this.fontSizeEl.querySelector(".ke-btn-text");i&&(i.textContent=e.fontSize?`${e.fontSize}px`:"字号")}if(e.linkUrl){const i=this.buttons.get("link");i==null||i.classList.add("ke-is-active")}}setupScrollHints(){const e=this.el,t=this.editor.el;e.isConnected&&(this.scrollFades=l("div.ke-tb-fades",{"aria-hidden":"true"},[l("i.ke-tb-fade ke-tb-fade-l")]),e.insertAdjacentElement("afterend",this.scrollFades),this.syncScrollHints=()=>{if(!e.isConnected||!t.isConnected)return;const i=e.scrollWidth-e.clientWidth,n=i>1,r=e.scrollLeft;t.classList.toggle("ke-tb-scrollable",n),t.classList.toggle("ke-tb-can-l",n&&r>1),t.classList.toggle("ke-tb-can-r",n&&r<i-1),t.style.setProperty("--ke-tb-h",`${e.offsetHeight}px`),n&&!this.hintSettled&&this.showScrollHint()},this.onTbScroll=()=>{this.syncScrollHints(),this.hideScrollHint()},e.addEventListener("scroll",this.onTbScroll,{passive:!0}),typeof ResizeObserver<"u"&&(this.tbRO=new ResizeObserver(()=>this.syncScrollHints()),this.tbRO.observe(e)),this.onTbPointerDown=i=>{this.hideScrollHint(),this.startDragScroll(i)},e.addEventListener("pointerdown",this.onTbPointerDown),requestAnimationFrame(this.syncScrollHints))}startDragScroll(e){const t=this.el,i=this.editor.el;if(e.button!==0||e.pointerType!=="mouse"||t.scrollWidth<=t.clientWidth+1||e.target.closest("input, textarea, select"))return;const n=e.clientX,r=t.scrollLeft;let s=!1;const a=d=>{var p;const h=d.clientX-n;if(!s){if(Math.abs(h)<5)return;s=!0;try{t.setPointerCapture(e.pointerId)}catch{}i.classList.add("ke-tb-dragging"),(p=this.editor.popover)==null||p.close()}d.preventDefault(),t.scrollLeft=r-h},c=()=>{if(t.removeEventListener("pointermove",a),t.removeEventListener("pointerup",c),t.removeEventListener("pointercancel",c),i.classList.remove("ke-tb-dragging"),!s)return;try{t.releasePointerCapture(e.pointerId)}catch{}const d=u=>{u.preventDefault(),u.stopPropagation(),h()},h=()=>{clearTimeout(p),t.removeEventListener("click",d,!0)},p=setTimeout(h,400);t.addEventListener("click",d,!0)};t.addEventListener("pointermove",a),t.addEventListener("pointerup",c),t.addEventListener("pointercancel",c)}showScrollHint(){this.hintSettled=!0;let e=!1;try{e=localStorage.getItem(Ne)==="1"}catch{}e||(this.hintEl=l("div.ke-tb-hint",{"aria-hidden":"true"},[l("span.ke-tb-hint-ico",{html:_t}),l("span",{text:"工具栏可左右滑动"})]),this.editor.el.appendChild(this.hintEl),this.hintTimer=setTimeout(()=>this.hideScrollHint(),3800))}hideScrollHint(){this.hintTimer&&(clearTimeout(this.hintTimer),this.hintTimer=null);const e=this.hintEl;if(e){this.hintEl=null;try{localStorage.setItem(Ne,"1")}catch{}e.classList.add("ke-is-out"),setTimeout(()=>e.remove(),260)}}destroy(){var i,n,r;const e=this.el;this.tbRO&&(this.tbRO.disconnect(),this.tbRO=null),this.hintTimer&&(clearTimeout(this.hintTimer),this.hintTimer=null),this.onTbScroll&&e.removeEventListener("scroll",this.onTbScroll),this.onTbPointerDown&&e.removeEventListener("pointerdown",this.onTbPointerDown);for(const s of this.custom.values())he(s.rt);this.custom.clear(),(i=this.scrollFades)==null||i.remove(),(n=this.hintEl)==null||n.remove(),this.scrollFades=null,this.hintEl=null;const t=(r=this.editor)==null?void 0:r.el;t&&(t.classList.remove("ke-tb-scrollable","ke-tb-can-l","ke-tb-can-r","ke-tb-dragging"),t.style.removeProperty("--ke-tb-h")),e.innerHTML="",this.buttons.clear()}}function Gt(o){if(!o)return"不限";const e=o/1024/1024;return e>=1?`${Math.round(e)}MB`:`${Math.round(o/1024)}KB`}function z(o){const e=window.getSelection();if(!e||e.rangeCount===0)return null;const t=e.getRangeAt(0);return o.contains(t.commonAncestorContainer)?t:null}function Fe(o){const e=window.getSelection();if(!e||e.rangeCount===0)return null;const t=e.getRangeAt(0);if(!o.contains(t.startContainer))return null;let i=0;return document.createTreeWalker(o,NodeFilter.SHOW_TEXT,{acceptNode(s){return s===t.startContainer?NodeFilter.FILTER_ACCEPT:(i+=s.textContent.length,NodeFilter.FILTER_SKIP)}}).nextNode()?i+t.startOffset:t.startContainer===o?0:null}function Xt(o,e){if(e==null)return;const t=window.getSelection();let i=Math.max(0,e);const n=document.createTreeWalker(o,NodeFilter.SHOW_TEXT);let r=n.nextNode(),s=null;for(;r;){const a=r.textContent.length;if(i<=a){try{t.setBaseAndExtent(r,i,r,i)}catch{}return}i-=a,s=r,r=n.nextNode()}if(s)try{t.setBaseAndExtent(s,s.textContent.length,s,s.textContent.length)}catch{}}function P(o,e,{inline:t=!1,selectAfter:i=!0}={}){o.focus();const n=z(o);if(!n)return o.appendChild(e),ee(o),e;if(n.collapsed||n.deleteContents(),t)n.insertNode(e);else{const a=N(n.startContainer,o);!a||a===o?o.appendChild(e):a.after(e)}const r=document.createRange();r.setStartAfter(e),r.collapse(!0);const s=window.getSelection();return s.removeAllRanges(),s.addRange(r),ee(o),i&&s.rangeCount===0&&o.focus(),e}function ee(o){const e=o.lastElementChild;if(!e){o.appendChild(document.createElement("p"));return}if(/^(IMG|VIDEO|IFRAME)$/.test(e.tagName)||e.dataset.kmedia!==void 0){const t=document.createElement("p");t.appendChild(document.createElement("br")),o.appendChild(t)}}function N(o,e){let t=o;for(;t&&t!==e;){if(t.nodeType===1&&/^(P|DIV|H[1-6]|LI|BLOCKQUOTE|PRE|SECTION|TD|TH)$/.test(t.tagName))return t;t=t.parentNode}return null}class Jt{constructor(e){this.editor=e,this.root=e.root}exec(e,t=null){this.editor.focus(),document.execCommand("styleWithCSS",!1,!0),document.execCommand("defaultParagraphSeparator",!1,"p");const i=document.execCommand(e,!1,t);return this.editor.afterEdit(),i}queryState(e){try{return document.queryCommandState(e)}catch{return!1}}queryValue(e){try{return document.queryCommandValue(e)}catch{return""}}hasSelection(){const e=z(this.root);return!!(e&&!e.collapsed)}toggleMark(e){const i={bold:"bold",italic:"italic",underline:"underline",strike:"strikeThrough"}[e];i&&(this.exec(i),this.root.querySelectorAll('span[style=""]').forEach(n=>n.replaceWith(...n.childNodes)))}setFontSize(e){this.editor.focus(),document.execCommand("styleWithCSS",!1,!1);const t=`__ke_fs_${ie()}__`;this.root.setAttribute("data-ke-marker",t),document.execCommand("fontSize",!1,"7"),this.root.removeAttribute("data-ke-marker"),this.root.querySelectorAll('font[size="7"]').forEach(i=>{const n=document.createElement("span");for(n.style.fontSize=`${e}px`;i.firstChild;)n.appendChild(i.firstChild);i.replaceWith(n)}),this.root.querySelectorAll("span").forEach(i=>{/xx-large/i.test(i.style.fontSize)&&(i.style.fontSize=`${e}px`)}),document.execCommand("styleWithCSS",!1,!0),this.editor.afterEdit()}setColor(e,t){this.editor.focus(),document.execCommand("styleWithCSS",!1,!0),t||(t=e==="fore"?"#3f3f3f":"transparent"),document.execCommand(e==="fore"?"foreColor":"hiliteColor",!1,t)||document.execCommand(e==="fore"?"foreColor":"backColor",!1,t),e==="back"&&t==="transparent"&&this.root.querySelectorAll('[style*="background-color"]').forEach(n=>{/background-color:\s*transparent|rgba\(0, 0, 0, 0\)/i.test(n.getAttribute("style")||"")&&(n.style.backgroundColor="",n.getAttribute("style").trim()||n.replaceWith(...n.childNodes))}),this.editor.afterEdit()}setAlign(e){var c,d;const t=(c=this.editor.bubble)==null?void 0:c.node;if(t&&((d=t.dataset)==null?void 0:d.kMedia)==="image"&&e!=="justify"){const h=t.querySelector("img");if(h){ne(h,e),this.editor.commitHistory(),this.editor.bubble.position();return}}const n={left:"justifyLeft",center:"justifyCenter",right:"justifyRight",justify:"justifyFull"}[e];if(!n)return;this.editor.focus();const r=z(this.root),s=N((r==null?void 0:r.commonAncestorContainer)||this.root,this.root);document.execCommand("styleWithCSS",!1,!0),document.execCommand(n);const a=s||this.root.firstElementChild;a&&/^(FIGURE|DIV|VIDEO)/.test(a.tagName||"")&&(a.style.textAlign=e),this.editor.afterEdit()}toggleList(e){this.exec(e==="ordered"?"insertOrderedList":"insertUnorderedList")}setHeading(e){const t=e?`<${e}>`:"<p>";this.exec("formatBlock",t)}toggleBlockquote(){const e=z(this.root),t=N((e==null?void 0:e.commonAncestorContainer)||this.root,this.root);t&&t.tagName==="BLOCKQUOTE"?this.exec("formatBlock","<p>"):this.exec("formatBlock","<blockquote>")}createLink({url:e,text:t="",target:i=!1}){var a,c;this.editor.focus();const n=z(this.root),r=n&&!n.collapsed,s=t||(r?n.toString():e);if(r)document.execCommand("createLink",!1,e),(c=(a=n.commonAncestorContainer.parentElement)==null?void 0:a.closest)==null||c.call(a,"a"),this.root.querySelectorAll(`a[href="${Zt(e)}"]`).forEach(d=>{i?(d.setAttribute("target","_blank"),d.setAttribute("rel","noopener noreferrer")):d.removeAttribute("target")});else{const d=l("a",{href:e},[s]);i&&(d.setAttribute("target","_blank"),d.setAttribute("rel","noopener noreferrer")),P(this.root,d,{inline:!0})}this.editor.afterEdit()}removeLink(){const e=z(this.root);Yt(e,this.root).forEach(i=>i.replaceWith(...i.childNodes)),this.editor.afterEdit()}insertTable(e,t){const i=document.createElement("table"),n=document.createElement("tbody");for(let r=0;r<t;r+=1){const s=document.createElement("tr");for(let a=0;a<e;a+=1){const c=document.createElement(r===0?"th":"td");c.innerHTML="<br>",s.appendChild(c)}n.appendChild(s)}i.appendChild(n),P(this.root,i),this.exec("insertHTML",""),this.editor.afterEdit()}insertCodeBlock(e=""){const t=document.createElement("pre"),i=document.createElement("code");i.textContent=e||"// 在这里输入代码",t.appendChild(i),P(this.root,t),this.editor.afterEdit()}insertDivider(){const e=document.createElement("hr");P(this.root,e),this.editor.afterEdit()}insertHTML(e,{clean:t=!0}={}){const i=t?K(e):e;this.editor.focus();const n=z(this.root);if(n){n.deleteContents();const r=document.createElement("div");r.innerHTML=i;const s=document.createDocumentFragment();for(;r.firstChild;)s.appendChild(r.firstChild);const a=s.lastChild;if(n.insertNode(s),a){const c=document.createRange();c.setStartAfter(a.nodeType===3?a:a.lastChild||a),c.collapse(!0);const d=window.getSelection();d.removeAllRanges(),d.addRange(c)}}else this.root.insertAdjacentHTML("beforeend",i);this.editor.afterEdit()}clearFormat(){if(this.editor.focus(),this.hasSelection()){document.execCommand("removeFormat"),document.execCommand("unlink");const e=z(this.root),t=N(e==null?void 0:e.commonAncestorContainer,this.root);t&&/^(H[1-6]|BLOCKQUOTE|PRE)$/.test(t.tagName)&&this.exec("formatBlock","<p>"),this.stripInlineStylesInRange(e)}else{const e=z(this.root),t=N((e==null?void 0:e.commonAncestorContainer)||this.root,this.root);if(t){const i=t.innerHTML,n=document.createElement("p");n.innerHTML=K(i,{allowEmpty:!0}),n.innerHTML=n.innerHTML.replace(/<(?!br|img)[^>]+>/gi,""),t.replaceWith(n)}}this.editor.afterEdit()}stripInlineStylesInRange(e){if(!e)return;const t=[],i=document.createTreeWalker(e.commonAncestorContainer,NodeFilter.SHOW_ELEMENT);let n=i.currentNode;for(;n;)e.intersectsNode(n)&&n.nodeType===1&&t.push(n),n=i.nextNode();t.forEach(r=>{r!==this.root&&(r.removeAttribute("style"),/^(SPAN|FONT)$/.test(r.tagName)&&!r.attributes.length&&r.replaceWith(...r.childNodes))})}currentBlock(){var i;const e=z(this.root),t=N((e==null?void 0:e.commonAncestorContainer)||this.root,this.root);return((i=t==null?void 0:t.tagName)==null?void 0:i.toLowerCase())||"p"}currentFontSize(){const e=z(this.root);if(!e)return"";let t=e.startContainer;for(;t&&t!==this.root;){if(t.nodeType===1&&t.style.fontSize)return t.style.fontSize.replace("px","");t=t.parentNode}return""}}function Yt(o,e){var s,a,c;if(!o)return[];const t=new Set;let n=o.startContainer.nodeType===1&&((a=(s=o.startContainer).querySelector)==null?void 0:a.call(s,"a"))||o.startContainer;for(;n&&n!==e;)n.tagName==="A"&&t.add(n),n=n.parentNode;try{(c=o.querySelectorAll)==null||c.call(o,"a").forEach(d=>t.add(d))}catch{}const r=o.commonAncestorContainer;return r.nodeType===1&&r.querySelectorAll("a").forEach(d=>o.intersectsNode(d)?t.add(d):null),[...t]}function Zt(o){var e;return(e=window.CSS)!=null&&e.escape?CSS.escape(o):String(o).replace(/["\\]/g,"\\$&")}class Qt{constructor(e,{limit:t=60,delay:i=400}={}){this.root=e,this.limit=t,this.delay=i,this.stack=[],this.index=-1,this.timer=null,this.locked=!1,this.lastHtml=e.innerHTML}snapshot(e=!1){clearTimeout(this.timer);const t=()=>{const i=this.root.innerHTML;if(i===this.lastHtml)return;this.lastHtml=i;const n={html:i,offset:Fe(this.root)};this.stack=this.stack.slice(0,this.index+1),this.stack.push(n),this.stack.length>this.limit&&this.stack.shift(),this.index=this.stack.length-1};e?t():this.timer=setTimeout(t,this.delay)}flush(){clearTimeout(this.timer),this.snapshot(!0)}apply(e,t){this.locked=!0,this.root.innerHTML=e,this.lastHtml=e,t!=null&&Xt(this.root,t),this.locked=!1}canUndo(){return this.index>0}canRedo(){return this.index>=0&&this.index<this.stack.length-1}undo(){if(!this.canUndo())return!1;clearTimeout(this.timer),this.index-=1;const e=this.stack[this.index];return this.apply(e.html,this.currentOffset(e,"undo")),this.lastHtml=e.html,!0}redo(){if(!this.canRedo())return!1;const e=this.stack[this.index+1];return this.index+=1,this.apply(e.html,this.currentOffset(e,"redo")),this.lastHtml=e.html,!0}currentOffset(e){const t=Fe(this.root);return e.offset}reset(e){clearTimeout(this.timer),this.stack=[{html:e,offset:0}],this.index=0,this.lastHtml=e}destroy(){clearTimeout(this.timer),this.stack=[]}}const ei=/\.(jpe?g|png|gif|webp|bmp|svg|avif)$/i,ti=/\.(mp4|mov|webm|m4v|ogv|avi|mkv)$/i;class ii{constructor(e){this.editor=e,this.options=e.options,this.tasks=new Map,this.input=null}kindOf(e){const t=String(e.type||""),i=String(e.name||"");return t.startsWith("image/")||ei.test(i)?"image":t.startsWith("video/")||ti.test(i)?"video":null}check(e,t){if(!t)return`不支持的文件类型:${e.name||"剪贴板内容"}`;const i=t==="image"?this.options.maxImageSize:this.options.maxVideoSize;return i&&e.size>i?`${e.name} 超出大小限制(${R(i)})`:null}pickFiles(e){this.input||(this.input=l("input",{type:"file",multiple:!0,style:{display:"none"}}),this.input.addEventListener("change",()=>{const t=[...this.input.files||[]];this.input.value="",this.addFiles(t)}),document.body.appendChild(this.input)),this.input.accept=e==="image"?this.options.imageAccept:this.options.videoAccept,this.input.multiple=e==="image",this.input.click()}async addFiles(e){const t=[];for(const i of e){const n=this.kindOf(i),r=this.check(i,n);r?this.editor.toast.warn(r):t.push({file:i,kind:n})}for(const i of t)await this.upload(i.file,i.kind);return t.length}async upload(e,t){const i=t==="image"?this.createImageHolder():this.createVideoHolder();this.editor.focus(),P(this.editor.root,i);const n={id:i.dataset.kId,file:e,kind:t,holder:i,ctrl:new AbortController,previewUrl:URL.createObjectURL(e)};this.tasks.set(n.id,n),this.decorateHolder(n);const r=i.querySelector("[data-k-preview]");return r&&(r.src=n.previewUrl),this.runUpload(n)}async runUpload(e){const t=this.editor,{holder:i,file:n,kind:r}=e;t.emit("uploadstart",{file:n,kind:r}),t.refreshStatus();let s=n;try{r==="image"&&(s=await Ie(n,this.options.image));const a=await t.uploader.upload(s,{signal:e.ctrl.signal,onProgress:(d,h)=>this.updateProgress(i,d,h,s,e)}),c=typeof a=="string"?{url:a}:a;if(!(c!=null&&c.url))throw new Error("上传结果缺少 url");return this.finish(e,{...c,size:s.size}),t.emit("uploaddone",{file:n,kind:r,url:c.url}),c}catch(a){return(a==null?void 0:a.name)==="AbortError"?(this.remove(e),t.emit("uploadcancel",{file:n,kind:r}),null):(this.fail(e,a),t.emit("uploaderror",{file:n,kind:r,error:a}),t.toast.error((a==null?void 0:a.message)||"上传失败"),null)}finally{ee(t.root),t.commitHistory(),t.refreshStatus()}}createImageHolder(){const e=l("figure",{"data-k-media":"image","data-k-id":ie("m"),"data-k-state":"uploading",contenteditable:"false"}),t=l("div.ke-media-holder",{},[l("img",{"data-k-preview":"",alt:"",style:{display:"none"}}),l("div.ke-media-name",{text:"图片上传中…"}),De()]);return t.appendChild(this.actionRow()),e.appendChild(t),e}createVideoHolder(){const e=l("div.ke-video-card",{"data-k-media":"video","data-k-id":ie("m"),"data-k-state":"uploading",contenteditable:"false"}),t=l("div.ke-video-body",{},[l("div.ke-video-head",{},[l("span",{text:"视频上传中…"}),l("span.ke-video-size",{text:""})]),De()]);return t.appendChild(this.actionRow()),e.appendChild(t),e}actionRow(){const e=this;return l("div",{"data-k-actions":"",style:{display:"flex",alignItems:"center",gap:"8px",width:"100%",marginTop:"2px"},onclick:t=>{const i=t.target.closest("[data-k-id]"),n=i&&e.tasks.get(i.dataset.kId);n&&(t.target.matches(".ke-media-cancel")?(n.ctrl.abort(),e.remove(n)):t.target.matches(".ke-media-retry")&&(n.ctrl=new AbortController,e.resetHolder(n),e.runUpload(n)))}},[l("button.ke-media-cancel",{type:"button",text:"取消"})])}decorateHolder(e){const{holder:t,file:i}=e,n=t.querySelector(".ke-media-name");n&&(n.textContent=`${i.name||"未命名"}(${R(i.size)})`);const r=t.querySelector(".ke-video-size");r&&(r.textContent=R(i.size));const s=t.querySelector(".ke-video-head span");s&&e.kind==="video"&&(s.textContent=`${i.name||"视频"} 上传中…`)}resetHolder(e){const t=e.holder;t.dataset.kState="uploading";const i=t.querySelector(".ke-progress i");i&&(i.style.width="0%",i.style.background="");const n=t.querySelector(".ke-media-pct");n&&(n.textContent="0%");const r=t.querySelector("[data-k-actions]");r&&(r.innerHTML='<button class="ke-media-cancel" type="button">取消</button>'),this.decorateHolder(e)}updateProgress(e,t,i,n,r){const s=Math.max(0,Math.min(100,Math.round((t||0)*100))),a=e.querySelector(".ke-progress i");a&&(a.style.width=`${s}%`);const c=e.querySelector(".ke-media-pct");c&&(c.textContent=`${s}%`),r&&this.editor.emit("uploadprogress",{file:r.file,kind:r.kind,percent:s,info:i});const d=e.querySelector(".ke-media-meta");if(!d)return;let h=d.querySelector("[data-k-chunks]");h||(h=l("span",{"data-k-chunks":"",style:{color:"#8a8f99",fontSize:"12px"}}),d.insertBefore(h,d.firstChild)),(i==null?void 0:i.chunks)>1?h.textContent=`${i.chunks} 片 · ${R(i.loaded)}/${R(i.total||n.size)}`:i!=null&&i.speed&&(h.textContent=`${R(i.speed)}/s`)}finish(e,t){const{holder:i,kind:n,file:r}=e,s=t.url;if(i.dataset.kState="done",i.dataset.kUrl=s,i.innerHTML="",n==="image"){const a=l("img",{src:s,alt:oi(r),"data-k-name":r.name||"",draggable:"false"});a.addEventListener("dblclick",()=>J(a.src)),i.appendChild(a)}else{const a=l("video",{src:s,controls:"",playsinline:"",preload:"metadata","data-k-name":r.name||""}),c=l("div.ke-video-body",{},[l("div.ke-video-head",{},[l("span",{text:r.name||"视频"}),l("span.ke-video-size",{text:R(t.size||r.size)})]),a]);i.appendChild(c)}e.previewUrl&&URL.revokeObjectURL(e.previewUrl),this.tasks.delete(e.id),this.editor.refreshStatus()}fail(e,t){const i=e.holder;i.dataset.kState="error";const n=i.querySelector(".ke-progress i");n&&(n.style.background="#e53e3e");const r=i.querySelector("[data-k-actions]");r&&(r.innerHTML="",r.appendChild(l("span.ke-media-error",{text:(t==null?void 0:t.message)||"上传失败",style:{marginRight:"auto",fontSize:"12px"}})),r.appendChild(l("button.ke-media-retry",{type:"button",text:"重试"})),r.appendChild(l("button.ke-media-cancel",{type:"button",text:"移除"})))}remove(e){var t;(t=e.holder)==null||t.remove(),e.previewUrl&&URL.revokeObjectURL(e.previewUrl),this.tasks.delete(e.id),ee(this.editor.root),this.editor.refreshStatus()}taskFromNode(e){var i;const t=(i=e==null?void 0:e.closest)==null?void 0:i.call(e,"[data-k-id]");return t?this.tasks.get(t.dataset.kId):null}cancelAll(){for(const e of[...this.tasks.values()])e.ctrl.abort(),this.remove(e)}insertFromUrl(e,t,i=""){const n=e==="image"?this.insertImageUrl(t,i):this.insertVideoUrl(t,i||"网络视频");return this.editor.toast.ok(e==="image"?"已插入网络图片":"已插入网络视频"),this.editor.emit("insertmedia",{kind:e,url:t,node:n}),n}insertImageUrl(e,t=""){const i=l("img",{src:e,alt:t||"",draggable:"false"});i.addEventListener("dblclick",()=>J(i.src));const n=l("figure",{"data-k-media":"image","data-k-state":"done","data-k-url":e,contenteditable:"false"},[i]);return P(this.editor.root,n),this.editor.commitHistory(),n}insertVideoUrl(e,t="视频"){const i=l("video",{src:e,controls:"",playsinline:"",preload:"metadata"}),n=l("div.ke-video-card",{"data-k-media":"video","data-k-state":"done","data-k-url":e,contenteditable:"false"},[l("div.ke-video-body",{},[l("div.ke-video-head",{},[l("span",{text:t})]),i])]);return P(this.editor.root,n),this.editor.commitHistory(),n}destroy(){var e;this.cancelAll(),(e=this.input)==null||e.remove(),this.input=null}}function oi(o){return String(o.name||"").replace(/\.[^.]+$/,"")}function De(){return l("div.ke-media-meta",{},[l("div.ke-progress",{},[l("i",{style:{width:"0%"}})]),l("span.ke-media-pct",{text:"0%"})])}async function Ie(o,e={}){var s,a;const t=e==null?void 0:e.compress;if(!t||!/^image\/(jpeg|jpg|png|webp)$/i.test(o.type))return o;const{maxWidth:i=1440,quality:n=.85,minSize:r=300*1024}=typeof t=="object"?t:{};if(o.size<r)return o;try{const c=await createImageBitmap(o);if(c.width<=i)return(s=c.close)==null||s.call(c),o;const d=document.createElement("canvas");d.width=i,d.height=Math.round(c.height*i/c.width),d.getContext("2d").drawImage(c,0,0,d.width,d.height),(a=c.close)==null||a.call(c);const h=await new Promise(p=>d.toBlob(p,"image/jpeg",n));return!h||h.size>=o.size?o:new File([h],String(o.name).replace(/\.\w+$/,".jpg"),{type:"image/jpeg",lastModified:o.lastModified})}catch{return o}}function ke(o){return`${Ue(o.size)}-${ni(o.lastModified)}-${ri(o.name)}`}async function qe(o){var a;if(!((a=globalThis.crypto)!=null&&a.subtle))return ke(o);const e=256*1024,t=[o.slice(0,e)];o.size>e&&t.push(o.slice(o.size-e));const i=new Uint8Array(t.reduce((c,d)=>c+d.size,0));let n=0;for(const c of t){const d=new Uint8Array(await c.arrayBuffer());i.set(d,n),n+=d.length}const r=await crypto.subtle.digest("SHA-256",i);return`${Array.from(new Uint8Array(r)).map(c=>c.toString(16).padStart(2,"0")).join("").slice(0,24)}-${Ue(o.size)}`}const Ue=o=>Number(o).toString(16),ni=o=>Number(o||0).toString(16),ri=o=>String(o).replace(/[^\w.-]/g,"").slice(0,24);function si(o="fast"){return o==="strong"||o==="sha256"?qe:typeof o=="function"?o:async e=>ke(e)}const ai=1024*1024;class j{constructor(e,t={}){if(!e||typeof e.put!="function")throw new Error("[KEditor] uploader 需要提供 put() 方法,参见 docs/upload-adapter.md");this.adapter=e,this.chunkSize=Math.max(64*1024,t.chunkSize||ai),this.concurrency=Math.max(1,t.concurrency||3),this.retries=t.retries===void 0?2:Math.max(0,t.retries),this.retryDelay=t.retryDelay??600,this.fingerprint=si(t.fingerprint||"fast"),this.slice=t.slice}async upload(e,t={}){var x,g,$,Qe,et,tt;const{onProgress:i,onChunk:n,signal:r}=t;if(this.adapter.simple)return this.uploadSimple(e,t);const s=Math.max(1,Math.ceil(e.size/this.chunkSize)),a={name:e.name||"blob",size:e.size,type:e.type||ci(e.name),lastModified:e.lastModified||0,fingerprint:await this.fingerprint(e),chunkSize:this.chunkSize,totalChunks:s},c=await((g=(x=this.adapter).init)==null?void 0:g.call(x,a,{signal:r}))||{};if(c.url)return i==null||i(1,{percent:100,loaded:e.size,total:e.size,chunks:s,instant:!0}),{url:c.url,instant:!0,chunks:0,size:e.size,name:a.name,key:c.key};const d=c.uploadId||a.fingerprint,h=new Set((c.uploadedChunks||c.uploaded||[]).map(Number));let p=0;for(const w of h)p+=Math.min(this.chunkSize,e.size-w*this.chunkSize);const u=[];for(let w=0;w<s;w+=1)h.has(w)||u.push(w);const k=new Array(s);let f=h.size;const y=Date.now(),v=()=>{const w=(Date.now()-y)/1e3;i==null||i(e.size?p/e.size:1,{percent:Math.min(100,Math.round(p/Math.max(1,e.size)*100)),loaded:p,total:e.size,chunks:s,uploadedChunks:f,speed:w>0?p/w:0})};v();let C=0,S=null;const A=async()=>{for(;C<u.length;){if(r!=null&&r.aborted)throw new DOMException("已取消上传","AbortError");const w=u[C++],te=this.slice?this.slice(e,w,this.chunkSize):e.slice(w*this.chunkSize,(w+1)*this.chunkSize);let ye=0;for(;;)try{const L=await this.adapter.put({uploadId:d,index:w,total:s,chunkSize:this.chunkSize,blob:te,file:e,meta:a,signal:r,size:te.size});L!=null&&L.url&&(k[w]=L),p+=te.size,f+=1,n==null||n({index:w,total:s,size:te.size}),v();break}catch(L){if((L==null?void 0:L.name)==="AbortError")throw L;if(ye+=1,ye>this.retries)throw S=L,new Error(`分片 ${w+1}/${s} 上传失败:${(L==null?void 0:L.message)||L}`);await li(this.retryDelay*ye,r)}}},H=Array.from({length:Math.max(1,Math.min(this.concurrency,u.length))},A);try{await Promise.all(H)}catch(w){throw await((Qe=($=this.adapter).abort)==null?void 0:Qe.call($,{uploadId:d,meta:a,error:w}).catch(()=>{})),w}if(S)throw S;const E=await((tt=(et=this.adapter).complete)==null?void 0:tt.call(et,{uploadId:d,meta:a,total:s,uploaded:f,chunkResults:k,file:e}))||{},m=E.url;if(!m)throw new Error("[KEditor] uploader.complete() 未返回 url");return{url:m,chunks:s,size:e.size,name:a.name,key:E.key,poster:E.poster,duration:E.duration,raw:E}}async uploadSimple(e,t={}){const{onProgress:i,signal:n}=t,r=Date.now(),s=await this.adapter.upload(e,{signal:n,onProgress:(c,d)=>{const h=d?c/d:0,p=(Date.now()-r)/1e3;i==null||i(h,{percent:Math.round(h*100),loaded:c,total:d||e.size,chunks:1,uploadedChunks:h>=1?1:0,speed:p>0?c/p:0})}}),a=typeof s=="string"?s:s==null?void 0:s.url;if(!a)throw new Error("[KEditor] uploader.upload() 未返回 url");return{url:a,chunks:1,size:e.size,name:e.name,key:typeof s=="object"?s.key:void 0,raw:s}}destroy(){var e,t;(t=(e=this.adapter).destroy)==null||t.call(e)}}const li=(o,e)=>new Promise((t,i)=>{const n=setTimeout(()=>{e==null||e.removeEventListener("abort",r),t()},o),r=()=>{clearTimeout(n),i(new DOMException("已取消上传","AbortError"))};e==null||e.addEventListener("abort",r,{once:!0})});function ci(o=""){var i;const e=(i=String(o).split(".").pop())==null?void 0:i.toLowerCase();return{jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",mp4:"video/mp4",mov:"video/quicktime",webm:"video/webm",m4v:"video/x-m4v"}[e]||"application/octet-stream"}function We(o){return{simple:!0,async upload(e,t={}){const i=await o(di(e),t);return typeof i=="string"?{url:i}:i}}}function di(o,e="blob",t=o.type){return o instanceof File?o:new File([o],e,{type:t})}const ge=o=>new Promise(e=>setTimeout(e,o)),hi=(o,e=.4)=>o*(1-e+Math.random()*e*2);function _e(o={}){const{latency:e=160,speed:t=12,onEvent:i=null,reuseObjectUrl:n=!0,failFirstChunk:r=!1}=o,s=new Map,a=new Map,c=new Map;let d=r;const h=(p,u)=>i==null?void 0:i(p,{...u,at:Date.now()});return{name:"mock",async init(p){h("init",p),await ge(120);const u=s.get(p.fingerprint);if(u)return h("instant",{name:p.name,url:u.url}),{url:u.url,key:p.fingerprint,instant:!0};const k=a.get(p.fingerprint)||new Set;return a.set(p.fingerprint,k),{uploadId:p.fingerprint,uploadedChunks:[...k]}},async put({uploadId:p,index:u,total:k,size:f,blob:y}){if(d&&u===0){d=!1,h("chunk-error",{index:u,total:k,message:"mock: 模拟首个分片网络异常"});const S=new Error("mock: 模拟首个分片网络异常");throw S.retryable=!0,S}const v=Math.max(40,hi(e+f/(t*1024/8)/8,.35));await ge(v);const C=a.get(p)||new Set;return C.add(u),a.set(p,C),h("chunk",{index:u,total:k,size:f,blobSize:y==null?void 0:y.size}),{etag:`${p}-${u}`}},async complete({uploadId:p,meta:u,file:k}){await ge(140);let f=c.get(u.fingerprint);if(!f||!n){const y=k instanceof File?k:new File([k],u.name,{type:u.type});f=URL.createObjectURL(y),c.set(u.fingerprint,f)}return s.set(u.fingerprint,{url:f,name:u.name,size:u.size,type:u.type}),a.delete(p),h("complete",{name:u.name,url:f,chunks:u.totalChunks,size:u.size}),{url:f,key:u.fingerprint}},async abort({uploadId:p}){h("abort",{uploadId:p})},list:()=>[...s.entries()].map(([p,u])=>({key:p,...u})),reset:()=>{s.clear(),a.clear()}}}function Ve(o={}){const{initUrl:e,chunkUrl:t,completeUrl:i,abortUrl:n,mode:r="raw",fieldName:s="file",headers:a={},withCredentials:c=!1,parse:d=k=>(k==null?void 0:k.data)||k||{},chunkUrlFor:h}=o,p=()=>typeof a=="function"?a()||{}:a||{},u=async(k,f={})=>{const y=await fetch(k,{credentials:c?"include":"same-origin",...f});if(!y.ok)throw new Error(`HTTP ${y.status} ${y.statusText}`);const v=await y.text();if(!v)return{};try{return d(JSON.parse(v))}catch{throw new Error(`服务端返回非 JSON 数据:${v.slice(0,80)}`)}};return{name:"http",async init(k,{signal:f}){if(!e)throw new Error("[KEditor] httpAdapter 缺少 initUrl");return u(e,{method:"POST",signal:f,headers:{"Content-Type":"application/json",...p()},body:JSON.stringify({fileName:k.name,fileSize:k.size,fileType:k.type,lastModified:k.lastModified,identifier:k.fingerprint,chunkSize:k.chunkSize,totalChunks:k.totalChunks})})},async put({uploadId:k,index:f,total:y,blob:v,meta:C,signal:S}){if(!t)throw new Error("[KEditor] httpAdapter 缺少 chunkUrl");const A=typeof h=="function"?h({uploadId:k,index:f}):t;if(r==="formdata"){const m=new FormData;return m.append(s,v,`${C.name}.part${f}`),m.append("uploadId",k),m.append("identifier",C.fingerprint),m.append("index",String(f)),m.append("total",String(y)),m.append("filename",C.name),u(A,{method:"POST",body:m,signal:S,headers:p()})}const H=A.includes("?")?"&":"?",E=`${A}${H}uploadId=${encodeURIComponent(k)}&index=${f}&total=${y}&filename=${encodeURIComponent(C.name)}`;return u(E,{method:"PUT",body:v,signal:S,headers:{"Content-Type":"application/octet-stream","X-Chunk-Index":String(f),...p()}})},async complete({uploadId:k,meta:f,total:y}){if(!i)throw new Error("[KEditor] httpAdapter 缺少 completeUrl");return u(i,{method:"POST",headers:{"Content-Type":"application/json",...p()},body:JSON.stringify({uploadId:k,identifier:f.fingerprint,fileName:f.name,fileSize:f.size,fileType:f.type,chunkSize:f.chunkSize,totalChunks:y})})},async abort({uploadId:k}){n&&await u(n,{method:"POST",headers:{"Content-Type":"application/json",...p()},body:JSON.stringify({uploadId:k})}).catch(()=>{})}}}function Ke(o="mock",e={}){if(o instanceof j)return o;if(typeof o=="function"&&!o.put)return new j(We(o),e);if(o&&typeof o=="object"&&!(o instanceof j)){if(typeof o.put=="function"||typeof o.upload=="function")return new j(o,{...e,...Ge(o)});if(o.type==="http")return new j(Ve(o),{...e,...Ge(o)})}return new j(_e(typeof o=="object"?o:{}),e)}const Ge=o=>{const e={};for(const t of["chunkSize","concurrency","retries","fingerprint"])o[t]!==void 0&&(e[t]=o[t]);return e};function pi(o){o.root.addEventListener("paste",async e=>{if(o.readOnly||!o.options.paste.enabled)return;const t=e.clipboardData;if(!t)return;e.preventDefault();const i=ui(t);if(i.length){o.options.paste.uploadFiles?(await o.media.addFiles(i),o.toast.show(`已上传 ${i.length} 个文件`)):o.toast.warn("当前配置不允许粘贴上传文件");return}const n=t.getData("text/html"),r=t.getData("text/plain");if(n&&o.options.paste.clean){let s=Me(n)?ze(n):n;s=K(s,{allowEmpty:!0}),o.options.paste.localizeImages&&(s=await ki(o,s)),o.commands.insertHTML(s,{clean:!1}),Me(n)&&o.toast.show("已清理 Word/WPS 格式")}else if(r){const s=r.split(/\r?\n/).map(a=>`<p>${ce(a)||"<br>"}</p>`).join("");o.commands.insertHTML(s,{clean:!1})}})}function ui(o){var t,i;const e=[];if((t=o.items)!=null&&t.length){for(const n of o.items)if(n.kind==="file"){const r=n.getAsFile();r&&e.push(Xe(r,e.length))}}return!e.length&&((i=o.files)!=null&&i.length)&&e.push(...Array.from(o.files).map((n,r)=>Xe(n,r))),e}function Xe(o,e){if(o.name&&o.name!=="image.png")return o;const t=(o.type.split("/")[1]||"png").replace("jpeg","jpg").replace("+xml",""),i=new Date().toISOString().slice(11,19).replace(/:/g,"");return new File([o],`pasted-${i}-${e}.${t}`,{type:o.type,lastModified:o.lastModified})}function fi(o){const e=o.root;let t=0;const i=n=>{var r;return Array.from(((r=n.dataTransfer)==null?void 0:r.types)||[]).includes("Files")};e.addEventListener("dragenter",n=>{!i(n)||o.readOnly||(n.preventDefault(),t+=1,o.el.classList.add("ke-is-dragover"))}),e.addEventListener("dragover",n=>{!i(n)||o.readOnly||(n.preventDefault(),n.dataTransfer.dropEffect="copy")}),e.addEventListener("dragleave",n=>{i(n)&&(t=Math.max(0,t-1),t===0&&o.el.classList.remove("ke-is-dragover"))}),e.addEventListener("drop",async n=>{if(!i(n)||o.readOnly)return;n.preventDefault(),t=0,o.el.classList.remove("ke-is-dragover"),mi(o,n);const r=[...n.dataTransfer.files||[]];if(r.length&&o.options.paste.uploadFiles){const s=await o.media.addFiles(r);s&&o.toast.show(`已上传 ${s} 个文件`)}})}function mi(o,e){let t=null;if(document.caretRangeFromPoint)t=document.caretRangeFromPoint(e.clientX,e.clientY);else if(document.caretPositionFromPoint){const i=document.caretPositionFromPoint(e.clientX,e.clientY);i&&(t=document.createRange(),t.setStart(i.offsetNode,i.offset),t.collapse(!0))}if(t&&o.root.contains(t.commonAncestorContainer)){const i=window.getSelection();i.removeAllRanges(),i.addRange(t)}else o.focus()}async function ki(o,e){const t=new DOMParser().parseFromString(`<div>${e}</div>`,"text/html"),i=[...t.body.querySelectorAll("img")].filter(n=>/^https?:/i.test(n.getAttribute("src")||""));for(const n of i)try{const r=await fetch(n.src,{mode:"cors"});if(!r.ok)continue;const s=await r.blob(),a=new File([s],n.alt||`remote-${Date.now()}.jpg`,{type:s.type||"image/jpeg"}),c=await o.media.upload(a,"image");n.remove(),c!=null&&c.url&&o.toast.show("外链图片已本地化")}catch{}return t.body.innerHTML.trim()}const Je=1024,be=1024*Je,F={value:"",placeholder:"开始撰写内容,支持拖拽 / 粘贴图片与视频…",height:460,minHeight:320,primaryColor:"#07c160",paperWidth:677,paperMode:"fluid",paperGap:24,paperMaxWidth:0,toolbar:Q,customButtons:[],hideToolbar:!1,hideStatusbar:!1,readOnly:!1,autofocus:!1,maxLength:0,wordCount:!0,sanitize:!0,historyLimit:60,uploader:"mock",upload:{chunkSize:be,concurrency:3,retries:2,fingerprint:"fast"},image:{compress:{maxWidth:1440,quality:.85,minSize:300*Je}},maxImageSize:20*be,maxVideoSize:512*be,imageAccept:"image/png,image/jpeg,image/gif,image/webp,image/bmp,image/svg+xml,image/avif",videoAccept:"video/mp4,video/quicktime,video/webm,video/x-m4v,video/ogg",paste:{enabled:!0,clean:!0,uploadFiles:!0,localizeImages:!1},onChange:null,onReady:null,onError:null,onUpload:null,beforeUpload:null,toolbarFloat:!1};let gi=0;class X{constructor(e,t={}){it(),this.options=yi(t),this.id=`ke-${gi+=1}`,this.el=xi(e,this.id),this.el.__keditor__=this;const i=this.el.innerHTML;this.emitters=new Map,this.domListeners=[],this.destroyed=!1,this.sourceMode=!1,this.previewMode=!1,this.fullscreen=!1,this.readOnly=!1,this.buildDOM(),this.toast=new vt,this.popover=new st(this.el),this.commands=new Jt(this),this.uploader=Ke(this.options.uploader,this.options.upload),this.media=bi(this),this.history=new Qt(this.root,{limit:this.options.historyLimit}),this.toolbar=new Kt(this,this.options.toolbar,this.options.customButtons),this.source=new xt(this),this.previewPanel=new yt(this),this.bubble=new wt(this),this.mainEl.append(this.source.el,this.previewPanel.el),this.applyTheme(),this.setContent(this.options.value||i,{sanitize:this.options.sanitize,silent:!0}),this.bindEvents(),this.setReadOnly(this.options.readOnly),this.refresh(),this.refreshStatus(),this.history.reset(this.root.innerHTML),queueMicrotask(()=>{var n,r;this.destroyed||(this.emit("ready",{editor:this}),(r=(n=this.options).onReady)==null||r.call(n,this),this.options.autofocus&&this.focus())})}buildDOM(){this.el.classList.add("ke"),this.el.id=this.el.id||this.id,this.el.innerHTML="",this.tbEl=l("div.ke-tb",{role:"toolbar","aria-label":"编辑器工具栏"}),this.scrollEl=l("div.ke-scroll"),this.paperEl=l("div.ke-paper"),this.root=l("div.ke-content",{contenteditable:this.readOnly?"false":"true",role:"textbox","aria-multiline":"true",spellcheck:"false","data-placeholder":this.options.placeholder,"data-ke-root":""}),this.root.style.minHeight=`${this.options.minHeight}px`,this.paperEl.appendChild(this.root),this.scrollEl.appendChild(this.paperEl),this.mainEl=l("div.ke-main",{},[this.scrollEl]),this.statusEl=Ci(this),this.dropzoneEl=l("div.ke-dropzone",{},[l("span",{text:"松开即可上传(分片传输)"})]),this.options.hideToolbar||this.el.appendChild(this.tbEl),this.el.appendChild(this.mainEl),this.options.hideStatusbar||this.el.appendChild(this.statusEl),this.el.appendChild(this.dropzoneEl),this.options.height&&(this.scrollEl.style.height=`${this.options.height}px`,this.scrollEl.style.maxHeight=`${this.options.height}px`),this.paperEl.style.setProperty("--ke-min-height",`${this.options.minHeight}px`),this.applyPaper()}applyPaper(){const{paperWidth:e,paperMode:t,paperGap:i,paperMaxWidth:n}=this.options;this.paperEl.style.setProperty("--ke-paper",`${e}px`),this.paperEl.style.setProperty("--ke-paper-gap",`${i}px`),n>0?this.paperEl.style.setProperty("--ke-paper-max",`${n}px`):this.paperEl.style.removeProperty("--ke-paper-max"),this.paperEl.classList.toggle("ke-is-fluid",t!=="fixed")}setPaper(e={}){return e.width!==void 0&&(this.options.paperWidth=I(Number(e.width)||0,200,8e3)),e.mode!==void 0&&(this.options.paperMode=e.mode==="fixed"?"fixed":"fluid"),e.gap!==void 0&&(this.options.paperGap=I(Number(e.gap)||0,0,600)),e.maxWidth!==void 0&&(this.options.paperMaxWidth=Math.max(0,Number(e.maxWidth)||0)),this.applyPaper(),{...this.paperOptions()}}paperOptions(){const{paperWidth:e,paperMode:t,paperGap:i,paperMaxWidth:n}=this.options;return{width:e,mode:t,gap:i,maxWidth:n}}applyTheme(){this.options.primaryColor&&this.el.style.setProperty("--ke-primary",this.options.primaryColor)}bindEvents(){const e=ot(()=>this.emitChange(),160);this.bind(this.root,"input",()=>{this.history.snapshot(),this.refreshStatus(),this.togglePlaceholder(),e(),this.enforceMaxLength()}),this.bind(this.root,"keydown",t=>this.handleKeydown(t)),this.bind(this.root,"blur",()=>{this.history.flush(),this.el.classList.remove("ke-is-focus"),this.emit("blur")}),this.bind(this.root,"focus",()=>{this.el.classList.add("ke-is-focus"),this.emit("focus")}),this.bind(this.root,"click",t=>this.handleContentClick(t)),this.bind(this.root,"dblclick",t=>{const i=t.target.closest("img");i&&this.root.contains(i)&&J(i.src)}),pi(this),fi(this),this.selectionHandler=()=>{!this.root.contains(document.activeElement)&&document.activeElement!==this.root||(this.refresh(),this.syncBubble())},document.addEventListener("selectionchange",this.selectionHandler),this.scrollHandler=()=>this.bubble.position(),this.bind(this.scrollEl,"scroll",this.scrollHandler),window.addEventListener("resize",this.scrollHandler)}bind(e,t,i){return e.addEventListener(t,i),this.domListeners.push({node:e,type:t,handler:i}),i}handleKeydown(e){const t=e.metaKey||e.ctrlKey,i=e.key.toLowerCase();if(t&&i==="z"){e.preventDefault(),e.shiftKey?this.redo():this.undo();return}if(t&&i==="y"){e.preventDefault(),this.redo();return}if(t&&["b","i","u"].includes(i)){e.preventDefault(),this.commands.toggleMark({b:"bold",i:"italic",u:"underline"}[i]),this.refresh();return}if(t&&e.shiftKey&&i==="k"){e.preventDefault(),this.toggleSource();return}if(t&&i==="k"){e.preventDefault(),this.toolbar.openLink();return}if(t&&i==="s"){e.preventDefault(),this.emit("save",{html:this.getHTML()});return}if(e.key==="Escape"){this.popover.close(),this.bubble.hide(),this.previewMode&&this.closePreview();return}(e.key==="Backspace"||e.key==="Delete")&&this.bubble.node&&(e.preventDefault(),this.bubble.remove())}handleContentClick(e){const t=e.target.closest("[data-k-media]");if(t&&this.root.contains(t)){this.selectMedia(t);return}this.clearMediaSelection(),this.bubble.hide()}selectMedia(e){this.clearMediaSelection(),e.classList.add("ke-is-selected-media"),this.bubble.show(e),this.refreshStatus()}clearMediaSelection(){this.root.querySelectorAll(".ke-is-selected-media").forEach(e=>e.classList.remove("ke-is-selected-media")),this.bubble.hide()}syncBubble(){!this.bubble.node||!this.root.contains(this.bubble.node)?this.bubble.hide():this.bubble.position()}getState(){var a,c,d;const e=z(this.root),t=N((e==null?void 0:e.commonAncestorContainer)||this.root,this.root),i=e?Si(e,this.root):null,n=(a=this.bubble)==null?void 0:a.node,r=n&&((c=n.dataset)==null?void 0:c.kMedia)==="image"?n.querySelector("img"):null,s=r?oe(r):Ei(e,t);return{bold:this.queryState("bold"),italic:this.queryState("italic"),underline:this.queryState("underline"),strikeThrough:this.queryState("strikeThrough"),ul:this.queryState("insertUnorderedList"),ol:this.queryState("insertOrderedList"),align:s,block:((d=t==null?void 0:t.tagName)==null?void 0:d.toLowerCase())||"p",fontSize:this.commands.currentFontSize(),linkUrl:i?i.getAttribute("href"):"",linkTarget:i?i.getAttribute("target")==="_blank":!1,selectionText:e?e.toString():"",canUndo:this.history.canUndo(),canRedo:this.history.canRedo(),source:this.sourceMode,preview:this.previewMode,fullscreen:this.fullscreen,readOnly:this.readOnly}}queryState(e){var t;if(!this.root.contains(((t=window.getSelection())==null?void 0:t.anchorNode)||null))return!1;try{return document.queryCommandState(e)}catch{return!1}}refresh(){if(!this.destroyed)try{this.toolbar.refresh(this.getState())}catch{}}refreshStatus(){const e=this.statusApi;e&&e.update(this.counts())}counts(){const e=Te(this.root.innerHTML);return{chars:e.replace(/\s/g,"").length,words:Li(e),images:this.root.querySelectorAll("img").length,videos:this.root.querySelectorAll('[data-k-media="video"] video, video').length,uploading:this.media?this.media.tasks.size:0}}togglePlaceholder(){const e=!this.root.textContent.trim()&&!this.root.querySelector("img,video,hr,table,iframe");this.root.classList.toggle("ke-is-empty",e)}enforceMaxLength(){var i,n;const e=this.options.maxLength;if(!e)return;const{chars:t}=this.counts();t>e?(this.toast.warn(`已超过建议字数 ${e}`),(i=this.statusEl)==null||i.classList.add("ke-is-over")):(n=this.statusEl)==null||n.classList.remove("ke-is-over")}getHTML({clean:e=!0}={}){const t=this.root.innerHTML;return e?Ze(t):t}getText(){return Te(this.root.innerHTML)}getJSON(){return{html:this.getHTML(),text:this.getText(),counts:this.counts()}}setContent(e,{sanitize:t=this.options.sanitize,silent:i=!1}={}){const n=K(e||"<p><br></p>",{allowEmpty:!0});return this.root.innerHTML=n||"<p><br></p>",this.afterEdit({silent:i}),i||this.history.snapshot(!0),this.togglePlaceholder(),this}appendHTML(e){const t=document.createRange();t.selectNodeContents(this.root),t.collapse(!1);const i=window.getSelection();return i.removeAllRanges(),i.addRange(t),this.commands.insertHTML(e),this}clear(){return this.media.cancelAll(),this.setContent("<p><br></p>"),this.focus(),this}afterEdit({silent:e=!1}={}){this.history.snapshot(),this.refreshStatus(),this.togglePlaceholder(),e||this.emitChange()}commitHistory(){this.history.snapshot(!0),this.refreshStatus(),this.emitChange()}emitChange(){var e,t;this.emit("change",{html:this.getHTML(),text:this.getText()}),(t=(e=this.options).onChange)==null||t.call(e,this.getHTML(),this)}focus(){if(this.readOnly||this.sourceMode)return this.sourceMode&&this.source.code.focus(),this;this.root.focus();const e=window.getSelection();if(!e||e.rangeCount===0||!this.root.contains(e.anchorNode)){const t=document.createRange(),i=this.root.firstElementChild||this.root;t.selectNodeContents(i),t.collapse(!1),e.removeAllRanges(),e.addRange(t)}return this}blur(){return this.root.blur(),this}saveSelection(){const e=z(this.root);return this.savedRange=e?e.cloneRange():null,this}restoreSelection(){this.root.focus();const e=window.getSelection();return this.savedRange&&this.root.contains(this.savedRange.startContainer)&&this.root.contains(this.savedRange.endContainer)?(e.removeAllRanges(),e.addRange(this.savedRange),this):this.focus()}setReadOnly(e){return this.readOnly=!!e,this.root.setAttribute("contenteditable",this.readOnly?"false":"true"),this.el.classList.toggle("ke-is-readonly",this.readOnly),this.refresh(),this}undo(){return this.history.flush(),this.history.undo()?(this.afterEdit({silent:!1}),this.refresh(),this):(this.toast.show("没有可撤销的操作"),this)}redo(){return this.history.redo()?(this.afterEdit(),this.refresh(),this):(this.toast.show("没有可重做的操作"),this)}upload(e,t=this.media.kindOf(e)){if(!t)throw new Error("[KEditor] 不支持的文件类型");return this.media.upload(e,t)}insertImage(e,t=""){return this.media.insertImageUrl(e,t)}insertVideo(e,t="视频"){return this.media.insertVideoUrl(e,t)}cancelUploads(){return this.media.cancelAll(),this}addButton(e,t){return this.toolbar.addButton(e,t)}moveButton(e,t){return this.toolbar.moveButton(e,t)}removeButton(e){return this.toolbar.removeButton(e)}setButtonOptions(e,t){return this.toolbar.setButtonOptions(e,t)}getButtonValue(e){return this.toolbar.getButtonValue(e)}setButtonValue(e,t){return this.toolbar.setButtonValue(e,t)}reportError(e,t){var r,s,a;const i=t&&t.message?t.message:String(t),n={type:e,error:t instanceof Error?t:new Error(i),message:i};return(r=this.toast)==null||r.error(i),this.emit("error",n),(a=(s=this.options).onError)==null||a.call(s,n),this}toggleSource(){return this.sourceMode?this.exitSource():this.enterSource(),this.sourceMode}enterSource(){this.sourceMode||(this.history.flush(),this.sourceMode=!0,this.el.classList.add("ke-is-source"),this.clearMediaSelection(),this.source.show(this.getHTML({clean:!0})),this.previewPanel.hide(),this.previewMode=!1,this.refresh(),this.emit("sourcechange",{mode:"source"}))}exitSource(){this.sourceMode&&(this.source.apply({silent:!0}),this.sourceMode=!1,this.el.classList.remove("ke-is-source"),this.source.hide(),this.focus(),this.refresh(),this.emit("sourcechange",{mode:"visual"}))}togglePreview(){return this.previewMode?this.closePreview():this.openPreview(),this.previewMode}openPreview(){this.previewMode=!0,this.previewPanel.show(Mi(this.getHTML())),this.refresh()}closePreview(){this.previewMode=!1,this.previewPanel.hide(),this.refresh()}toggleFullscreen(){return this.fullscreen=!this.fullscreen,this.el.classList.toggle("ke-is-fullscreen",this.fullscreen),document.body.style.overflow=this.fullscreen?"hidden":"",this.refresh(),this.fullscreen}on(e,t){return this.addListener(e,t)}off(e,t){return this.removeListener(e,t)}emit(e,t={}){var n,r,s,a;const i=this.emitters.get(e)||[];for(const c of i)try{c(t)}catch(d){(r=(n=this.options).onError)==null||r.call(n,d)}return e.startsWith("upload")&&((a=(s=this.options).onUpload)==null||a.call(s,{stage:e,...t})),this}addListener(e,t){return this.emitters.has(e)||this.emitters.set(e,[]),this.emitters.get(e).push(t),()=>this.removeListener(e,t)}removeListener(e,t){const i=this.emitters.get(e)||[],n=i.indexOf(t);return n>=0&&i.splice(n,1),this}get element(){return this.root}get editorElement(){return this.el}destroy(){if(!this.destroyed){this.destroyed=!0,this.media.destroy(),this.history.destroy(),this.popover.destroy(),this.source.destroy(),this.previewPanel.destroy(),this.bubble.destroy(),this.toolbar.destroy(),this.toast.destroy();for(const{node:e,type:t,handler:i}of this.domListeners)e.removeEventListener(t,i);document.removeEventListener("selectionchange",this.selectionHandler),this.scrollEl.removeEventListener("scroll",this.scrollHandler),window.removeEventListener("resize",this.scrollHandler),this.fullscreen&&(document.body.style.overflow=""),this.el.__keditor__===this&&(this.el.__keditor__=null),this.el.innerHTML="",this.el.classList.remove("ke","ke-is-fullscreen","ke-is-readonly"),this.el.removeAttribute("style"),this.emitters.clear()}}static create(e,t){return new X(e,t)}}function bi(o){const e=new ii(o),t=e.upload.bind(e);return e.upload=async(i,n)=>{const r=o.options.beforeUpload;let s=i;return r&&(s=await r(i,n),s===!1)?null:t(s,n)},e.replaceNode=async(i,n)=>{const r=i.dataset.kMedia==="video"?"video":"image",s=document.createRange();s.setStartBefore(i),s.collapse(!0);const a=window.getSelection();a.removeAllRanges(),a.addRange(s);const c=await e.upload(n,r);return i.remove(),o.commitHistory(),c},e}function xi(o,e){if(typeof o=="string"){const t=document.querySelector(o);if(!t)throw new Error(`[KEditor] 找不到挂载节点:${o}`);return t}if(o instanceof HTMLElement)return o;if((o==null?void 0:o.$el)instanceof HTMLElement)return o.$el;throw new Error(`[KEditor] 无效的挂载目标(${typeof o})`)}function yi(o){const e={...F,...o};return e.image={...F.image,...o.image||{}},e.paste={...F.paste,...o.paste||{}},e.upload={...F.upload,...o.upload||{}},e.customButtons=Be(o.customButtons),Array.isArray(o.toolbar)&&(e.toolbar=o.toolbar),o.toolbar===!1&&(e.toolbar=[]),o.toolbar===!0&&(e.toolbar=Q),e.customButtons.length&&o.toolbar!==!1&&(e.toolbar=wi(e.toolbar,e.customButtons)),e.height=I(e.height??460,0,4e3),e.paperWidth=I(Number(e.paperWidth)||F.paperWidth,200,8e3),e.paperMode=e.paperMode==="fixed"?"fixed":"fluid",e.paperGap=Number.isFinite(Number(e.paperGap))?I(Number(e.paperGap),0,600):F.paperGap,e.paperMaxWidth=Math.max(0,Number(e.paperMaxWidth)||0),e}const vi=o=>o!=="|"&&o!==":tail";function wi(o,e){const t=[...o],i=[];for(const n of e)if(!t.includes(n.name)){if(n.position==null){i.push(n.name);continue}t.splice(Ye(t,n.position),0,n.name)}return i.length&&t.splice(Ye(t,null),0,"|",...i),t}function Ye(o,e){const t=(()=>{const s=o.indexOf(":tail");return s<0?o.length:s})();if(e==null||e==="end")return t;if(e==="start")return 0;if(e==="tail")return o.length;if(typeof e=="number"){let s=0;for(let a=0;a<o.length;a++)if(vi(o[a])){if(s===Math.max(0,Math.floor(e)))return a;s++}return t}const i=!!(e&&typeof e=="object"&&e.after),n=String(typeof e=="string"?e:(i?e.after:e.before)||""),r=o.indexOf(n);return r<0?t:i?r+1:r}function Ci(o){const e=l("b",{text:"0"}),t=l("b",{text:"0"}),i=l("b",{text:"0"}),n=l("b",{text:"0"}),r=l("span.ke-chip",{hidden:!0}),s=l("span.ke-status-hint",{text:"支持拖拽 / 粘贴上传,Ctrl/⌘ + S 保存"}),a=l("span.ke-status-tail"),c=l("div.ke-status",{},[l("span",{},["字数 ",e," · ",t," 词"]),l("span",{},["图片 ",i," · 视频 ",n]),r,s,a]),d={update:h=>{e.textContent=String(h.chars),t.textContent=String(h.words),i.textContent=String(h.images),n.textContent=String(h.videos),h.uploading>0?(r.hidden=!1,r.className="ke-chip ke-is-busy",r.textContent=`${h.uploading} 个上传进行中`):r.hidden=!0},addExtra:h=>a.appendChild(h)};return o.statusApi=d,o.options.wordCount||(c.style.display="none"),c}function Si(o,e){var n;let t=o==null?void 0:o.commonAncestorContainer;if(!t||!e.contains(t))return null;t.nodeType===3&&(t=t.parentElement);const i=(n=t==null?void 0:t.closest)==null?void 0:n.call(t,"a");return i&&e.contains(i)?i:null}function Ei(o,e){var n,r;const t=e||(o==null?void 0:o.commonAncestorContainer),i=[t,t==null?void 0:t.parentElement].filter(s=>s&&s.nodeType===1);for(const s of i){const a=(n=s.style)==null?void 0:n.textAlign;if(a)return a==="-webkit-justify"?"justify":a;const c=(r=s.getAttribute)==null?void 0:r.call(s,"align");if(c)return c}try{if(document.queryCommandState("justifyCenter"))return"center";if(document.queryCommandState("justifyRight"))return"right";if(document.queryCommandState("justifyFull"))return"justify"}catch{}return"left"}function Li(o){const e=(o.match(/[\u4e00-\u9fa5\u3040-\u30ff]/g)||[]).length,t=(o.match(/[a-zA-Z0-9'’-]+/g)||[]).length;return e+t}function Ze(o){const t=new DOMParser().parseFromString(`<div>${o}</div>`,"text/html").body.firstChild;return t.querySelectorAll("[contenteditable]").forEach(i=>i.removeAttribute("contenteditable")),t.querySelectorAll("[data-k-id]").forEach(i=>i.removeAttribute("data-k-id")),t.querySelectorAll("[data-k-state]").forEach(i=>i.removeAttribute("data-k-state")),t.querySelectorAll("[data-ke-marker]").forEach(i=>i.removeAttribute("data-ke-marker")),t.querySelectorAll("[data-placeholder]").forEach(i=>i.removeAttribute("data-placeholder")),t.querySelectorAll(".ke-is-selected-media").forEach(i=>i.classList.remove("ke-is-selected-media")),t.querySelectorAll('[data-k-state="uploading"], [data-k-state="error"]').forEach(i=>i.remove()),t.innerHTML.trim()}function Mi(o){const t=new DOMParser().parseFromString(`<div>${o}</div>`,"text/html").body.firstChild;return t.querySelectorAll("[data-k-media]").forEach(i=>{i.removeAttribute("data-k-media"),i.removeAttribute("data-k-url")}),t.innerHTML}const zi="1.0.6";function xe(o,e={}){return new X(o,e)}const Ti=xe;function Ai(o,e={}){const t=typeof o=="string"?document.querySelector(o):o;return t!=null&&t.__keditor__&&t.__keditor__.destroy(),xe(t,e)}b.ChunkUploader=j,b.DEFAULT_TOOLBAR=Q,b.KEditor=X,b.cleanWordHtml=ze,b.create=xe,b.createUploader=Ke,b.default=X,b.defaults=F,b.escapeHtml=ce,b.exportHtml=Ze,b.fastFingerprint=ke,b.formatHtml=ae,b.httpAdapter=Ve,b.isSafeUrl=Y,b.maybeCompress=Ie,b.mockAdapter=_e,b.mount=Ti,b.normalizeCustomButtons=Be,b.normalizeItems=G,b.normalizePosition=de,b.replace=Ai,b.sanitizeHtml=K,b.simpleAdapter=We,b.strongFingerprint=qe,b.version=zi,Object.defineProperties(b,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});
|
|
483
|
+
`).trim()}const Pt=1e4;function Ae(o){if(Array.isArray(o))return o;if(!o||typeof o!="object")return[];for(const e of["items","list","data","rows","records","result"]){const t=o[e];if(Array.isArray(t))return t;if(t&&typeof t=="object"){const i=Ae(t);if(i.length)return i}}return[]}function Z(o,e){for(const t of e){const i=o[t];if(i!=null)return i}}function Nt(o,e){if(o==null)return null;if(typeof o=="string"||typeof o=="number"){const n=String(o);return{value:n,label:n,desc:"",url:"",group:"",html:"",disabled:!1,raw:o}}if(typeof o!="object")return null;const t=Z(o,["value","id","key","val","code"]),i=Z(o,["label","text","name","title"]);return{value:String(t===void 0?e:t),label:String(i===void 0||i===""?t===void 0?e:t:i),desc:String(Z(o,["desc","description","sub","subtitle","tip"])??""),url:String(Z(o,["url","href","link","jumpUrl","jump"])??""),group:String(o.group??""),html:String(o.html??""),disabled:!!o.disabled,raw:o}}function G(o){return Ae(o).map(Nt).filter(Boolean)}function de(o={}){const e=o.position!==void 0?o.position:o.at,t=n=>Math.max(0,Math.floor(Number(n))),i=n=>typeof n=="object"&&n?n.before||n.after:n;if(typeof e=="number"&&Number.isFinite(e))return t(e);if(typeof e=="string"&&e){const n=e.toLowerCase();return n==="start"||n==="begin"||n==="first"?"start":n==="end"||n==="last"||n==="main"?"end":n==="tail"||n===":tail"||n==="right"?"tail":{before:e}}if(e&&typeof e=="object"){if(e.before)return{before:String(i(e))};if(e.after)return{after:String(i(e))}}return typeof o.index=="number"&&Number.isFinite(o.index)?t(o.index):o.before?{before:String(o.before)}:o.after?{after:String(o.after)}:null}function He(o){if(!o||typeof o!="object")return null;const e=String(o.name||"").trim();return e?{name:e,position:de(o),type:o.type==="button"?"button":"select",title:o.title||o.text||e,text:o.text||"",placeholder:o.placeholder||o.text||"请选择",icon:o.icon||"",width:Number(o.width)>0?Number(o.width):0,searchable:!!o.searchable,note:o.note?String(o.note):"",emptyText:o.emptyText?String(o.emptyText):"",cache:o.cache!==!1,keepValue:o.keepValue!==!1,multiple:!1,options:o.options??null,load:typeof o.load=="function"?o.load:null,url:o.url?String(o.url):"",fetchOptions:o.fetchOptions&&typeof o.fetchOptions=="object"?o.fetchOptions:{},pick:typeof o.pick=="function"?o.pick:null,link:o.link??null,insert:o.insert===void 0?"auto":o.insert,onSelect:typeof o.onSelect=="function"?o.onSelect:null,onClick:typeof o.onClick=="function"?o.onClick:null,active:typeof o.active=="function"?o.active:null,enabled:typeof o.enabled=="function"?o.enabled:null}:null}function Be(o){return Array.isArray(o)?o.map(He).filter(Boolean):[]}function jt(){return{items:null,loaded:!1,loading:null,value:null,controller:null,error:"",gen:0,external:!1}}async function Ft(o,e,t){return o.load?G(await o.load(e)):o.url?G(await Dt(o,e,t)):G(o.options)}async function Dt(o,e,t){var c;const i=o.fetchOptions,n=i.fetch||(typeof fetch=="function"?fetch.bind(globalThis):null);if(!n)throw new Error("当前环境无 fetch,请改用 load 函数提供数据");(c=t.controller)==null||c.abort();const r=typeof AbortController=="function"?new AbortController:null;t.controller=r;const s=Number(i.timeout)>0?Number(i.timeout):Pt,a=setTimeout(()=>r==null?void 0:r.abort(),s);try{const d=await n(o.url,{method:i.method||"GET",headers:i.headers,body:i.body,credentials:i.credentials,signal:r?r.signal:void 0});if(!d||d.ok===!1)throw new Error(`接口返回 ${d&&d.status?d.status:"异常"}`);const h=i.parser?await i.parser(d):await d.json();return o.pick?o.pick(h,e):h}catch(d){throw d&&d.name==="AbortError"?new Error(`请求超时(${s}ms)或被取消`):d}finally{clearTimeout(a),t.controller===r&&(t.controller=null)}}function It(o,e,t,{force:i=!1}={}){if(!i&&t.external&&t.items||!i&&o.cache&&t.items)return Promise.resolve(t.items);if(!i&&t.loading)return t.loading;const n=t.gen,r=Ft(o,e,t).then(s=>n!==t.gen?t.items:(t.items=s,t.loaded=!0,t.error="",s)).catch(s=>{if(n!==t.gen)return t.items;throw t.error=s&&s.message?s.message:String(s),s}).finally(()=>{t.loading===r&&(t.loading=null)});return t.loading=r,r}function qt(o,e){return o.gen+=1,o.items=G(e),o.loaded=!0,o.error="",o.external=!0,he(o),o.loading=null,o.items}function he(o){var e;(e=o.controller)==null||e.abort(),o.controller=null}function pe(o,e){return String(o).replace(/\{(\w+)\}/g,(t,i)=>{if(e[i]!==void 0&&e[i]!==null)return String(e[i]);const n=e.raw&&e.raw[i];return n==null?t:String(n)})}function ue(o,e,t){return typeof o=="function"?o(e,t):o}function $e(o,e,t){const i=o.link;let n=null;if(typeof i=="function"?n=i(e,t):typeof i=="string"?n={url:i}:i&&typeof i=="object"?n=i:(i===!0||e.url)&&(n={url:e.url}),!n)return null;typeof n=="string"&&(n={url:n});const r=W(pe(String(ue(n.url,e,t)??""),e));if(!r||!Y(r))return null;const s=ue(n.text,e,t),a=ue(n.title,e,t),c=n.mode==="open"?"open":"insert",d=n.target==="_self"||n.target===!1?"_self":"_blank";return{mode:c,url:r,text:s==null||s===""?e.label:pe(String(s),e),target:d,title:a?pe(String(a),e):""}}function Re(o,e){o.commands.insertHTML(ce(e))}async function Ut(o,e,t,i){o.restoreSelection();const n=$e(e,i,o),r={editor:o,item:i,link:n,insertLink:d=>Oe(o,{...n,...d}),insertHtml:d=>o.commands.insertHTML(String(d)),insertText:d=>Re(o,d),open:(d,h)=>Pe(d||n&&n.url,h||n&&n.target)};let s="none",a=!1;e.onSelect&&(a=await e.onSelect(i,r)===!1),a||(s=Wt(o,e,i,n)),e.keepValue&&(t.value=i);const c={name:e.name,item:i,link:n,action:s,editor:o};return o.emit("customselect",c),c}function Wt(o,e,t,i){const n=e.insert;return n===!1||n==="none"?"none":i&&i.mode==="open"?(Pe(i.url,i.target),"open"):n==="link"||n==="auto"&&i?i?(Oe(o,i),"link"):"none":n==="html"||n==="auto"&&t.html?t.html?(o.commands.insertHTML(t.html),"html"):"none":(Re(o,t.label),"text")}function Oe(o,e){o.commands.createLink({url:e.url,text:e.text,target:e.target!=="_self"})}function Pe(o,e="_blank"){!o||!Y(o)||(e==="_self"?window.location.href=o:window.open(o,"_blank","noopener,noreferrer"))}const fe='<svg class="ke-caret" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><path d="m6 9 6 6 6-6"/></svg>',Ne="keditor.toolbarScrollHint",_t='<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.1" stroke-linecap="round" stroke-linejoin="round"><path d="M8 7 4 12l4 5"/><path d="M16 7l4 5-4 5"/><path d="M4 12h16"/></svg>',me=[{value:"p",label:"正文",desc:"默认段落 · 17px,正文内容都用它",sample:"正文示例文字",sampleClass:"s-body"},{value:"h1",label:"标题一",desc:"大标题 · 22px 加粗,全文主标题(建议只用一次)",sample:"标题一示例",sampleClass:"s-h1"},{value:"h2",label:"标题二",desc:"章节标题 · 20px 加粗,划分小节",sample:"标题二示例",sampleClass:"s-h2"},{value:"h3",label:"标题三",desc:"小标题 · 18px 加粗,章节内的层级",sample:"标题三示例",sampleClass:"s-h3"}],Vt=[12,14,15,16,17,18,20,22,24,28,32],Q=["undo","redo","|","heading","fontsize","|","bold","italic","underline","strike","|","foreColor","backColor","|","alignLeft","alignCenter","alignRight","alignJustify","|","ul","ol","quote","|","link","image","video","table","code","hr","clear",":tail","source","fullscreen"],je={undo:{icon:"undo",title:"撤销 (⌘/Ctrl+Z)",run:o=>o.undo(),active:o=>!!o.canUndo,enabled:o=>o.canUndo},redo:{icon:"redo",title:"重做 (⌘/Ctrl+Shift+Z)",run:o=>o.redo(),active:o=>!!o.canRedo,enabled:o=>o.canRedo},bold:{glyph:["B","ke-glyph"],title:"加粗 (⌘/Ctrl+B)",cmd:"bold",active:o=>o.bold},italic:{glyph:["I","ke-glyph ke-glyph-i"],title:"斜体 (⌘/Ctrl+I)",cmd:"italic",active:o=>o.italic},underline:{glyph:["U","ke-glyph ke-glyph-u"],title:"下划线 (⌘/Ctrl+U)",cmd:"underline",active:o=>o.underline},strike:{glyph:["S","ke-glyph ke-glyph-s"],title:"删除线",cmd:"strike",active:o=>o.strikeThrough},alignLeft:{icon:"alignLeft",title:"左对齐",run:o=>o.commands.setAlign("left"),active:o=>o.align==="left"},alignCenter:{icon:"alignCenter",title:"居中",run:o=>o.commands.setAlign("center"),active:o=>o.align==="center"},alignRight:{icon:"alignRight",title:"右对齐",run:o=>o.commands.setAlign("right"),active:o=>o.align==="right"},alignJustify:{icon:"alignJustify",title:"两端对齐",run:o=>o.commands.setAlign("justify"),active:o=>o.align==="justify"},ul:{icon:"ul",title:"无序列表",run:o=>o.commands.toggleList("unordered"),active:o=>o.ul},ol:{icon:"ol",title:"有序列表",run:o=>o.commands.toggleList("ordered"),active:o=>o.ol},quote:{icon:"quote",title:"引用",run:o=>o.commands.toggleBlockquote(),active:o=>o.block==="blockquote"},link:{icon:"link",title:"插入链接",run:o=>o.toolbar.openLink(),active:o=>o.link,toggles:!0},image:{icon:"image",title:"图片(本地上传 / 网络链接)",run:o=>o.toolbar.openMedia("image"),toggles:!0},video:{icon:"video",title:"视频(本地上传 / 网络链接,支持分片上传)",run:o=>o.toolbar.openMedia("video"),toggles:!0},table:{icon:"table",title:"插入表格",run:o=>o.toolbar.openTable(),toggles:!0},code:{icon:"code",title:"代码块",run:o=>o.commands.insertCodeBlock()},hr:{icon:"hr",title:"分割线",run:o=>o.commands.insertDivider()},clear:{icon:"clear",title:"清除格式",run:o=>o.commands.clearFormat()},source:{icon:"source",title:"查看 / 编辑 HTML 源码(⌘/Ctrl+Shift+K)",text:"源码",run:o=>o.toggleSource(),active:o=>o.source},preview:{icon:"preview",title:"预览效果(手机 / 平板 / 电脑宽度)",text:"预览",run:o=>o.togglePreview(),active:o=>o.preview},fullscreen:{icon:"expand",title:"全屏编辑",text:"全屏",run:o=>o.toggleFullscreen(),active:o=>o.fullscreen},foreColor:{pop:"fore",title:"字体颜色",toggles:!0,swatch:"fore"},backColor:{pop:"back",title:"背景高亮色",toggles:!0,swatch:"back"}};class Kt{constructor(e,t=Q,i=[]){this.editor=e,this.buttons=new Map,this.custom=new Map,this.colorState={foreColor:"#3f3f3f",backColor:"#f6c344"},this.recent={foreColor:[],backColor:[]},this.el=e.tbEl;for(const n of i)this.registerCustom(n);this.build(t),this.setupScrollHints()}build(e){const t=l("div.ke-tb-group");this.el.appendChild(t),this.groupEl=t,this.tailEl=null;const i=()=>this.tailEl||t;for(const n of e){if(n==="|"){i().appendChild(l("span.ke-tb-sep"));continue}if(n===":tail"){this.tailEl=l("div.ke-tb-tail"),this.el.appendChild(this.tailEl);continue}if(this.custom.has(n)){const s=this.custom.get(n);s.button=this.buildCustomButton(s),i().appendChild(s.button);continue}if(n==="heading"){i().appendChild(this.buildHeading());continue}if(n==="fontsize"){i().appendChild(this.buildFontSize());continue}const r=je[n];r&&i().appendChild(this.buildButton(n,r))}for(const[n,r]of this.custom)r.button||(r.button=this.buildCustomButton(r),this.insertButton(r.button,r.spec.position))}buildButton(e,t){const i=l("button.ke-btn",{type:"button",title:t.title,"data-k-item":e,onclick:n=>{var r;n.preventDefault(),t.pop?this.toggleColor(e,i):t.cmd?this.editor.commands.toggleMark(t.cmd):(r=t.run)==null||r.call(t,this.editor),t.toggles||this.editor.popover.close()}});if(t.icon&&(i.innerHTML=M(t.icon)),t.text&&i.appendChild(l("span.ke-btn-text",{text:t.text})),t.glyph){const[n,r]=t.glyph;i.appendChild(l("span",{class:r,text:n}))}if(t.swatch){const n=t.swatch==="fore"?this.colorState.foreColor:this.colorState.backColor,r=l("span",{class:t.swatch==="fore"?"ke-glyph ke-glyph-a":"ke-glyph ke-glyph-a ke-glyph-hl"});r.appendChild(l("span",{text:"A"})),i.appendChild(r),t.swatch==="fore"&&i.appendChild(l("span",{class:"ke-dot"})),this.paintButton(i,t.swatch,n),i.dataset.kPop=t.swatch==="fore"?"foreColor":"backColor"}return t.toggles&&!t.swatch&&(i.dataset.kPop=e),this.buttons.set(e,i),i}paintButton(e,t,i){!e||!i||e.style.setProperty(t==="fore"?"--ke-fore":"--ke-back",i)}openPop(e,t,i={}){this.editor.saveSelection(),this.editor.popover.open(e,t,{align:"start",...i,onClose:()=>{var n;e.classList.remove("ke-is-open"),(n=i.onClose)==null||n.call(i)}}),e.classList.add("ke-is-open")}togglePop(e,t,i,n={}){const r=this.editor.popover;if(r.isOpen&&r.anchor===t){r.close();return}this.openPop(t,i,n)}buildHeading(){const e=me[0],t=l("button.ke-btn.ke-btn-label",{type:"button",title:"段落样式:正文 / 标题一 / 标题二 / 标题三","data-k-item":"heading",dataset:{kPop:"heading"},onclick:i=>{i.preventDefault(),this.togglePop("heading",t,()=>ct(me,{value:this.editor.getState().block,onPick:n=>{this.editor.restoreSelection(),this.editor.commands.setHeading(n),this.editor.popover.close(),this.editor.refresh()}}))}});return t.innerHTML=`<span class="ke-btn-text">${e.label}</span>${fe}`,this.headingEl=t,this.buttons.set("heading",t),t}buildFontSize(){const e=l("button.ke-btn.ke-btn-label",{type:"button",title:"字号","data-k-item":"fontsize",dataset:{kPop:"fontsize"},onclick:t=>{t.preventDefault(),this.togglePop("fontsize",e,()=>dt(Vt,{value:this.editor.getState().fontSize,onPick:i=>{this.editor.restoreSelection(),this.editor.commands.setFontSize(Number(i)),this.editor.popover.close(),this.editor.refresh()}}))}});return e.innerHTML=`<span class="ke-btn-text">字号</span>${fe}`,this.fontSizeEl=e,this.buttons.set("fontsize",e),e}registerCustom(e){const t=He(e);if(!t)return null;const i=this.custom.get(t.name),n={spec:t,rt:i?i.rt:jt(),button:i?i.button:null};return this.custom.set(t.name,n),n}buildCustomButton(e){const{spec:t}=e,i=t.type==="select",n=l("button.ke-btn",{type:"button",class:i?"ke-btn-label ke-btn-custom":"ke-btn-custom",title:t.title,"data-k-item":t.name,dataset:{kPop:t.name,kCustom:t.name},onclick:r=>{r.preventDefault(),i?this.openCustom(t.name):this.runCustomButton(t)}});return t.icon&&(n.innerHTML=/</.test(t.icon)?t.icon:M(t.icon)),i?(n.appendChild(l("span.ke-btn-text",{text:t.text||t.placeholder})),n.insertAdjacentHTML("beforeend",fe)):t.text&&n.appendChild(l("span.ke-btn-text",{text:t.text})),this.syncCustomLabel(t.name,n),n}syncCustomLabel(e,t){const i=this.custom.get(e),n=t||(i==null?void 0:i.button);if(!i||!n)return;const{spec:r,rt:s}=i;if(r.type!=="select")return;const a=n.querySelector(".ke-btn-text");if(!a)return;const c=s.value;a.textContent=c?c.label:r.text||r.placeholder,n.title=c?`${r.title}:${c.label}`:r.title,n.classList.toggle("ke-has-value",!!c)}openCustom(e){const t=this.custom.get(e);if(!t)return;this.revealButton(t.button);const{spec:i,rt:n}=t,r=!!(i.load||i.url),s=({force:a}={})=>It(i,this.editor,n,{force:a});this.togglePop(e,t.button,()=>kt({title:i.title,note:i.note||"",searchable:i.searchable,width:i.width,remote:r,value:n.value?n.value.value:"",emptyText:i.emptyText,load:s,reload:s,linkOf:a=>$e(i,a,this.editor),onPick:a=>this.pickCustom(e,a)}))}async pickCustom(e,t){const i=this.custom.get(e);if(i){this.editor.popover.close();try{await Ut(this.editor,i.spec,i.rt,t)}catch(n){this.editor.reportError("custombutton",n)}this.syncCustomLabel(e),this.editor.refresh()}}async runCustomButton(e){this.editor.popover.close();try{e.onClick&&await e.onClick({editor:this.editor,name:e.name}),this.editor.emit("customclick",{name:e.name,editor:this.editor})}catch(t){this.editor.reportError("custombutton",t)}this.editor.refresh()}addButton(e,t={}){var r;const i=this.registerCustom(e);if(!i)return null;i.button&&i.button.remove(),i.button=this.buildCustomButton(i);const n=t.at!==void 0?t.at:de(t)??i.spec.position;return this.insertButton(i.button,n,{withSep:n==null}),this.revealButton(i.button),(r=this.syncScrollHints)==null||r.call(this),i.button}buttonNodes(){const e=[];for(const t of[this.groupEl,this.tailEl])if(t)for(const i of t.children)i.dataset&&i.dataset.kItem&&e.push(i);return e}slotOf(e){const t={parent:this.groupEl||this.el,ref:null};if(e==="tail")return{parent:this.tailEl||this.groupEl||this.el,ref:null};if(e==null||e==="end")return t;if(e==="start"){const a=this.buttonNodes()[0];return a?{parent:a.parentElement,ref:a}:t}const i=this.buttonNodes();if(typeof e=="number"){const a=i[Math.max(0,Math.floor(e))];if(a)return{parent:a.parentElement,ref:a};const c=i[i.length-1];return c?{parent:c.parentElement,ref:null}:t}const n=!!(e&&typeof e=="object"&&e.after),r=typeof e=="string"?e:String((n?e.after:e.before)||""),s=i.find(a=>a.dataset.kItem===r);return s?{parent:s.parentElement,ref:n?s.nextElementSibling||null:s}:t}insertButton(e,t,{withSep:i}={}){const{parent:n,ref:r}=this.slotOf(t);!n||!e||(i&&!r&&n.appendChild(l("span.ke-tb-sep")),n.insertBefore(e,r||null))}moveButton(e,t){var n,r;const i=this.buttonNodes().find(s=>s.dataset.kItem===String(e));return i?(i.remove(),this.insertButton(i,t===void 0?((n=this.custom.get(String(e)))==null?void 0:n.spec.position)??null:t),this.revealButton(i),(r=this.syncScrollHints)==null||r.call(this),!0):!1}revealButton(e){const t=this.el;if(!t||!e||!e.isConnected)return;const i=t.scrollWidth-t.clientWidth;if(i<=1)return;const n=this.tailEl?this.tailEl.offsetWidth:0,r=e.offsetLeft,s=r+e.offsetWidth,a=t.scrollLeft+t.clientWidth-n;s>a-4?t.scrollLeft=Math.min(i,s-t.clientWidth+n+10):r<t.scrollLeft+4&&(t.scrollLeft=Math.max(0,r-10))}removeButton(e){var r,s,a,c;const t=this.custom.get(e);if(!t)return!1;he(t.rt),this.editor.popover.anchor===t.button&&this.editor.popover.close();const i=(r=t.button)==null?void 0:r.previousElementSibling,n=(s=t.button)==null?void 0:s.nextElementSibling;return(a=t.button)==null||a.remove(),i&&i.classList.contains("ke-tb-sep")&&(!n||n.classList.contains("ke-tb-sep"))&&i.remove(),this.buttons.delete(e),this.custom.delete(e),(c=this.syncScrollHints)==null||c.call(this),!0}setButtonOptions(e,t){const i=this.custom.get(e);if(!i)return null;const n=qt(i.rt,t);return this.editor.popover.isOpen&&this.editor.popover.anchor===i.button&&(this.editor.popover.close(),this.openCustom(e)),n}getButtonValue(e){const t=this.custom.get(e);return t?t.rt.value:null}setButtonValue(e,t){const i=this.custom.get(e);if(!i)return null;const r=(i.rt.items||[]).find(s=>String(s.value)===String(t))||null;return i.rt.value=r,this.syncCustomLabel(e),r}toggleColor(e,t){const i=e==="foreColor"?"fore":"back";this.togglePop(e,t,()=>at({title:i==="fore"?"字体颜色":"背景高亮色",kind:i,value:this.colorState[e],recents:this.recent[e],onPick:n=>this.applyColor(e,i,n,t),onClear:()=>this.applyColor(e,i,null,t)}),{onClose:()=>t.classList.remove("ke-is-active")})}applyColor(e,t,i,n){this.editor.restoreSelection(),i&&(this.colorState[e]=i,this.recent[e]=[i,...this.recent[e].filter(r=>r.toLowerCase()!==i.toLowerCase())].slice(0,8),this.paintButton(n,t,i)),this.editor.commands.setColor(t,i),this.editor.popover.close()}openTable(){const e=this.buttons.get("table");this.togglePop("table",e,()=>ht((t,i)=>{this.editor.restoreSelection(),this.editor.commands.insertTable(t,i),this.editor.popover.close()}))}openLink(){const e=this.buttons.get("link"),t=this.editor.getState(),i=t.linkUrl;this.togglePop("link",e,()=>ft({url:i||"",text:i?"":t.selectionText||"",target:i?t.linkTarget:!0,onCancel:()=>this.editor.popover.close(),onRemove:i?()=>{this.editor.restoreSelection(),this.editor.commands.removeLink(),this.editor.popover.close()}:null,onSubmit:({url:n,text:r,target:s})=>{this.editor.restoreSelection(),this.editor.commands.createLink({url:W(n),text:r,target:s}),this.editor.popover.close()}}))}openMedia(e){const t=this.buttons.get(e),i=this.editor,n=i.options;this.togglePop(e,t,()=>pt(e,{multiple:e==="image",maxText:`${e==="image"?"图片":"视频"}上限 ${Gt(e==="image"?n.maxImageSize:n.maxVideoSize)}`,hint:e==="image"?"支持 PNG / JPG / GIF / WebP / SVG":"支持 MP4 / MOV / WebM,大文件自动分片",onFiles:r=>{i.popover.close(),r&&r.length?i.media.addFiles([...r]):i.media.pickFiles(e)},onUrl:({url:r,name:s})=>{i.popover.close(),i.restoreSelection(),i.media.insertFromUrl(e,r,s)}}))}refresh(e){var t;for(const[i,n]of this.buttons){const r=je[i];if(!r)continue;const s=((t=r.active)==null?void 0:t.call(r,e))||!1;(n.dataset.kPop||!r.pop)&&n.classList.toggle("ke-is-active",s),r.enabled&&(n.disabled=!r.enabled(e))}for(const[i,n]of this.custom){const{spec:r,button:s}=n;s&&(r.active&&s.classList.toggle("ke-is-active",!!r.active(e,this.editor)),r.enabled&&(s.disabled=!r.enabled(e,this.editor)),r.type==="select"&&this.syncCustomLabel(i))}if(this.headingEl){const i=me.find(r=>r.value===e.block),n=this.headingEl.querySelector(".ke-btn-text");n&&(n.textContent=i?i.label:"正文"),this.headingEl.title=i?`${i.label}:${i.desc}`:"段落样式"}if(this.fontSizeEl){const i=this.fontSizeEl.querySelector(".ke-btn-text");i&&(i.textContent=e.fontSize?`${e.fontSize}px`:"字号")}if(e.linkUrl){const i=this.buttons.get("link");i==null||i.classList.add("ke-is-active")}}setupScrollHints(){const e=this.el,t=this.editor.el;e.isConnected&&(this.scrollFades=l("div.ke-tb-fades",{"aria-hidden":"true"},[l("i.ke-tb-fade ke-tb-fade-l")]),e.insertAdjacentElement("afterend",this.scrollFades),this.syncScrollHints=()=>{if(!e.isConnected||!t.isConnected)return;const i=e.scrollWidth-e.clientWidth,n=i>1,r=e.scrollLeft;t.classList.toggle("ke-tb-scrollable",n),t.classList.toggle("ke-tb-can-l",n&&r>1),t.classList.toggle("ke-tb-can-r",n&&r<i-1),t.style.setProperty("--ke-tb-h",`${e.offsetHeight}px`),n&&!this.hintSettled&&this.showScrollHint()},this.onTbScroll=()=>{this.syncScrollHints(),this.hideScrollHint()},e.addEventListener("scroll",this.onTbScroll,{passive:!0}),typeof ResizeObserver<"u"&&(this.tbRO=new ResizeObserver(()=>this.syncScrollHints()),this.tbRO.observe(e)),this.onTbPointerDown=i=>{this.hideScrollHint(),this.startDragScroll(i)},e.addEventListener("pointerdown",this.onTbPointerDown),requestAnimationFrame(this.syncScrollHints))}startDragScroll(e){const t=this.el,i=this.editor.el;if(e.button!==0||e.pointerType!=="mouse"||t.scrollWidth<=t.clientWidth+1||e.target.closest("input, textarea, select"))return;const n=e.clientX,r=t.scrollLeft;let s=!1;const a=d=>{var p;const h=d.clientX-n;if(!s){if(Math.abs(h)<5)return;s=!0;try{t.setPointerCapture(e.pointerId)}catch{}i.classList.add("ke-tb-dragging"),(p=this.editor.popover)==null||p.close()}d.preventDefault(),t.scrollLeft=r-h},c=()=>{if(t.removeEventListener("pointermove",a),t.removeEventListener("pointerup",c),t.removeEventListener("pointercancel",c),i.classList.remove("ke-tb-dragging"),!s)return;try{t.releasePointerCapture(e.pointerId)}catch{}const d=u=>{u.preventDefault(),u.stopPropagation(),h()},h=()=>{clearTimeout(p),t.removeEventListener("click",d,!0)},p=setTimeout(h,400);t.addEventListener("click",d,!0)};t.addEventListener("pointermove",a),t.addEventListener("pointerup",c),t.addEventListener("pointercancel",c)}showScrollHint(){this.hintSettled=!0;let e=!1;try{e=localStorage.getItem(Ne)==="1"}catch{}e||(this.hintEl=l("div.ke-tb-hint",{"aria-hidden":"true"},[l("span.ke-tb-hint-ico",{html:_t}),l("span",{text:"工具栏可左右滑动"})]),this.editor.el.appendChild(this.hintEl),this.hintTimer=setTimeout(()=>this.hideScrollHint(),3800))}hideScrollHint(){this.hintTimer&&(clearTimeout(this.hintTimer),this.hintTimer=null);const e=this.hintEl;if(e){this.hintEl=null;try{localStorage.setItem(Ne,"1")}catch{}e.classList.add("ke-is-out"),setTimeout(()=>e.remove(),260)}}destroy(){var i,n,r;const e=this.el;this.tbRO&&(this.tbRO.disconnect(),this.tbRO=null),this.hintTimer&&(clearTimeout(this.hintTimer),this.hintTimer=null),this.onTbScroll&&e.removeEventListener("scroll",this.onTbScroll),this.onTbPointerDown&&e.removeEventListener("pointerdown",this.onTbPointerDown);for(const s of this.custom.values())he(s.rt);this.custom.clear(),(i=this.scrollFades)==null||i.remove(),(n=this.hintEl)==null||n.remove(),this.scrollFades=null,this.hintEl=null;const t=(r=this.editor)==null?void 0:r.el;t&&(t.classList.remove("ke-tb-scrollable","ke-tb-can-l","ke-tb-can-r","ke-tb-dragging"),t.style.removeProperty("--ke-tb-h")),e.innerHTML="",this.buttons.clear()}}function Gt(o){if(!o)return"不限";const e=o/1024/1024;return e>=1?`${Math.round(e)}MB`:`${Math.round(o/1024)}KB`}function z(o){const e=window.getSelection();if(!e||e.rangeCount===0)return null;const t=e.getRangeAt(0);return o.contains(t.commonAncestorContainer)?t:null}function Fe(o){const e=window.getSelection();if(!e||e.rangeCount===0)return null;const t=e.getRangeAt(0);if(!o.contains(t.startContainer))return null;let i=0;return document.createTreeWalker(o,NodeFilter.SHOW_TEXT,{acceptNode(s){return s===t.startContainer?NodeFilter.FILTER_ACCEPT:(i+=s.textContent.length,NodeFilter.FILTER_SKIP)}}).nextNode()?i+t.startOffset:t.startContainer===o?0:null}function Xt(o,e){if(e==null)return;const t=window.getSelection();let i=Math.max(0,e);const n=document.createTreeWalker(o,NodeFilter.SHOW_TEXT);let r=n.nextNode(),s=null;for(;r;){const a=r.textContent.length;if(i<=a){try{t.setBaseAndExtent(r,i,r,i)}catch{}return}i-=a,s=r,r=n.nextNode()}if(s)try{t.setBaseAndExtent(s,s.textContent.length,s,s.textContent.length)}catch{}}function P(o,e,{inline:t=!1,selectAfter:i=!0}={}){o.focus();const n=z(o);if(!n)return o.appendChild(e),ee(o),e;if(n.collapsed||n.deleteContents(),t)n.insertNode(e);else{const a=N(n.startContainer,o);!a||a===o?o.appendChild(e):a.after(e)}const r=document.createRange();r.setStartAfter(e),r.collapse(!0);const s=window.getSelection();return s.removeAllRanges(),s.addRange(r),ee(o),i&&s.rangeCount===0&&o.focus(),e}function ee(o){const e=o.lastElementChild;if(!e){o.appendChild(document.createElement("p"));return}if(/^(IMG|VIDEO|IFRAME)$/.test(e.tagName)||e.dataset.kmedia!==void 0){const t=document.createElement("p");t.appendChild(document.createElement("br")),o.appendChild(t)}}function N(o,e){let t=o;for(;t&&t!==e;){if(t.nodeType===1&&/^(P|DIV|H[1-6]|LI|BLOCKQUOTE|PRE|SECTION|TD|TH)$/.test(t.tagName))return t;t=t.parentNode}return null}class Jt{constructor(e){this.editor=e,this.root=e.root}exec(e,t=null){this.editor.focus(),document.execCommand("styleWithCSS",!1,!0),document.execCommand("defaultParagraphSeparator",!1,"p");const i=document.execCommand(e,!1,t);return this.editor.afterEdit(),i}queryState(e){try{return document.queryCommandState(e)}catch{return!1}}queryValue(e){try{return document.queryCommandValue(e)}catch{return""}}hasSelection(){const e=z(this.root);return!!(e&&!e.collapsed)}toggleMark(e){const i={bold:"bold",italic:"italic",underline:"underline",strike:"strikeThrough"}[e];i&&(this.exec(i),this.root.querySelectorAll('span[style=""]').forEach(n=>n.replaceWith(...n.childNodes)))}setFontSize(e){this.editor.focus(),document.execCommand("styleWithCSS",!1,!1);const t=`__ke_fs_${ie()}__`;this.root.setAttribute("data-ke-marker",t),document.execCommand("fontSize",!1,"7"),this.root.removeAttribute("data-ke-marker"),this.root.querySelectorAll('font[size="7"]').forEach(i=>{const n=document.createElement("span");for(n.style.fontSize=`${e}px`;i.firstChild;)n.appendChild(i.firstChild);i.replaceWith(n)}),this.root.querySelectorAll("span").forEach(i=>{/xx-large/i.test(i.style.fontSize)&&(i.style.fontSize=`${e}px`)}),document.execCommand("styleWithCSS",!1,!0),this.editor.afterEdit()}setColor(e,t){this.editor.focus(),document.execCommand("styleWithCSS",!1,!0),t||(t=e==="fore"?"#3f3f3f":"transparent"),document.execCommand(e==="fore"?"foreColor":"hiliteColor",!1,t)||document.execCommand(e==="fore"?"foreColor":"backColor",!1,t),e==="back"&&t==="transparent"&&this.root.querySelectorAll('[style*="background-color"]').forEach(n=>{/background-color:\s*transparent|rgba\(0, 0, 0, 0\)/i.test(n.getAttribute("style")||"")&&(n.style.backgroundColor="",n.getAttribute("style").trim()||n.replaceWith(...n.childNodes))}),this.editor.afterEdit()}setAlign(e){var c,d;const t=(c=this.editor.bubble)==null?void 0:c.node;if(t&&((d=t.dataset)==null?void 0:d.kMedia)==="image"&&e!=="justify"){const h=t.querySelector("img");if(h){ne(h,e),this.editor.commitHistory(),this.editor.bubble.position();return}}const n={left:"justifyLeft",center:"justifyCenter",right:"justifyRight",justify:"justifyFull"}[e];if(!n)return;this.editor.focus();const r=z(this.root),s=N((r==null?void 0:r.commonAncestorContainer)||this.root,this.root);document.execCommand("styleWithCSS",!1,!0),document.execCommand(n);const a=s||this.root.firstElementChild;a&&/^(FIGURE|DIV|VIDEO)/.test(a.tagName||"")&&(a.style.textAlign=e),this.editor.afterEdit()}toggleList(e){this.exec(e==="ordered"?"insertOrderedList":"insertUnorderedList")}setHeading(e){const t=e?`<${e}>`:"<p>";this.exec("formatBlock",t)}toggleBlockquote(){const e=z(this.root),t=N((e==null?void 0:e.commonAncestorContainer)||this.root,this.root);t&&t.tagName==="BLOCKQUOTE"?this.exec("formatBlock","<p>"):this.exec("formatBlock","<blockquote>")}createLink({url:e,text:t="",target:i=!1}){var a,c;this.editor.focus();const n=z(this.root),r=n&&!n.collapsed,s=t||(r?n.toString():e);if(r)document.execCommand("createLink",!1,e),(c=(a=n.commonAncestorContainer.parentElement)==null?void 0:a.closest)==null||c.call(a,"a"),this.root.querySelectorAll(`a[href="${Zt(e)}"]`).forEach(d=>{i?(d.setAttribute("target","_blank"),d.setAttribute("rel","noopener noreferrer")):d.removeAttribute("target")});else{const d=l("a",{href:e},[s]);i&&(d.setAttribute("target","_blank"),d.setAttribute("rel","noopener noreferrer")),P(this.root,d,{inline:!0})}this.editor.afterEdit()}removeLink(){const e=z(this.root);Yt(e,this.root).forEach(i=>i.replaceWith(...i.childNodes)),this.editor.afterEdit()}insertTable(e,t){const i=document.createElement("table"),n=document.createElement("tbody");for(let r=0;r<t;r+=1){const s=document.createElement("tr");for(let a=0;a<e;a+=1){const c=document.createElement(r===0?"th":"td");c.innerHTML="<br>",s.appendChild(c)}n.appendChild(s)}i.appendChild(n),P(this.root,i),this.exec("insertHTML",""),this.editor.afterEdit()}insertCodeBlock(e=""){const t=document.createElement("pre"),i=document.createElement("code");i.textContent=e||"// 在这里输入代码",t.appendChild(i),P(this.root,t),this.editor.afterEdit()}insertDivider(){const e=document.createElement("hr");P(this.root,e),this.editor.afterEdit()}insertHTML(e,{clean:t=!0}={}){const i=t?K(e):e;this.editor.focus();const n=z(this.root);if(n){n.deleteContents();const r=document.createElement("div");r.innerHTML=i;const s=document.createDocumentFragment();for(;r.firstChild;)s.appendChild(r.firstChild);const a=s.lastChild;if(n.insertNode(s),a){const c=document.createRange();c.setStartAfter(a.nodeType===3?a:a.lastChild||a),c.collapse(!0);const d=window.getSelection();d.removeAllRanges(),d.addRange(c)}}else this.root.insertAdjacentHTML("beforeend",i);this.editor.afterEdit()}clearFormat(){if(this.editor.focus(),this.hasSelection()){document.execCommand("removeFormat"),document.execCommand("unlink");const e=z(this.root),t=N(e==null?void 0:e.commonAncestorContainer,this.root);t&&/^(H[1-6]|BLOCKQUOTE|PRE)$/.test(t.tagName)&&this.exec("formatBlock","<p>"),this.stripInlineStylesInRange(e)}else{const e=z(this.root),t=N((e==null?void 0:e.commonAncestorContainer)||this.root,this.root);if(t){const i=t.innerHTML,n=document.createElement("p");n.innerHTML=K(i,{allowEmpty:!0}),n.innerHTML=n.innerHTML.replace(/<(?!br|img)[^>]+>/gi,""),t.replaceWith(n)}}this.editor.afterEdit()}stripInlineStylesInRange(e){if(!e)return;const t=[],i=document.createTreeWalker(e.commonAncestorContainer,NodeFilter.SHOW_ELEMENT);let n=i.currentNode;for(;n;)e.intersectsNode(n)&&n.nodeType===1&&t.push(n),n=i.nextNode();t.forEach(r=>{r!==this.root&&(r.removeAttribute("style"),/^(SPAN|FONT)$/.test(r.tagName)&&!r.attributes.length&&r.replaceWith(...r.childNodes))})}currentBlock(){var i;const e=z(this.root),t=N((e==null?void 0:e.commonAncestorContainer)||this.root,this.root);return((i=t==null?void 0:t.tagName)==null?void 0:i.toLowerCase())||"p"}currentFontSize(){const e=z(this.root);if(!e)return"";let t=e.startContainer;for(;t&&t!==this.root;){if(t.nodeType===1&&t.style.fontSize)return t.style.fontSize.replace("px","");t=t.parentNode}return""}}function Yt(o,e){var s,a,c;if(!o)return[];const t=new Set;let n=o.startContainer.nodeType===1&&((a=(s=o.startContainer).querySelector)==null?void 0:a.call(s,"a"))||o.startContainer;for(;n&&n!==e;)n.tagName==="A"&&t.add(n),n=n.parentNode;try{(c=o.querySelectorAll)==null||c.call(o,"a").forEach(d=>t.add(d))}catch{}const r=o.commonAncestorContainer;return r.nodeType===1&&r.querySelectorAll("a").forEach(d=>o.intersectsNode(d)?t.add(d):null),[...t]}function Zt(o){var e;return(e=window.CSS)!=null&&e.escape?CSS.escape(o):String(o).replace(/["\\]/g,"\\$&")}class Qt{constructor(e,{limit:t=60,delay:i=400}={}){this.root=e,this.limit=t,this.delay=i,this.stack=[],this.index=-1,this.timer=null,this.locked=!1,this.lastHtml=e.innerHTML}snapshot(e=!1){clearTimeout(this.timer);const t=()=>{const i=this.root.innerHTML;if(i===this.lastHtml)return;this.lastHtml=i;const n={html:i,offset:Fe(this.root)};this.stack=this.stack.slice(0,this.index+1),this.stack.push(n),this.stack.length>this.limit&&this.stack.shift(),this.index=this.stack.length-1};e?t():this.timer=setTimeout(t,this.delay)}flush(){clearTimeout(this.timer),this.snapshot(!0)}apply(e,t){this.locked=!0,this.root.innerHTML=e,this.lastHtml=e,t!=null&&Xt(this.root,t),this.locked=!1}canUndo(){return this.index>0}canRedo(){return this.index>=0&&this.index<this.stack.length-1}undo(){if(!this.canUndo())return!1;clearTimeout(this.timer),this.index-=1;const e=this.stack[this.index];return this.apply(e.html,this.currentOffset(e,"undo")),this.lastHtml=e.html,!0}redo(){if(!this.canRedo())return!1;const e=this.stack[this.index+1];return this.index+=1,this.apply(e.html,this.currentOffset(e,"redo")),this.lastHtml=e.html,!0}currentOffset(e){const t=Fe(this.root);return e.offset}reset(e){clearTimeout(this.timer),this.stack=[{html:e,offset:0}],this.index=0,this.lastHtml=e}destroy(){clearTimeout(this.timer),this.stack=[]}}const ei=/\.(jpe?g|png|gif|webp|bmp|svg|avif)$/i,ti=/\.(mp4|mov|webm|m4v|ogv|avi|mkv)$/i;class ii{constructor(e){this.editor=e,this.options=e.options,this.tasks=new Map,this.input=null}kindOf(e){const t=String(e.type||""),i=String(e.name||"");return t.startsWith("image/")||ei.test(i)?"image":t.startsWith("video/")||ti.test(i)?"video":null}check(e,t){if(!t)return`不支持的文件类型:${e.name||"剪贴板内容"}`;const i=t==="image"?this.options.maxImageSize:this.options.maxVideoSize;return i&&e.size>i?`${e.name} 超出大小限制(${R(i)})`:null}pickFiles(e){this.input||(this.input=l("input",{type:"file",multiple:!0,style:{display:"none"}}),this.input.addEventListener("change",()=>{const t=[...this.input.files||[]];this.input.value="",this.addFiles(t)}),document.body.appendChild(this.input)),this.input.accept=e==="image"?this.options.imageAccept:this.options.videoAccept,this.input.multiple=e==="image",this.input.click()}async addFiles(e){const t=[];for(const i of e){const n=this.kindOf(i),r=this.check(i,n);r?this.editor.toast.warn(r):t.push({file:i,kind:n})}for(const i of t)await this.upload(i.file,i.kind);return t.length}async upload(e,t){const i=t==="image"?this.createImageHolder():this.createVideoHolder();this.editor.focus(),P(this.editor.root,i);const n={id:i.dataset.kId,file:e,kind:t,holder:i,ctrl:new AbortController,previewUrl:URL.createObjectURL(e)};this.tasks.set(n.id,n),this.decorateHolder(n);const r=i.querySelector("[data-k-preview]");return r&&(r.src=n.previewUrl),this.runUpload(n)}async runUpload(e){const t=this.editor,{holder:i,file:n,kind:r}=e;t.emit("uploadstart",{file:n,kind:r}),t.refreshStatus();let s=n;try{r==="image"&&(s=await Ie(n,this.options.image));const a=await t.uploader.upload(s,{signal:e.ctrl.signal,onProgress:(d,h)=>this.updateProgress(i,d,h,s,e)}),c=typeof a=="string"?{url:a}:a;if(!(c!=null&&c.url))throw new Error("上传结果缺少 url");return this.finish(e,{...c,size:s.size}),t.emit("uploaddone",{file:n,kind:r,url:c.url}),c}catch(a){return(a==null?void 0:a.name)==="AbortError"?(this.remove(e),t.emit("uploadcancel",{file:n,kind:r}),null):(this.fail(e,a),t.emit("uploaderror",{file:n,kind:r,error:a}),t.toast.error((a==null?void 0:a.message)||"上传失败"),null)}finally{ee(t.root),t.commitHistory(),t.refreshStatus()}}createImageHolder(){const e=l("figure",{"data-k-media":"image","data-k-id":ie("m"),"data-k-state":"uploading",contenteditable:"false"}),t=l("div.ke-media-holder",{},[l("img",{"data-k-preview":"",alt:"",style:{display:"none"}}),l("div.ke-media-name",{text:"图片上传中…"}),De()]);return t.appendChild(this.actionRow()),e.appendChild(t),e}createVideoHolder(){const e=l("div.ke-video-card",{"data-k-media":"video","data-k-id":ie("m"),"data-k-state":"uploading",contenteditable:"false"}),t=l("div.ke-video-body",{},[l("div.ke-video-head",{},[l("span",{text:"视频上传中…"}),l("span.ke-video-size",{text:""})]),De()]);return t.appendChild(this.actionRow()),e.appendChild(t),e}actionRow(){const e=this;return l("div",{"data-k-actions":"",style:{display:"flex",alignItems:"center",gap:"8px",width:"100%",marginTop:"2px"},onclick:t=>{const i=t.target.closest("[data-k-id]"),n=i&&e.tasks.get(i.dataset.kId);n&&(t.target.matches(".ke-media-cancel")?(n.ctrl.abort(),e.remove(n)):t.target.matches(".ke-media-retry")&&(n.ctrl=new AbortController,e.resetHolder(n),e.runUpload(n)))}},[l("button.ke-media-cancel",{type:"button",text:"取消"})])}decorateHolder(e){const{holder:t,file:i}=e,n=t.querySelector(".ke-media-name");n&&(n.textContent=`${i.name||"未命名"}(${R(i.size)})`);const r=t.querySelector(".ke-video-size");r&&(r.textContent=R(i.size));const s=t.querySelector(".ke-video-head span");s&&e.kind==="video"&&(s.textContent=`${i.name||"视频"} 上传中…`)}resetHolder(e){const t=e.holder;t.dataset.kState="uploading";const i=t.querySelector(".ke-progress i");i&&(i.style.width="0%",i.style.background="");const n=t.querySelector(".ke-media-pct");n&&(n.textContent="0%");const r=t.querySelector("[data-k-actions]");r&&(r.innerHTML='<button class="ke-media-cancel" type="button">取消</button>'),this.decorateHolder(e)}updateProgress(e,t,i,n,r){const s=Math.max(0,Math.min(100,Math.round((t||0)*100))),a=e.querySelector(".ke-progress i");a&&(a.style.width=`${s}%`);const c=e.querySelector(".ke-media-pct");c&&(c.textContent=`${s}%`),r&&this.editor.emit("uploadprogress",{file:r.file,kind:r.kind,percent:s,info:i});const d=e.querySelector(".ke-media-meta");if(!d)return;let h=d.querySelector("[data-k-chunks]");h||(h=l("span",{"data-k-chunks":"",style:{color:"#8a8f99",fontSize:"12px"}}),d.insertBefore(h,d.firstChild)),(i==null?void 0:i.chunks)>1?h.textContent=`${i.chunks} 片 · ${R(i.loaded)}/${R(i.total||n.size)}`:i!=null&&i.speed&&(h.textContent=`${R(i.speed)}/s`)}finish(e,t){const{holder:i,kind:n,file:r}=e,s=t.url;if(i.dataset.kState="done",i.dataset.kUrl=s,i.innerHTML="",n==="image"){const a=l("img",{src:s,alt:oi(r),"data-k-name":r.name||"",draggable:"false"});a.addEventListener("dblclick",()=>J(a.src)),i.appendChild(a)}else{const a=l("video",{src:s,controls:"",playsinline:"",preload:"metadata","data-k-name":r.name||""}),c=l("div.ke-video-body",{},[l("div.ke-video-head",{},[l("span",{text:r.name||"视频"}),l("span.ke-video-size",{text:R(t.size||r.size)})]),a]);i.appendChild(c)}e.previewUrl&&URL.revokeObjectURL(e.previewUrl),this.tasks.delete(e.id),this.editor.refreshStatus()}fail(e,t){const i=e.holder;i.dataset.kState="error";const n=i.querySelector(".ke-progress i");n&&(n.style.background="#e53e3e");const r=i.querySelector("[data-k-actions]");r&&(r.innerHTML="",r.appendChild(l("span.ke-media-error",{text:(t==null?void 0:t.message)||"上传失败",style:{marginRight:"auto",fontSize:"12px"}})),r.appendChild(l("button.ke-media-retry",{type:"button",text:"重试"})),r.appendChild(l("button.ke-media-cancel",{type:"button",text:"移除"})))}remove(e){var t;(t=e.holder)==null||t.remove(),e.previewUrl&&URL.revokeObjectURL(e.previewUrl),this.tasks.delete(e.id),ee(this.editor.root),this.editor.refreshStatus()}taskFromNode(e){var i;const t=(i=e==null?void 0:e.closest)==null?void 0:i.call(e,"[data-k-id]");return t?this.tasks.get(t.dataset.kId):null}cancelAll(){for(const e of[...this.tasks.values()])e.ctrl.abort(),this.remove(e)}insertFromUrl(e,t,i=""){const n=e==="image"?this.insertImageUrl(t,i):this.insertVideoUrl(t,i||"网络视频");return this.editor.toast.ok(e==="image"?"已插入网络图片":"已插入网络视频"),this.editor.emit("insertmedia",{kind:e,url:t,node:n}),n}insertImageUrl(e,t=""){const i=l("img",{src:e,alt:t||"",draggable:"false"});i.addEventListener("dblclick",()=>J(i.src));const n=l("figure",{"data-k-media":"image","data-k-state":"done","data-k-url":e,contenteditable:"false"},[i]);return P(this.editor.root,n),this.editor.commitHistory(),n}insertVideoUrl(e,t="视频"){const i=l("video",{src:e,controls:"",playsinline:"",preload:"metadata"}),n=l("div.ke-video-card",{"data-k-media":"video","data-k-state":"done","data-k-url":e,contenteditable:"false"},[l("div.ke-video-body",{},[l("div.ke-video-head",{},[l("span",{text:t})]),i])]);return P(this.editor.root,n),this.editor.commitHistory(),n}destroy(){var e;this.cancelAll(),(e=this.input)==null||e.remove(),this.input=null}}function oi(o){return String(o.name||"").replace(/\.[^.]+$/,"")}function De(){return l("div.ke-media-meta",{},[l("div.ke-progress",{},[l("i",{style:{width:"0%"}})]),l("span.ke-media-pct",{text:"0%"})])}async function Ie(o,e={}){var s,a;const t=e==null?void 0:e.compress;if(!t||!/^image\/(jpeg|jpg|png|webp)$/i.test(o.type))return o;const{maxWidth:i=1440,quality:n=.85,minSize:r=300*1024}=typeof t=="object"?t:{};if(o.size<r)return o;try{const c=await createImageBitmap(o);if(c.width<=i)return(s=c.close)==null||s.call(c),o;const d=document.createElement("canvas");d.width=i,d.height=Math.round(c.height*i/c.width),d.getContext("2d").drawImage(c,0,0,d.width,d.height),(a=c.close)==null||a.call(c);const h=await new Promise(p=>d.toBlob(p,"image/jpeg",n));return!h||h.size>=o.size?o:new File([h],String(o.name).replace(/\.\w+$/,".jpg"),{type:"image/jpeg",lastModified:o.lastModified})}catch{return o}}function ke(o){return`${Ue(o.size)}-${ni(o.lastModified)}-${ri(o.name)}`}async function qe(o){var a;if(!((a=globalThis.crypto)!=null&&a.subtle))return ke(o);const e=256*1024,t=[o.slice(0,e)];o.size>e&&t.push(o.slice(o.size-e));const i=new Uint8Array(t.reduce((c,d)=>c+d.size,0));let n=0;for(const c of t){const d=new Uint8Array(await c.arrayBuffer());i.set(d,n),n+=d.length}const r=await crypto.subtle.digest("SHA-256",i);return`${Array.from(new Uint8Array(r)).map(c=>c.toString(16).padStart(2,"0")).join("").slice(0,24)}-${Ue(o.size)}`}const Ue=o=>Number(o).toString(16),ni=o=>Number(o||0).toString(16),ri=o=>String(o).replace(/[^\w.-]/g,"").slice(0,24);function si(o="fast"){return o==="strong"||o==="sha256"?qe:typeof o=="function"?o:async e=>ke(e)}const ai=1024*1024;class j{constructor(e,t={}){if(!e||typeof e.put!="function")throw new Error("[KEditor] uploader 需要提供 put() 方法,参见 docs/upload-adapter.md");this.adapter=e,this.chunkSize=Math.max(64*1024,t.chunkSize||ai),this.concurrency=Math.max(1,t.concurrency||3),this.retries=t.retries===void 0?2:Math.max(0,t.retries),this.retryDelay=t.retryDelay??600,this.fingerprint=si(t.fingerprint||"fast"),this.slice=t.slice}async upload(e,t={}){var x,g,$,Qe,et,tt;const{onProgress:i,onChunk:n,signal:r}=t;if(this.adapter.simple)return this.uploadSimple(e,t);const s=Math.max(1,Math.ceil(e.size/this.chunkSize)),a={name:e.name||"blob",size:e.size,type:e.type||ci(e.name),lastModified:e.lastModified||0,fingerprint:await this.fingerprint(e),chunkSize:this.chunkSize,totalChunks:s},c=await((g=(x=this.adapter).init)==null?void 0:g.call(x,a,{signal:r}))||{};if(c.url)return i==null||i(1,{percent:100,loaded:e.size,total:e.size,chunks:s,instant:!0}),{url:c.url,instant:!0,chunks:0,size:e.size,name:a.name,key:c.key};const d=c.uploadId||a.fingerprint,h=new Set((c.uploadedChunks||c.uploaded||[]).map(Number));let p=0;for(const w of h)p+=Math.min(this.chunkSize,e.size-w*this.chunkSize);const u=[];for(let w=0;w<s;w+=1)h.has(w)||u.push(w);const k=new Array(s);let f=h.size;const y=Date.now(),v=()=>{const w=(Date.now()-y)/1e3;i==null||i(e.size?p/e.size:1,{percent:Math.min(100,Math.round(p/Math.max(1,e.size)*100)),loaded:p,total:e.size,chunks:s,uploadedChunks:f,speed:w>0?p/w:0})};v();let C=0,S=null;const A=async()=>{for(;C<u.length;){if(r!=null&&r.aborted)throw new DOMException("已取消上传","AbortError");const w=u[C++],te=this.slice?this.slice(e,w,this.chunkSize):e.slice(w*this.chunkSize,(w+1)*this.chunkSize);let ye=0;for(;;)try{const L=await this.adapter.put({uploadId:d,index:w,total:s,chunkSize:this.chunkSize,blob:te,file:e,meta:a,signal:r,size:te.size});L!=null&&L.url&&(k[w]=L),p+=te.size,f+=1,n==null||n({index:w,total:s,size:te.size}),v();break}catch(L){if((L==null?void 0:L.name)==="AbortError")throw L;if(ye+=1,ye>this.retries)throw S=L,new Error(`分片 ${w+1}/${s} 上传失败:${(L==null?void 0:L.message)||L}`);await li(this.retryDelay*ye,r)}}},H=Array.from({length:Math.max(1,Math.min(this.concurrency,u.length))},A);try{await Promise.all(H)}catch(w){throw await((Qe=($=this.adapter).abort)==null?void 0:Qe.call($,{uploadId:d,meta:a,error:w}).catch(()=>{})),w}if(S)throw S;const E=await((tt=(et=this.adapter).complete)==null?void 0:tt.call(et,{uploadId:d,meta:a,total:s,uploaded:f,chunkResults:k,file:e}))||{},m=E.url;if(!m)throw new Error("[KEditor] uploader.complete() 未返回 url");return{url:m,chunks:s,size:e.size,name:a.name,key:E.key,poster:E.poster,duration:E.duration,raw:E}}async uploadSimple(e,t={}){const{onProgress:i,signal:n}=t,r=Date.now(),s=await this.adapter.upload(e,{signal:n,onProgress:(c,d)=>{const h=d?c/d:0,p=(Date.now()-r)/1e3;i==null||i(h,{percent:Math.round(h*100),loaded:c,total:d||e.size,chunks:1,uploadedChunks:h>=1?1:0,speed:p>0?c/p:0})}}),a=typeof s=="string"?s:s==null?void 0:s.url;if(!a)throw new Error("[KEditor] uploader.upload() 未返回 url");return{url:a,chunks:1,size:e.size,name:e.name,key:typeof s=="object"?s.key:void 0,raw:s}}destroy(){var e,t;(t=(e=this.adapter).destroy)==null||t.call(e)}}const li=(o,e)=>new Promise((t,i)=>{const n=setTimeout(()=>{e==null||e.removeEventListener("abort",r),t()},o),r=()=>{clearTimeout(n),i(new DOMException("已取消上传","AbortError"))};e==null||e.addEventListener("abort",r,{once:!0})});function ci(o=""){var i;const e=(i=String(o).split(".").pop())==null?void 0:i.toLowerCase();return{jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",mp4:"video/mp4",mov:"video/quicktime",webm:"video/webm",m4v:"video/x-m4v"}[e]||"application/octet-stream"}function We(o){return{simple:!0,async upload(e,t={}){const i=await o(di(e),t);return typeof i=="string"?{url:i}:i}}}function di(o,e="blob",t=o.type){return o instanceof File?o:new File([o],e,{type:t})}const ge=o=>new Promise(e=>setTimeout(e,o)),hi=(o,e=.4)=>o*(1-e+Math.random()*e*2);function _e(o={}){const{latency:e=160,speed:t=12,onEvent:i=null,reuseObjectUrl:n=!0,failFirstChunk:r=!1}=o,s=new Map,a=new Map,c=new Map;let d=r;const h=(p,u)=>i==null?void 0:i(p,{...u,at:Date.now()});return{name:"mock",async init(p){h("init",p),await ge(120);const u=s.get(p.fingerprint);if(u)return h("instant",{name:p.name,url:u.url}),{url:u.url,key:p.fingerprint,instant:!0};const k=a.get(p.fingerprint)||new Set;return a.set(p.fingerprint,k),{uploadId:p.fingerprint,uploadedChunks:[...k]}},async put({uploadId:p,index:u,total:k,size:f,blob:y}){if(d&&u===0){d=!1,h("chunk-error",{index:u,total:k,message:"mock: 模拟首个分片网络异常"});const S=new Error("mock: 模拟首个分片网络异常");throw S.retryable=!0,S}const v=Math.max(40,hi(e+f/(t*1024/8)/8,.35));await ge(v);const C=a.get(p)||new Set;return C.add(u),a.set(p,C),h("chunk",{index:u,total:k,size:f,blobSize:y==null?void 0:y.size}),{etag:`${p}-${u}`}},async complete({uploadId:p,meta:u,file:k}){await ge(140);let f=c.get(u.fingerprint);if(!f||!n){const y=k instanceof File?k:new File([k],u.name,{type:u.type});f=URL.createObjectURL(y),c.set(u.fingerprint,f)}return s.set(u.fingerprint,{url:f,name:u.name,size:u.size,type:u.type}),a.delete(p),h("complete",{name:u.name,url:f,chunks:u.totalChunks,size:u.size}),{url:f,key:u.fingerprint}},async abort({uploadId:p}){h("abort",{uploadId:p})},list:()=>[...s.entries()].map(([p,u])=>({key:p,...u})),reset:()=>{s.clear(),a.clear()}}}function Ve(o={}){const{initUrl:e,chunkUrl:t,completeUrl:i,abortUrl:n,mode:r="raw",fieldName:s="file",headers:a={},withCredentials:c=!1,parse:d=k=>(k==null?void 0:k.data)||k||{},chunkUrlFor:h}=o,p=()=>typeof a=="function"?a()||{}:a||{},u=async(k,f={})=>{const y=await fetch(k,{credentials:c?"include":"same-origin",...f});if(!y.ok)throw new Error(`HTTP ${y.status} ${y.statusText}`);const v=await y.text();if(!v)return{};try{return d(JSON.parse(v))}catch{throw new Error(`服务端返回非 JSON 数据:${v.slice(0,80)}`)}};return{name:"http",async init(k,{signal:f}){if(!e)throw new Error("[KEditor] httpAdapter 缺少 initUrl");return u(e,{method:"POST",signal:f,headers:{"Content-Type":"application/json",...p()},body:JSON.stringify({fileName:k.name,fileSize:k.size,fileType:k.type,lastModified:k.lastModified,identifier:k.fingerprint,chunkSize:k.chunkSize,totalChunks:k.totalChunks})})},async put({uploadId:k,index:f,total:y,blob:v,meta:C,signal:S}){if(!t)throw new Error("[KEditor] httpAdapter 缺少 chunkUrl");const A=typeof h=="function"?h({uploadId:k,index:f}):t;if(r==="formdata"){const m=new FormData;return m.append(s,v,`${C.name}.part${f}`),m.append("uploadId",k),m.append("identifier",C.fingerprint),m.append("index",String(f)),m.append("total",String(y)),m.append("filename",C.name),u(A,{method:"POST",body:m,signal:S,headers:p()})}const H=A.includes("?")?"&":"?",E=`${A}${H}uploadId=${encodeURIComponent(k)}&index=${f}&total=${y}&filename=${encodeURIComponent(C.name)}`;return u(E,{method:"PUT",body:v,signal:S,headers:{"Content-Type":"application/octet-stream","X-Chunk-Index":String(f),...p()}})},async complete({uploadId:k,meta:f,total:y}){if(!i)throw new Error("[KEditor] httpAdapter 缺少 completeUrl");return u(i,{method:"POST",headers:{"Content-Type":"application/json",...p()},body:JSON.stringify({uploadId:k,identifier:f.fingerprint,fileName:f.name,fileSize:f.size,fileType:f.type,chunkSize:f.chunkSize,totalChunks:y})})},async abort({uploadId:k}){n&&await u(n,{method:"POST",headers:{"Content-Type":"application/json",...p()},body:JSON.stringify({uploadId:k})}).catch(()=>{})}}}function Ke(o="mock",e={}){if(o instanceof j)return o;if(typeof o=="function"&&!o.put)return new j(We(o),e);if(o&&typeof o=="object"&&!(o instanceof j)){if(typeof o.put=="function"||typeof o.upload=="function")return new j(o,{...e,...Ge(o)});if(o.type==="http")return new j(Ve(o),{...e,...Ge(o)})}return new j(_e(typeof o=="object"?o:{}),e)}const Ge=o=>{const e={};for(const t of["chunkSize","concurrency","retries","fingerprint"])o[t]!==void 0&&(e[t]=o[t]);return e};function pi(o){o.root.addEventListener("paste",async e=>{if(o.readOnly||!o.options.paste.enabled)return;const t=e.clipboardData;if(!t)return;e.preventDefault();const i=ui(t);if(i.length){o.options.paste.uploadFiles?(await o.media.addFiles(i),o.toast.show(`已上传 ${i.length} 个文件`)):o.toast.warn("当前配置不允许粘贴上传文件");return}const n=t.getData("text/html"),r=t.getData("text/plain");if(n&&o.options.paste.clean){let s=Me(n)?ze(n):n;s=K(s,{allowEmpty:!0}),o.options.paste.localizeImages&&(s=await ki(o,s)),o.commands.insertHTML(s,{clean:!1}),Me(n)&&o.toast.show("已清理 Word/WPS 格式")}else if(r){const s=r.split(/\r?\n/).map(a=>`<p>${ce(a)||"<br>"}</p>`).join("");o.commands.insertHTML(s,{clean:!1})}})}function ui(o){var t,i;const e=[];if((t=o.items)!=null&&t.length){for(const n of o.items)if(n.kind==="file"){const r=n.getAsFile();r&&e.push(Xe(r,e.length))}}return!e.length&&((i=o.files)!=null&&i.length)&&e.push(...Array.from(o.files).map((n,r)=>Xe(n,r))),e}function Xe(o,e){if(o.name&&o.name!=="image.png")return o;const t=(o.type.split("/")[1]||"png").replace("jpeg","jpg").replace("+xml",""),i=new Date().toISOString().slice(11,19).replace(/:/g,"");return new File([o],`pasted-${i}-${e}.${t}`,{type:o.type,lastModified:o.lastModified})}function fi(o){const e=o.root;let t=0;const i=n=>{var r;return Array.from(((r=n.dataTransfer)==null?void 0:r.types)||[]).includes("Files")};e.addEventListener("dragenter",n=>{!i(n)||o.readOnly||(n.preventDefault(),t+=1,o.el.classList.add("ke-is-dragover"))}),e.addEventListener("dragover",n=>{!i(n)||o.readOnly||(n.preventDefault(),n.dataTransfer.dropEffect="copy")}),e.addEventListener("dragleave",n=>{i(n)&&(t=Math.max(0,t-1),t===0&&o.el.classList.remove("ke-is-dragover"))}),e.addEventListener("drop",async n=>{if(!i(n)||o.readOnly)return;n.preventDefault(),t=0,o.el.classList.remove("ke-is-dragover"),mi(o,n);const r=[...n.dataTransfer.files||[]];if(r.length&&o.options.paste.uploadFiles){const s=await o.media.addFiles(r);s&&o.toast.show(`已上传 ${s} 个文件`)}})}function mi(o,e){let t=null;if(document.caretRangeFromPoint)t=document.caretRangeFromPoint(e.clientX,e.clientY);else if(document.caretPositionFromPoint){const i=document.caretPositionFromPoint(e.clientX,e.clientY);i&&(t=document.createRange(),t.setStart(i.offsetNode,i.offset),t.collapse(!0))}if(t&&o.root.contains(t.commonAncestorContainer)){const i=window.getSelection();i.removeAllRanges(),i.addRange(t)}else o.focus()}async function ki(o,e){const t=new DOMParser().parseFromString(`<div>${e}</div>`,"text/html"),i=[...t.body.querySelectorAll("img")].filter(n=>/^https?:/i.test(n.getAttribute("src")||""));for(const n of i)try{const r=await fetch(n.src,{mode:"cors"});if(!r.ok)continue;const s=await r.blob(),a=new File([s],n.alt||`remote-${Date.now()}.jpg`,{type:s.type||"image/jpeg"}),c=await o.media.upload(a,"image");n.remove(),c!=null&&c.url&&o.toast.show("外链图片已本地化")}catch{}return t.body.innerHTML.trim()}const Je=1024,be=1024*Je,F={value:"",placeholder:"开始撰写内容,支持拖拽 / 粘贴图片与视频…",height:460,minHeight:320,primaryColor:"#07c160",paperWidth:677,paperMode:"fluid",paperGap:24,paperMaxWidth:0,toolbar:Q,customButtons:[],hideToolbar:!1,hideStatusbar:!1,readOnly:!1,autofocus:!1,maxLength:0,wordCount:!0,sanitize:!0,historyLimit:60,uploader:"mock",upload:{chunkSize:be,concurrency:3,retries:2,fingerprint:"fast"},image:{compress:{maxWidth:1440,quality:.85,minSize:300*Je}},maxImageSize:20*be,maxVideoSize:512*be,imageAccept:"image/png,image/jpeg,image/gif,image/webp,image/bmp,image/svg+xml,image/avif",videoAccept:"video/mp4,video/quicktime,video/webm,video/x-m4v,video/ogg",paste:{enabled:!0,clean:!0,uploadFiles:!0,localizeImages:!1},onChange:null,onReady:null,onError:null,onUpload:null,beforeUpload:null,toolbarFloat:!1};let gi=0;class X{constructor(e,t={}){it(),this.options=yi(t),this.id=`ke-${gi+=1}`,this.el=xi(e,this.id),this.el.__keditor__=this;const i=this.el.innerHTML;this.emitters=new Map,this.domListeners=[],this.destroyed=!1,this.sourceMode=!1,this.previewMode=!1,this.fullscreen=!1,this.readOnly=!1,this.buildDOM(),this.toast=new vt,this.popover=new st(this.el),this.commands=new Jt(this),this.uploader=Ke(this.options.uploader,this.options.upload),this.media=bi(this),this.history=new Qt(this.root,{limit:this.options.historyLimit}),this.toolbar=new Kt(this,this.options.toolbar,this.options.customButtons),this.source=new xt(this),this.previewPanel=new yt(this),this.bubble=new wt(this),this.mainEl.append(this.source.el,this.previewPanel.el),this.applyTheme(),this.setContent(this.options.value||i,{sanitize:this.options.sanitize,silent:!0}),this.bindEvents(),this.setReadOnly(this.options.readOnly),this.refresh(),this.refreshStatus(),this.history.reset(this.root.innerHTML),queueMicrotask(()=>{var n,r;this.destroyed||(this.emit("ready",{editor:this}),(r=(n=this.options).onReady)==null||r.call(n,this),this.options.autofocus&&this.focus())})}buildDOM(){this.el.classList.add("ke"),this.el.id=this.el.id||this.id,this.el.innerHTML="",this.tbEl=l("div.ke-tb",{role:"toolbar","aria-label":"编辑器工具栏"}),this.scrollEl=l("div.ke-scroll"),this.paperEl=l("div.ke-paper"),this.root=l("div.ke-content",{contenteditable:this.readOnly?"false":"true",role:"textbox","aria-multiline":"true",spellcheck:"false","data-placeholder":this.options.placeholder,"data-ke-root":""}),this.root.style.minHeight=`${this.options.minHeight}px`,this.paperEl.appendChild(this.root),this.scrollEl.appendChild(this.paperEl),this.mainEl=l("div.ke-main",{},[this.scrollEl]),this.statusEl=Ci(this),this.dropzoneEl=l("div.ke-dropzone",{},[l("span",{text:"松开即可上传(分片传输)"})]),this.options.hideToolbar||this.el.appendChild(this.tbEl),this.el.appendChild(this.mainEl),this.options.hideStatusbar||this.el.appendChild(this.statusEl),this.el.appendChild(this.dropzoneEl),this.options.height&&(this.scrollEl.style.height=`${this.options.height}px`,this.scrollEl.style.maxHeight=`${this.options.height}px`),this.paperEl.style.setProperty("--ke-min-height",`${this.options.minHeight}px`),this.applyPaper()}applyPaper(){const{paperWidth:e,paperMode:t,paperGap:i,paperMaxWidth:n}=this.options;this.paperEl.style.setProperty("--ke-paper",`${e}px`),this.paperEl.style.setProperty("--ke-paper-gap",`${i}px`),n>0?this.paperEl.style.setProperty("--ke-paper-max",`${n}px`):this.paperEl.style.removeProperty("--ke-paper-max"),this.paperEl.classList.toggle("ke-is-fluid",t!=="fixed")}setPaper(e={}){return e.width!==void 0&&(this.options.paperWidth=I(Number(e.width)||0,200,8e3)),e.mode!==void 0&&(this.options.paperMode=e.mode==="fixed"?"fixed":"fluid"),e.gap!==void 0&&(this.options.paperGap=I(Number(e.gap)||0,0,600)),e.maxWidth!==void 0&&(this.options.paperMaxWidth=Math.max(0,Number(e.maxWidth)||0)),this.applyPaper(),{...this.paperOptions()}}paperOptions(){const{paperWidth:e,paperMode:t,paperGap:i,paperMaxWidth:n}=this.options;return{width:e,mode:t,gap:i,maxWidth:n}}applyTheme(){this.options.primaryColor&&this.el.style.setProperty("--ke-primary",this.options.primaryColor)}bindEvents(){const e=ot(()=>this.emitChange(),160);this.bind(this.root,"input",()=>{this.history.snapshot(),this.refreshStatus(),this.togglePlaceholder(),e(),this.enforceMaxLength()}),this.bind(this.root,"keydown",t=>this.handleKeydown(t)),this.bind(this.root,"blur",()=>{this.history.flush(),this.el.classList.remove("ke-is-focus"),this.emit("blur")}),this.bind(this.root,"focus",()=>{this.el.classList.add("ke-is-focus"),this.emit("focus")}),this.bind(this.root,"click",t=>this.handleContentClick(t)),this.bind(this.root,"dblclick",t=>{const i=t.target.closest("img");i&&this.root.contains(i)&&J(i.src)}),pi(this),fi(this),this.selectionHandler=()=>{!this.root.contains(document.activeElement)&&document.activeElement!==this.root||(this.refresh(),this.syncBubble())},document.addEventListener("selectionchange",this.selectionHandler),this.scrollHandler=()=>this.bubble.position(),this.bind(this.scrollEl,"scroll",this.scrollHandler),window.addEventListener("resize",this.scrollHandler)}bind(e,t,i){return e.addEventListener(t,i),this.domListeners.push({node:e,type:t,handler:i}),i}handleKeydown(e){const t=e.metaKey||e.ctrlKey,i=e.key.toLowerCase();if(t&&i==="z"){e.preventDefault(),e.shiftKey?this.redo():this.undo();return}if(t&&i==="y"){e.preventDefault(),this.redo();return}if(t&&["b","i","u"].includes(i)){e.preventDefault(),this.commands.toggleMark({b:"bold",i:"italic",u:"underline"}[i]),this.refresh();return}if(t&&e.shiftKey&&i==="k"){e.preventDefault(),this.toggleSource();return}if(t&&i==="k"){e.preventDefault(),this.toolbar.openLink();return}if(t&&i==="s"){e.preventDefault(),this.emit("save",{html:this.getHTML()});return}if(e.key==="Escape"){this.popover.close(),this.bubble.hide(),this.previewMode&&this.closePreview();return}(e.key==="Backspace"||e.key==="Delete")&&this.bubble.node&&(e.preventDefault(),this.bubble.remove())}handleContentClick(e){const t=e.target.closest("[data-k-media]");if(t&&this.root.contains(t)){this.selectMedia(t);return}this.clearMediaSelection(),this.bubble.hide()}selectMedia(e){this.clearMediaSelection(),e.classList.add("ke-is-selected-media"),this.bubble.show(e),this.refreshStatus()}clearMediaSelection(){this.root.querySelectorAll(".ke-is-selected-media").forEach(e=>e.classList.remove("ke-is-selected-media")),this.bubble.hide()}syncBubble(){!this.bubble.node||!this.root.contains(this.bubble.node)?this.bubble.hide():this.bubble.position()}getState(){var a,c,d;const e=z(this.root),t=N((e==null?void 0:e.commonAncestorContainer)||this.root,this.root),i=e?Si(e,this.root):null,n=(a=this.bubble)==null?void 0:a.node,r=n&&((c=n.dataset)==null?void 0:c.kMedia)==="image"?n.querySelector("img"):null,s=r?oe(r):Ei(e,t);return{bold:this.queryState("bold"),italic:this.queryState("italic"),underline:this.queryState("underline"),strikeThrough:this.queryState("strikeThrough"),ul:this.queryState("insertUnorderedList"),ol:this.queryState("insertOrderedList"),align:s,block:((d=t==null?void 0:t.tagName)==null?void 0:d.toLowerCase())||"p",fontSize:this.commands.currentFontSize(),linkUrl:i?i.getAttribute("href"):"",linkTarget:i?i.getAttribute("target")==="_blank":!1,selectionText:e?e.toString():"",canUndo:this.history.canUndo(),canRedo:this.history.canRedo(),source:this.sourceMode,preview:this.previewMode,fullscreen:this.fullscreen,readOnly:this.readOnly}}queryState(e){var t;if(!this.root.contains(((t=window.getSelection())==null?void 0:t.anchorNode)||null))return!1;try{return document.queryCommandState(e)}catch{return!1}}refresh(){if(!this.destroyed)try{this.toolbar.refresh(this.getState())}catch{}}refreshStatus(){const e=this.statusApi;e&&e.update(this.counts())}counts(){const e=Te(this.root.innerHTML);return{chars:e.replace(/\s/g,"").length,words:Li(e),images:this.root.querySelectorAll("img").length,videos:this.root.querySelectorAll('[data-k-media="video"] video, video').length,uploading:this.media?this.media.tasks.size:0}}togglePlaceholder(){const e=!this.root.textContent.trim()&&!this.root.querySelector("img,video,hr,table,iframe");this.root.classList.toggle("ke-is-empty",e)}enforceMaxLength(){var i,n;const e=this.options.maxLength;if(!e)return;const{chars:t}=this.counts();t>e?(this.toast.warn(`已超过建议字数 ${e}`),(i=this.statusEl)==null||i.classList.add("ke-is-over")):(n=this.statusEl)==null||n.classList.remove("ke-is-over")}getHTML({clean:e=!0}={}){const t=this.root.innerHTML;return e?Ze(t):t}getText(){return Te(this.root.innerHTML)}getJSON(){return{html:this.getHTML(),text:this.getText(),counts:this.counts()}}setContent(e,{sanitize:t=this.options.sanitize,silent:i=!1}={}){const n=K(e||"<p><br></p>",{allowEmpty:!0});return this.root.innerHTML=n||"<p><br></p>",this.afterEdit({silent:i}),i||this.history.snapshot(!0),this.togglePlaceholder(),this}appendHTML(e){const t=document.createRange();t.selectNodeContents(this.root),t.collapse(!1);const i=window.getSelection();return i.removeAllRanges(),i.addRange(t),this.commands.insertHTML(e),this}clear(){return this.media.cancelAll(),this.setContent("<p><br></p>"),this.focus(),this}afterEdit({silent:e=!1}={}){this.history.snapshot(),this.refreshStatus(),this.togglePlaceholder(),e||this.emitChange()}commitHistory(){this.history.snapshot(!0),this.refreshStatus(),this.emitChange()}emitChange(){var e,t;this.emit("change",{html:this.getHTML(),text:this.getText()}),(t=(e=this.options).onChange)==null||t.call(e,this.getHTML(),this)}focus(){if(this.readOnly||this.sourceMode)return this.sourceMode&&this.source.code.focus(),this;this.root.focus();const e=window.getSelection();if(!e||e.rangeCount===0||!this.root.contains(e.anchorNode)){const t=document.createRange(),i=this.root.firstElementChild||this.root;t.selectNodeContents(i),t.collapse(!1),e.removeAllRanges(),e.addRange(t)}return this}blur(){return this.root.blur(),this}saveSelection(){const e=z(this.root);return this.savedRange=e?e.cloneRange():null,this}restoreSelection(){this.root.focus();const e=window.getSelection();return this.savedRange&&this.root.contains(this.savedRange.startContainer)&&this.root.contains(this.savedRange.endContainer)?(e.removeAllRanges(),e.addRange(this.savedRange),this):this.focus()}setReadOnly(e){return this.readOnly=!!e,this.root.setAttribute("contenteditable",this.readOnly?"false":"true"),this.el.classList.toggle("ke-is-readonly",this.readOnly),this.refresh(),this}undo(){return this.history.flush(),this.history.undo()?(this.afterEdit({silent:!1}),this.refresh(),this):(this.toast.show("没有可撤销的操作"),this)}redo(){return this.history.redo()?(this.afterEdit(),this.refresh(),this):(this.toast.show("没有可重做的操作"),this)}upload(e,t=this.media.kindOf(e)){if(!t)throw new Error("[KEditor] 不支持的文件类型");return this.media.upload(e,t)}insertImage(e,t=""){return this.media.insertImageUrl(e,t)}insertVideo(e,t="视频"){return this.media.insertVideoUrl(e,t)}cancelUploads(){return this.media.cancelAll(),this}addButton(e,t){return this.toolbar.addButton(e,t)}moveButton(e,t){return this.toolbar.moveButton(e,t)}removeButton(e){return this.toolbar.removeButton(e)}setButtonOptions(e,t){return this.toolbar.setButtonOptions(e,t)}getButtonValue(e){return this.toolbar.getButtonValue(e)}setButtonValue(e,t){return this.toolbar.setButtonValue(e,t)}reportError(e,t){var r,s,a;const i=t&&t.message?t.message:String(t),n={type:e,error:t instanceof Error?t:new Error(i),message:i};return(r=this.toast)==null||r.error(i),this.emit("error",n),(a=(s=this.options).onError)==null||a.call(s,n),this}toggleSource(){return this.sourceMode?this.exitSource():this.enterSource(),this.sourceMode}enterSource(){this.sourceMode||(this.history.flush(),this.sourceMode=!0,this.el.classList.add("ke-is-source"),this.clearMediaSelection(),this.source.show(this.getHTML({clean:!0})),this.previewPanel.hide(),this.previewMode=!1,this.refresh(),this.emit("sourcechange",{mode:"source"}))}exitSource(){this.sourceMode&&(this.source.apply({silent:!0}),this.sourceMode=!1,this.el.classList.remove("ke-is-source"),this.source.hide(),this.focus(),this.refresh(),this.emit("sourcechange",{mode:"visual"}))}togglePreview(){return this.previewMode?this.closePreview():this.openPreview(),this.previewMode}openPreview(){this.previewMode=!0,this.previewPanel.show(Mi(this.getHTML())),this.refresh()}closePreview(){this.previewMode=!1,this.previewPanel.hide(),this.refresh()}toggleFullscreen(){return this.fullscreen=!this.fullscreen,this.el.classList.toggle("ke-is-fullscreen",this.fullscreen),document.body.style.overflow=this.fullscreen?"hidden":"",this.refresh(),this.fullscreen}on(e,t){return this.addListener(e,t)}off(e,t){return this.removeListener(e,t)}emit(e,t={}){var n,r,s,a;const i=this.emitters.get(e)||[];for(const c of i)try{c(t)}catch(d){(r=(n=this.options).onError)==null||r.call(n,d)}return e.startsWith("upload")&&((a=(s=this.options).onUpload)==null||a.call(s,{stage:e,...t})),this}addListener(e,t){return this.emitters.has(e)||this.emitters.set(e,[]),this.emitters.get(e).push(t),()=>this.removeListener(e,t)}removeListener(e,t){const i=this.emitters.get(e)||[],n=i.indexOf(t);return n>=0&&i.splice(n,1),this}get element(){return this.root}get editorElement(){return this.el}destroy(){if(!this.destroyed){this.destroyed=!0,this.media.destroy(),this.history.destroy(),this.popover.destroy(),this.source.destroy(),this.previewPanel.destroy(),this.bubble.destroy(),this.toolbar.destroy(),this.toast.destroy();for(const{node:e,type:t,handler:i}of this.domListeners)e.removeEventListener(t,i);document.removeEventListener("selectionchange",this.selectionHandler),this.scrollEl.removeEventListener("scroll",this.scrollHandler),window.removeEventListener("resize",this.scrollHandler),this.fullscreen&&(document.body.style.overflow=""),this.el.__keditor__===this&&(this.el.__keditor__=null),this.el.innerHTML="",this.el.classList.remove("ke","ke-is-fullscreen","ke-is-readonly"),this.el.removeAttribute("style"),this.emitters.clear()}}static create(e,t){return new X(e,t)}}function bi(o){const e=new ii(o),t=e.upload.bind(e);return e.upload=async(i,n)=>{const r=o.options.beforeUpload;let s=i;return r&&(s=await r(i,n),s===!1)?null:t(s,n)},e.replaceNode=async(i,n)=>{const r=i.dataset.kMedia==="video"?"video":"image",s=document.createRange();s.setStartBefore(i),s.collapse(!0);const a=window.getSelection();a.removeAllRanges(),a.addRange(s);const c=await e.upload(n,r);return i.remove(),o.commitHistory(),c},e}function xi(o,e){if(typeof o=="string"){const t=document.querySelector(o);if(!t)throw new Error(`[KEditor] 找不到挂载节点:${o}`);return t}if(o instanceof HTMLElement)return o;if((o==null?void 0:o.$el)instanceof HTMLElement)return o.$el;throw new Error(`[KEditor] 无效的挂载目标(${typeof o})`)}function yi(o){const e={...F,...o};return e.image={...F.image,...o.image||{}},e.paste={...F.paste,...o.paste||{}},e.upload={...F.upload,...o.upload||{}},e.customButtons=Be(o.customButtons),Array.isArray(o.toolbar)&&(e.toolbar=o.toolbar),o.toolbar===!1&&(e.toolbar=[]),o.toolbar===!0&&(e.toolbar=Q),e.customButtons.length&&o.toolbar!==!1&&(e.toolbar=wi(e.toolbar,e.customButtons)),e.height=I(e.height??460,0,4e3),e.paperWidth=I(Number(e.paperWidth)||F.paperWidth,200,8e3),e.paperMode=e.paperMode==="fixed"?"fixed":"fluid",e.paperGap=Number.isFinite(Number(e.paperGap))?I(Number(e.paperGap),0,600):F.paperGap,e.paperMaxWidth=Math.max(0,Number(e.paperMaxWidth)||0),e}const vi=o=>o!=="|"&&o!==":tail";function wi(o,e){const t=[...o],i=[];for(const n of e)if(!t.includes(n.name)){if(n.position==null){i.push(n.name);continue}t.splice(Ye(t,n.position),0,n.name)}return i.length&&t.splice(Ye(t,null),0,"|",...i),t}function Ye(o,e){const t=(()=>{const s=o.indexOf(":tail");return s<0?o.length:s})();if(e==null||e==="end")return t;if(e==="start")return 0;if(e==="tail")return o.length;if(typeof e=="number"){let s=0;for(let a=0;a<o.length;a++)if(vi(o[a])){if(s===Math.max(0,Math.floor(e)))return a;s++}return t}const i=!!(e&&typeof e=="object"&&e.after),n=String(typeof e=="string"?e:(i?e.after:e.before)||""),r=o.indexOf(n);return r<0?t:i?r+1:r}function Ci(o){const e=l("b",{text:"0"}),t=l("b",{text:"0"}),i=l("b",{text:"0"}),n=l("b",{text:"0"}),r=l("span.ke-chip",{hidden:!0}),s=l("span.ke-status-hint",{text:"支持拖拽 / 粘贴上传,Ctrl/⌘ + S 保存"}),a=l("span.ke-status-tail"),c=l("div.ke-status",{},[l("span",{},["字数 ",e," · ",t," 词"]),l("span",{},["图片 ",i," · 视频 ",n]),r,s,a]),d={update:h=>{e.textContent=String(h.chars),t.textContent=String(h.words),i.textContent=String(h.images),n.textContent=String(h.videos),h.uploading>0?(r.hidden=!1,r.className="ke-chip ke-is-busy",r.textContent=`${h.uploading} 个上传进行中`):r.hidden=!0},addExtra:h=>a.appendChild(h)};return o.statusApi=d,o.options.wordCount||(c.style.display="none"),c}function Si(o,e){var n;let t=o==null?void 0:o.commonAncestorContainer;if(!t||!e.contains(t))return null;t.nodeType===3&&(t=t.parentElement);const i=(n=t==null?void 0:t.closest)==null?void 0:n.call(t,"a");return i&&e.contains(i)?i:null}function Ei(o,e){var n,r;const t=e||(o==null?void 0:o.commonAncestorContainer),i=[t,t==null?void 0:t.parentElement].filter(s=>s&&s.nodeType===1);for(const s of i){const a=(n=s.style)==null?void 0:n.textAlign;if(a)return a==="-webkit-justify"?"justify":a;const c=(r=s.getAttribute)==null?void 0:r.call(s,"align");if(c)return c}try{if(document.queryCommandState("justifyCenter"))return"center";if(document.queryCommandState("justifyRight"))return"right";if(document.queryCommandState("justifyFull"))return"justify"}catch{}return"left"}function Li(o){const e=(o.match(/[\u4e00-\u9fa5\u3040-\u30ff]/g)||[]).length,t=(o.match(/[a-zA-Z0-9'’-]+/g)||[]).length;return e+t}function Ze(o){const t=new DOMParser().parseFromString(`<div>${o}</div>`,"text/html").body.firstChild;return t.querySelectorAll("[contenteditable]").forEach(i=>i.removeAttribute("contenteditable")),t.querySelectorAll("[data-k-id]").forEach(i=>i.removeAttribute("data-k-id")),t.querySelectorAll("[data-k-state]").forEach(i=>i.removeAttribute("data-k-state")),t.querySelectorAll("[data-ke-marker]").forEach(i=>i.removeAttribute("data-ke-marker")),t.querySelectorAll("[data-placeholder]").forEach(i=>i.removeAttribute("data-placeholder")),t.querySelectorAll(".ke-is-selected-media").forEach(i=>i.classList.remove("ke-is-selected-media")),t.querySelectorAll('[data-k-state="uploading"], [data-k-state="error"]').forEach(i=>i.remove()),t.innerHTML.trim()}function Mi(o){const t=new DOMParser().parseFromString(`<div>${o}</div>`,"text/html").body.firstChild;return t.querySelectorAll("[data-k-media]").forEach(i=>{i.removeAttribute("data-k-media"),i.removeAttribute("data-k-url")}),t.innerHTML}const zi="1.0.7";function xe(o,e={}){return new X(o,e)}const Ti=xe;function Ai(o,e={}){const t=typeof o=="string"?document.querySelector(o):o;return t!=null&&t.__keditor__&&t.__keditor__.destroy(),xe(t,e)}b.ChunkUploader=j,b.DEFAULT_TOOLBAR=Q,b.KEditor=X,b.cleanWordHtml=ze,b.create=xe,b.createUploader=Ke,b.default=X,b.defaults=F,b.escapeHtml=ce,b.exportHtml=Ze,b.fastFingerprint=ke,b.formatHtml=ae,b.httpAdapter=Ve,b.isSafeUrl=Y,b.maybeCompress=Ie,b.mockAdapter=_e,b.mount=Ti,b.normalizeCustomButtons=Be,b.normalizeItems=G,b.normalizePosition=de,b.replace=Ai,b.sanitizeHtml=K,b.simpleAdapter=We,b.strongFingerprint=qe,b.version=zi,Object.defineProperties(b,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "kyle-editor",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.7",
|
|
4
4
|
"description": "轻量、美观的微信公众号风格富文本编辑器(纯前端,支持图片/视频分片上传、HTML 源码模式),可通过 <script> 引入或作为 Vue 3 组件安装。",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/keditor.cjs",
|
|
@@ -25,8 +25,6 @@
|
|
|
25
25
|
"files": [
|
|
26
26
|
"dist",
|
|
27
27
|
"types",
|
|
28
|
-
"imgs",
|
|
29
|
-
"docs",
|
|
30
28
|
"README.md",
|
|
31
29
|
"LICENSE"
|
|
32
30
|
],
|