wds-editor 1.0.0 → 1.1.0

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.
@@ -1,11 +1,8 @@
1
- (function(T,$){typeof exports=="object"&&typeof module<"u"?$(exports,require("prosemirror-state"),require("prosemirror-view"),require("prosemirror-history"),require("prosemirror-model"),require("prosemirror-schema-list"),require("prosemirror-tables"),require("prosemirror-inputrules"),require("prosemirror-keymap"),require("prosemirror-commands"),require("prosemirror-gapcursor"),require("prosemirror-dropcursor")):typeof define=="function"&&define.amd?define(["exports","prosemirror-state","prosemirror-view","prosemirror-history","prosemirror-model","prosemirror-schema-list","prosemirror-tables","prosemirror-inputrules","prosemirror-keymap","prosemirror-commands","prosemirror-gapcursor","prosemirror-dropcursor"],$):(T=typeof globalThis<"u"?globalThis:T||self,$(T.WDSEditor={},T.PMState,T.PMView,T.PMHistory,T.PMModel,T["PMSchema-list"],T.PMTables,T.PMInputrules,T.PMKeymap,T.PMCommands,T.PMGapcursor,T.PMDropcursor))})(this,(function(T,$,pe,Y,J,ae,N,X,Te,U,zt,Ht){"use strict";const Pt=/^(https?:|mailto:|tel:)/i,Qe=/^[a-z][a-z0-9+.-]*:/i;function V(t){if(t==null)return null;const e=t.trim();if(!e)return null;const n=e.replace(/[\u0000- \u007f-\u009f]/g,"");return Qe.test(n)&&!Pt.test(n)?null:e}function Ze(t){const e=t.trim();return e?/^[^\s@/]+@[^\s@/]+\.[^\s@/]+$/.test(e)?`mailto:${e}`:!Qe.test(e)&&!/^[/#?.]/.test(e)&&/^[\w-]+(\.[\w-]+)+/.test(e)?`https://${e}`:V(e):null}function Bt(t){return t.replace(/<!--[\s\S]*?-->/g,"").replace(/<\/?o:p[^>]*>/gi,"").replace(/<\/?(w|m|v):[^>]*>/gi,"").replace(/<xml[\s\S]*?<\/xml>/gi,"").replace(/<style[\s\S]*?<\/style>/gi,"").replace(/<meta[^>]*>/gi,"").replace(/<link[^>]*>/gi,"")}const et={black:"#000000",white:"#ffffff",red:"#ff0000",green:"#008000",blue:"#0000ff",yellow:"#ffff00",orange:"#ffa500",purple:"#800080",pink:"#ffc0cb",gray:"#808080",grey:"#808080",silver:"#c0c0c0",navy:"#000080",teal:"#008080",maroon:"#800000",olive:"#808000",lime:"#00ff00",aqua:"#00ffff",cyan:"#00ffff",fuchsia:"#ff00ff",magenta:"#ff00ff",darkred:"#8b0000",darkblue:"#00008b",darkgreen:"#006400",lightgray:"#d3d3d3",lightgrey:"#d3d3d3",darkgray:"#a9a9a9",darkgrey:"#a9a9a9"},De=t=>Math.max(0,Math.min(255,Math.round(t))).toString(16).padStart(2,"0");function se(t){if(!t)return null;const e=t.trim().toLowerCase().replace(/\s*!important$/,"");if(et[e])return et[e];let n=/^#([0-9a-f]{3})$/.exec(e);return n?"#"+[...n[1]].map(r=>r+r).join(""):(n=/^#([0-9a-f]{6})(ff)?$/.exec(e),n?"#"+n[1]:(n=/^rgba?\(\s*(\d+(?:\.\d+)?)[\s,]+(\d+(?:\.\d+)?)[\s,]+(\d+(?:\.\d+)?)(?:\s*[,/]\s*([\d.]+%?))?\s*\)$/.exec(e),n?n[4]!==void 0&&(n[4].endsWith("%")?parseFloat(n[4])/100:parseFloat(n[4]))<1?null:"#"+De(+n[1])+De(+n[2])+De(+n[3]):null))}function tt(t){const e=se(t);return e&&e!=="#000000"?e:null}function Ne(t){const e=se(t)??se((t??"").split(/\s+(?![^(]*\))/).find(n=>se(n)));return e&&e!=="#ffffff"?e:null}const Ft=[{color:"#dc2626",name:"colorRed"},{color:"#ea580c",name:"colorOrange"},{color:"#ca8a04",name:"colorAmber"},{color:"#16a34a",name:"colorGreen"},{color:"#0d9488",name:"colorTeal"},{color:"#2563eb",name:"colorBlue"},{color:"#7c3aed",name:"colorPurple"},{color:"#db2777",name:"colorPink"},{color:"#475569",name:"colorSlate"},{color:"#94a3b8",name:"colorGray"}],Ut=[{color:"#fef08a",name:"colorYellow"},{color:"#bbf7d0",name:"colorGreen"},{color:"#bae6fd",name:"colorBlue"},{color:"#fbcfe8",name:"colorPink"},{color:"#fed7aa",name:"colorOrange"},{color:"#e9d5ff",name:"colorPurple"}],_t=["left","center","right","justify"];function nt(t){const e=(t.style.textAlign||t.getAttribute("align")||"").toLowerCase();return _t.includes(e)&&e!=="left"?e:null}function rt(t){return t?{style:`text-align: ${t}`}:{}}const qt={left:"float: left; margin: 0 1em 1em 0",right:"float: right; margin: 0 0 1em 1em",center:"display: block; margin-left: auto; margin-right: auto"},Wt={left:"float: left; margin: 0 1em 1em 0",right:"float: right; margin: 0 0 1em 1em",center:"display: table; margin-left: auto; margin-right: auto"};function Gt(t){const e=t.style.float||t.getAttribute("align")||"";return e==="left"||e==="right"?e:(t.style.display==="block"||t.style.display==="table")&&t.style.marginLeft==="auto"&&t.style.marginRight==="auto"?"center":null}const it={src:{},alt:{default:""},title:{default:null},width:{default:null},height:{default:null},align:{default:null}};function ot(t,e){const n=V(t.getAttribute("src"));return n?{src:n,alt:t.getAttribute("alt")??"",title:t.getAttribute("title"),width:at(t.getAttribute("width")??t.style.width),height:at(t.getAttribute("height")??t.style.height),align:Gt(e)}:!1}function Ie(t,e){const{src:n,alt:r,title:i,width:a,height:l,align:d}=t,o={src:n,alt:r??""};i&&(o.title=i),a&&(o.width=String(a)),a&&l&&(o.height=String(l));const s=e?qt[d]:void 0;return s&&(o.style=s),o}function at(t){const e=/^\s*(\d{1,5})(px)?\s*$/.exec(t??"");return e?Number(e[1]):null}const jt={doc:{content:"block+"},paragraph:{content:"inline*",group:"block",attrs:{align:{default:null}},parseDOM:[{tag:"p",getAttrs:t=>({align:nt(t)})}],toDOM:t=>["p",rt(t.attrs.align),0]},heading:{content:"inline*",group:"block",defining:!0,attrs:{level:{default:2},align:{default:null}},parseDOM:[1,2,3,4,5,6].map(t=>({tag:`h${t}`,getAttrs:e=>({level:Math.min(t,4),align:nt(e)})})),toDOM:t=>[`h${t.attrs.level}`,rt(t.attrs.align),0]},blockquote:{content:"block+",group:"block",defining:!0,parseDOM:[{tag:"blockquote"}],toDOM:()=>["blockquote",0]},horizontal_rule:{group:"block",parseDOM:[{tag:"hr"}],toDOM:()=>["hr"]},code_block:{content:"text*",marks:"",group:"block",code:!0,defining:!0,attrs:{language:{default:null}},parseDOM:[{tag:"pre",preserveWhitespace:"full",getAttrs:t=>{const e=t.querySelector("code"),n=/language-([\w-]+)/.exec(e?.className??"");return{language:n?n[1]:null}}}],toDOM:t=>["pre",["code",t.attrs.language?{class:`language-${t.attrs.language}`}:{},0]]},...N.tableNodes({tableGroup:"block",cellContent:"block+",cellAttributes:{}}),text:{group:"inline"},image:{inline:!0,group:"inline",draggable:!0,attrs:it,parseDOM:[{tag:"img[src]",getAttrs:t=>ot(t,t)}],toDOM:t=>["img",Ie(t.attrs,!0)]},figure:{group:"block",content:"inline*",marks:"_",draggable:!0,isolating:!0,attrs:it,parseDOM:[{tag:"figure",getAttrs:t=>{const e=t.querySelector("img");return e?ot(e,t):!1},contentElement:t=>t.querySelector("figcaption")??document.createElement("figcaption")}],toDOM:t=>{const e=Wt[t.attrs.align];return["figure",e?{style:e}:{},["img",Ie(t.attrs,!1)],["figcaption",0]]}},hard_break:{inline:!0,group:"inline",selectable:!1,parseDOM:[{tag:"br"}],toDOM:()=>["br"]}},Vt={link:{attrs:{href:{},title:{default:null},target:{default:null}},inclusive:!1,parseDOM:[{tag:"a[href]",getAttrs:t=>{const e=t,n=V(e.getAttribute("href"));return n?{href:n,title:e.getAttribute("title"),target:e.getAttribute("target")==="_blank"?"_blank":null}:!1}}],toDOM:t=>{const e={href:t.attrs.href};return t.attrs.title&&(e.title=t.attrs.title),t.attrs.target==="_blank"&&(e.target="_blank",e.rel="noopener noreferrer"),["a",e,0]}},strong:{parseDOM:[{tag:"strong"},{tag:"b",getAttrs:t=>t.style.fontWeight!=="normal"&&null},{style:"font-weight=400",clearMark:t=>t.type.name==="strong"},{style:"font-weight",getAttrs:t=>/^(bold(er)?|[5-9]\d{2,})$/.test(t)&&null}],toDOM:()=>["strong",0]},em:{parseDOM:[{tag:"i"},{tag:"em"},{style:"font-style=italic"},{style:"font-style=normal",clearMark:t=>t.type.name==="em"}],toDOM:()=>["em",0]},underline:{parseDOM:[{tag:"u"},{style:"text-decoration=underline"},{style:"text-decoration-line=underline"}],toDOM:()=>["u",0]},strike:{parseDOM:[{tag:"s"},{tag:"del"},{tag:"strike"},{style:"text-decoration=line-through"},{style:"text-decoration-line=line-through"}],toDOM:()=>["s",0]},textColor:{attrs:{color:{}},parseDOM:[{tag:"span",getAttrs:t=>{const e=tt(t.style.color);return e?{color:e}:!1}},{tag:"font[color]",getAttrs:t=>{const e=tt(t.getAttribute("color"));return e?{color:e}:!1}}],toDOM:t=>["span",{style:`color: ${t.attrs.color}`},0]},highlight:{attrs:{color:{default:"#fef08a"}},parseDOM:[{tag:"mark",getAttrs:t=>({color:Ne(t.style.backgroundColor)??"#fef08a"})},{style:"background-color",getAttrs:t=>{const e=Ne(t);return e?{color:e}:!1}},{style:"background",getAttrs:t=>{const e=Ne(t);return e?{color:e}:!1}}],toDOM:t=>["mark",{style:`background-color: ${se(t.attrs.color)??"#fef08a"}`},0]},code:{parseDOM:[{tag:"code"}],toDOM:()=>["code",0]}},st=new J.Schema({nodes:jt,marks:Vt}),f=new J.Schema({nodes:ae.addListNodes(st.spec.nodes,"paragraph block*","block"),marks:st.spec.marks}),Kt=J.DOMSerializer.fromSchema(f),Yt=J.DOMParser.fromSchema(f);function Me(t){const e=new window.DOMParser().parseFromString(`<!doctype html><body>${t}`,"text/html");return Yt.parse(e.body)}function Le(t){if(lt(t))return"";const e=document.createElement("div");return e.append(Kt.serializeFragment(t.content)),e.querySelectorAll("[style]").forEach(n=>n.setAttribute("style",Xt(n.getAttribute("style")??""))),e.innerHTML}const Jt=(t,e,n,r)=>"#"+[e,n,r].map(i=>(+i).toString(16).padStart(2,"0")).join("");function Xt(t){return t.split(";").map(e=>e.trim()).filter(Boolean).map(e=>e.replace(/rgb\(\s*(\d+),\s*(\d+),\s*(\d+)\s*\)/g,Jt).replace(/(^|[\s:])0px(?![\w.])/g,(n,r)=>`${r}0`).replace(/\s*:\s*/,": ")).join("; ")}function lt(t){const e=t.firstChild;return t.childCount===1&&!!e&&e.type===f.nodes.paragraph&&e.content.size===0&&!e.attrs.align}const Qt="p|h[1-6]|blockquote|pre|ul|ol|li|table|thead|tbody|tr|figure";function ct(t){const e=t.replace(new RegExp(`(<\\/(?:${Qt})>|<hr>)`,"g"),`$1
2
- `).replace(new RegExp("(<(?:ul|ol|blockquote)(?:\\s[^>]*)?>)","g"),`$1
3
- `).split(`
4
- `).map(r=>r.trim()).filter(Boolean);let n=0;return e.map(r=>{/^<\/(ul|ol|blockquote)>/.test(r)&&(n=Math.max(0,n-1));const i=" ".repeat(n)+r;return/^<(ul|ol|blockquote)(\s[^>]*)?>$/.test(r)?n++:/<\/(ul|ol|blockquote)>$/.test(r)&&!/^<\/(ul|ol|blockquote)>/.test(r)&&(n=Math.max(0,n-1)),i}).join(`
5
- `)}function me(t,e){const{from:n,$from:r,to:i,empty:a}=t.selection;return a?!!e.isInSet(t.storedMarks||r.marks()):t.doc.rangeHasMark(n,i,e)}function Zt(t){const e=t.selection.$from.parent;return e.type===f.nodes.paragraph?"paragraph":e.type===f.nodes.code_block?"codeBlock":e.type===f.nodes.heading?`heading${e.attrs.level}`:null}function en(t){return t==="paragraph"?U.setBlockType(f.nodes.paragraph):t==="codeBlock"?U.setBlockType(f.nodes.code_block):U.setBlockType(f.nodes.heading,{level:Number(t.slice(-1))})}const _=t=>U.toggleMark(f.marks[t]);function dt(t,e){const{$from:n}=t.selection;for(let r=n.depth;r>0;r--)if(n.node(r).type===e)return!0;return!1}function ut(t){const{$from:e}=t.selection;for(let n=e.depth;n>0;n--){const r=e.node(n).type;if(r===f.nodes.bullet_list||r===f.nodes.ordered_list)return r}return null}function ht(t){return(e,n,r)=>{const{$from:i}=e.selection;for(let a=i.depth;a>0;a--){const l=i.node(a);if(l.type===f.nodes.bullet_list||l.type===f.nodes.ordered_list)return l.type===t?ae.liftListItem(f.nodes.list_item)(e,n,r):(n&&n(e.tr.setNodeMarkup(i.before(a),t)),!0)}return ae.wrapInList(t)(e,n,r)}}const Oe=ae.sinkListItem(f.nodes.list_item),$e=(t,e,n)=>ae.liftListItem(f.nodes.list_item)(t,e,n)||U.lift(t,e);function tn(){return(t,e)=>dt(t,f.nodes.blockquote)?U.lift(t,e):U.wrapIn(f.nodes.blockquote)(t,e)}function Q(t){return(e,n)=>{const r=t==="left"?null:t,{from:i,to:a}=e.selection,l=e.tr;let d=!1;return e.doc.nodesBetween(i,a,(o,s)=>o.type===f.nodes.paragraph||o.type===f.nodes.heading?(d=!0,o.attrs.align!==r&&l.setNodeMarkup(s,void 0,{...o.attrs,align:r}),!1):!0),d?(n&&n(l),!0):!1}}function xe(t){return t.selection.$from.parent.attrs.align??"left"}const nn=(t,e)=>{const n=f.nodes.horizontal_rule;if(!e)return!0;const r=t.tr.replaceSelectionWith(n.create()),i=r.selection.$from;return!i.nodeAfter&&i.parent.type===f.nodes.doc&&r.insert(i.pos,f.nodes.paragraph.create()),e(r.scrollIntoView()),!0},rn=(t,e)=>{const{from:n,to:r,empty:i}=t.selection,a=t.tr;if(i)a.setStoredMarks([]);else for(const l of Object.values(f.marks))l!==f.marks.link&&a.removeMark(n,r,l);return t.doc.nodesBetween(n,r,(l,d)=>l.isTextblock&&l.type!==f.nodes.paragraph?(a.setBlockType(d,d+l.nodeSize,f.nodes.paragraph),!1):(l.type===f.nodes.paragraph&&l.attrs.align&&a.setNodeMarkup(d,void 0,{align:null}),!0)),e&&e(a),!0};function Re(t){const e=f.marks.link,{$from:n,from:r,to:i,empty:a}=t.selection;if(!a){let u=null;return t.doc.nodesBetween(r,i,(p,g)=>{const v=e.isInSet(p.marks);v&&!u&&(u={from:Math.max(g,r),to:Math.min(g+p.nodeSize,i),...v.attrs})}),u}const l=e.isInSet(n.marks())??e.isInSet(n.nodeBefore?.marks??[]);if(!l)return null;const d=n.start(),o=[];let s=0;n.parent.forEach(u=>{const p=d+s,g=p+u.nodeSize;if(l.isInSet(u.marks)){const v=o[o.length-1];v&&v[1]===p?v[1]=g:o.push([p,g])}s+=u.nodeSize});const c=o.find(([u,p])=>u<=n.pos&&n.pos<=p);return c?{from:c[0],to:c[1],...l.attrs}:null}function ze(t){const e=t.selection;return e instanceof $.NodeSelection&&(e.node.type===f.nodes.image||e.node.type===f.nodes.figure)?{pos:e.from,attrs:e.node.attrs,figure:e.node.type===f.nodes.figure,node:e.node}:null}function ft(t,e,n){const r=f.nodes.figure.create(n),i=t.doc.resolve(e),a=i.parent;a.type===f.nodes.paragraph&&a.childCount===1?t.replaceWith(i.before(),i.after(),r):t.replaceRangeWith(e,e+1,r);let l=-1;return t.doc.descendants((d,o)=>l>=0?!1:(d.type===f.nodes.figure&&d.attrs.src===n.src&&d.content.size===0&&(l=o),!0)),l>=0&&t.setSelection($.TextSelection.create(t.doc,l+1)),t}function on(t,e,n,r){const i=f.nodes.image.create(r),a=[f.nodes.paragraph.create(null,i)];return n.content.size&&a.push(f.nodes.paragraph.create(null,n.content)),t.replaceWith(e,e+n.nodeSize,J.Fragment.from(a)),t.setSelection($.NodeSelection.create(t.doc,e+1))}function an(t,e,n=!0){const r=f.nodes,i=a=>r.table_row.create(null,Array.from({length:e},()=>a.createAndFill()));return r.table.create(null,Array.from({length:t},(a,l)=>i(n&&l===0?r.table_header:r.table_cell)))}function sn(t,e){return(n,r)=>{if(N.isInTable(n))return!1;if(!r)return!0;const i=an(t,e),a=n.tr,l=n.selection.$from;l.parent.type===f.nodes.paragraph&&l.parent.content.size===0&&l.depth===1?a.replaceWith(l.before(),l.after(),i):a.replaceSelectionWith(i);let o=-1;if(a.doc.descendants((s,c)=>o>=0?!1:(s===i&&(o=c),o<0&&s.type!==f.nodes.table)),o>=0){const s=o+a.doc.nodeAt(o).nodeSize;s>=a.doc.content.size&&a.insert(s,f.nodes.paragraph.create()),a.setSelection($.TextSelection.create(a.doc,o+4))}return r(a.scrollIntoView()),!0}}const ln=(t,e,n)=>N.isInTable(t)?N.goToNextCell(1)(t,e)||!e||!n?!0:(N.addRowAfter(t,e),N.goToNextCell(1)(n.state,e)):!1,cn=(t,e)=>N.isInTable(t)&&N.goToNextCell(-1)(t,e);function He(t,e){const n=f.marks[e],{from:r,to:i,empty:a,$from:l}=t.selection;if(a)return n.isInSet(t.storedMarks||l.marks())?.attrs.color??null;let d;return t.doc.nodesBetween(r,i,o=>{if(!o.isText||d===null)return;const s=n.isInSet(o.marks)?.attrs.color??null;d=d===void 0||d===s?s:null}),d??null}function dn(t,e){return(n,r)=>{const i=f.marks[t],{from:a,to:l,empty:d}=n.selection;if(!r)return!0;const o=n.tr;return d?(o.removeStoredMark(i),e&&o.addStoredMark(i.create({color:e}))):(o.removeMark(a,l,i),e&&o.addMark(a,l,i.create({color:e}))),r(o.scrollIntoView()),!0}}function un(){const t=f.nodes;return X.inputRules({rules:[X.textblockTypeInputRule(/^(#{1,4})\s$/,t.heading,e=>({level:e[1].length})),X.wrappingInputRule(/^\s*>\s$/,t.blockquote),X.wrappingInputRule(/^\s*([-+*])\s$/,t.bullet_list),X.wrappingInputRule(/^(\d+)\.\s$/,t.ordered_list,e=>({order:+e[1]}),(e,n)=>n.childCount+n.attrs.order===+e[1]),X.textblockTypeInputRule(/^```$/,t.code_block),new X.InputRule(/^(?:---|\*\*\*|___)$/,(e,n,r,i)=>{const a=e.doc.resolve(r);if(a.parent.type!==t.paragraph)return null;const l=a.before();return e.tr.replaceWith(l,i+1,[t.horizontal_rule.create(),t.paragraph.create()])})]})}function hn(t){const e=U.chainCommands(U.exitCode,(n,r)=>(r&&r(n.tr.replaceSelectionWith(f.nodes.hard_break.create()).scrollIntoView()),!0));return Te.keymap({"Mod-z":Y.undo,"Mod-y":Y.redo,"Shift-Mod-z":Y.redo,Backspace:X.undoInputRule,"Mod-b":_("strong"),"Mod-i":_("em"),"Mod-u":_("underline"),"Mod-Shift-x":_("strike"),"Mod-e":_("code"),"Mod-k":t.link,"Shift-Enter":e,"Mod-Enter":e,Enter:ae.splitListItem(f.nodes.list_item),Tab:Oe,"Shift-Tab":$e})}const fn=()=>Te.keymap(U.baseKeymap);function pn(t){return new $.Plugin({props:{decorations(e){const n=e.doc,r=n.firstChild;return!t||n.childCount!==1||!r||!r.isTextblock||r.content.size>0?null:pe.DecorationSet.create(n,[pe.Decoration.node(0,r.nodeSize,{class:"wds-placeholder","data-placeholder":t})])}}})}const ne=new $.PluginKey("wds-upload");function mn(){return new $.Plugin({key:ne,state:{init:()=>pe.DecorationSet.empty,apply(t,e){e=e.map(t.mapping,t.doc);const n=t.getMeta(ne);if(n&&"add"in n){const r=document.createElement("span");r.className="wds-upload-placeholder",r.setAttribute("aria-hidden","true"),e=e.add(t.doc,[pe.Decoration.widget(n.add.pos,r,{id:n.add.id})])}else n&&"remove"in n&&(e=e.remove(e.find(void 0,void 0,r=>r.id===n.remove.id)));return e}},props:{decorations:t=>ne.getState(t)}})}function gn(t,e){const n=ne.getState(t)?.find(void 0,void 0,r=>r.id===e);return n&&n.length?n[0].from:null}const A=t=>`<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false">${t}</svg>`,L={undo:A('<path d="M9 14 4 9l5-5"/><path d="M4 9h11a5 5 0 0 1 0 10h-3"/>'),redo:A('<path d="m15 14 5-5-5-5"/><path d="M20 9H9a5 5 0 0 0 0 10h3"/>'),bold:A('<path d="M7 5h6a3.5 3.5 0 0 1 0 7H7z"/><path d="M7 12h7a3.5 3.5 0 0 1 0 7H7z"/>'),italic:A('<path d="M14 5h-4"/><path d="M14 19h-4"/><path d="m14 5-4 14"/><path d="M18 5h-4M10 19H6"/>'),underline:A('<path d="M7 4v7a5 5 0 0 0 10 0V4"/><path d="M5 20h14"/>'),strike:A('<path d="M4 12h16"/><path d="M16.5 7.5C16 5.6 14.2 4.5 12 4.5c-2.6 0-4.5 1.4-4.5 3.4 0 1.3.8 2.3 2.4 3"/><path d="M8 16.5c.6 1.9 2.2 3 4.3 3 2.7 0 4.6-1.4 4.6-3.6 0-.9-.3-1.6-.9-2.2"/>'),code:A('<path d="m9 8-4 4 4 4"/><path d="m15 8 4 4-4 4"/>'),link:A('<path d="M10 14a4.5 4.5 0 0 0 6.4 0l3-3a4.5 4.5 0 0 0-6.4-6.4l-1 1"/><path d="M14 10a4.5 4.5 0 0 0-6.4 0l-3 3a4.5 4.5 0 0 0 6.4 6.4l1-1"/>'),blockquote:A('<path d="M5 18c2.5-1 4-3.2 4-6.5V7H5v5h3"/><path d="M14 18c2.5-1 4-3.2 4-6.5V7h-4v5h3"/>'),bulletList:A('<circle cx="5" cy="7" r="1" fill="currentColor"/><circle cx="5" cy="12" r="1" fill="currentColor"/><circle cx="5" cy="17" r="1" fill="currentColor"/><path d="M9 7h11M9 12h11M9 17h11"/>'),orderedList:A('<path d="M10 7h10M10 12h10M10 17h10"/><path d="M4 5.5 5.5 5v4"/><path d="M4 14.2c.3-.6.8-.9 1.4-.9.7 0 1.1.4 1.1 1 0 .9-1.4 1.6-2.5 2.7h2.6"/>'),indent:A('<path d="M4 6h16M10 10h10M10 14h10M4 18h16"/><path d="m4 9.5 3 2.5-3 2.5"/>'),outdent:A('<path d="M4 6h16M10 10h10M10 14h10M4 18h16"/><path d="m7 9.5-3 2.5 3 2.5"/>'),alignLeft:A('<path d="M4 6h16M4 10h10M4 14h16M4 18h10"/>'),alignCenter:A('<path d="M4 6h16M7 10h10M4 14h16M7 18h10"/>'),alignRight:A('<path d="M4 6h16M10 10h10M4 14h16M10 18h10"/>'),alignJustify:A('<path d="M4 6h16M4 10h16M4 14h16M4 18h16"/>'),hr:A('<path d="M3 12h18"/><path d="M8 7h8M8 17h8" opacity=".45"/>'),clear:A('<path d="M6 5h12"/><path d="M12 5 9 19"/><path d="m15 14 5 5M20 14l-5 5"/>'),source:A('<path d="m8 7-5 5 5 5"/><path d="m16 7 5 5-5 5"/><path d="m14 4-4 16"/>'),fullscreen:A('<path d="M4 9V4h5M20 9V4h-5M4 15v5h5M20 15v5h-5"/>'),close:A('<path d="M6 6l12 12M18 6 6 18"/>'),image:A('<rect x="3" y="4" width="18" height="16" rx="2"/><circle cx="8.5" cy="9.5" r="1.5"/><path d="m21 16-5-5-9 9"/>'),file:A('<path d="M14 3H7a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8z"/><path d="M14 3v5h5"/><path d="M9 13h6M9 17h4"/>'),folder:A('<path d="M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/>'),upload:A('<path d="M12 16V4"/><path d="m7 9 5-5 5 5"/><path d="M4 16v3a1 1 0 0 0 1 1h14a1 1 0 0 0 1-1v-3"/>'),grid:A('<rect x="4" y="4" width="6" height="6" rx="1"/><rect x="14" y="4" width="6" height="6" rx="1"/><rect x="4" y="14" width="6" height="6" rx="1"/><rect x="14" y="14" width="6" height="6" rx="1"/>'),list:A('<path d="M9 6h11M9 12h11M9 18h11"/><path d="M4 6h1M4 12h1M4 18h1"/>'),trash:A('<path d="M4 7h16"/><path d="M10 11v6M14 11v6"/><path d="M6 7l1 12a2 2 0 0 0 2 2h6a2 2 0 0 0 2-2l1-12"/><path d="M9 7V4h6v3"/>'),table:A('<rect x="3" y="4" width="18" height="16" rx="2"/><path d="M3 10h18M3 15h18M9 4v16M15 4v16"/>'),pasteText:A('<path d="M9 4h6v3H9z"/><path d="M15 5h2a2 2 0 0 1 2 2v12a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V7a2 2 0 0 1 2-2h2"/><path d="M9 12h6M12 12v6"/>'),textColor:A('<path d="m6 16 6-12 6 12"/><path d="M8.5 11h7"/><rect class="wds-swatch-bar" x="3" y="19" width="18" height="3" rx="1" stroke="none"/>'),highlight:A('<path d="m14 4 5 5-7 7H7v-5z"/><path d="M7 16l-2 2"/><rect class="wds-swatch-bar" x="3" y="19" width="18" height="3" rx="1" stroke="none"/>'),globe:A('<circle cx="12" cy="12" r="9"/><path d="M3 12h18"/><path d="M12 3a14 14 0 0 1 0 18 14 14 0 0 1 0-18"/>')},R=t=>e=>e.exec(t),pt={undo:{type:"button",label:"undo",icon:L.undo,shortcut:"Mod+Z",run:t=>t.undo(),enabled:t=>Y.undoDepth(t)>0},redo:{type:"button",label:"redo",icon:L.redo,shortcut:"Mod+Y",run:t=>t.redo(),enabled:t=>Y.redoDepth(t)>0},blocks:{type:"blocks"},bold:{type:"button",label:"bold",icon:L.bold,shortcut:"Mod+B",run:R(_("strong")),active:t=>me(t,f.marks.strong)},italic:{type:"button",label:"italic",icon:L.italic,shortcut:"Mod+I",run:R(_("em")),active:t=>me(t,f.marks.em)},underline:{type:"button",label:"underline",icon:L.underline,shortcut:"Mod+U",run:R(_("underline")),active:t=>me(t,f.marks.underline)},strike:{type:"button",label:"strike",icon:L.strike,run:R(_("strike")),active:t=>me(t,f.marks.strike)},textColor:{type:"button",label:"textColor",icon:L.textColor,popup:!0,run:(t,e)=>t.openColorPicker("textColor",e),swatch:t=>He(t,"textColor")},highlight:{type:"button",label:"highlight",icon:L.highlight,popup:!0,run:(t,e)=>t.openColorPicker("highlight",e),swatch:t=>He(t,"highlight")},code:{type:"button",label:"code",icon:L.code,run:R(_("code")),active:t=>me(t,f.marks.code)},link:{type:"button",label:"link",icon:L.link,shortcut:"Mod+K",run:t=>t.openLinkDialog(),active:t=>!!Re(t)},image:{type:"button",label:"image",icon:L.image,run:t=>t.openImageDialog(),active:t=>!!ze(t)},file:{type:"button",label:"file",icon:L.file,run:t=>t.openFileManager("file"),available:t=>t.hasFileManager()},table:{type:"button",label:"table",icon:L.table,popup:!0,run:(t,e)=>t.openTableMenu(e),active:t=>N.isInTable(t)},blockquote:{type:"button",label:"blockquote",icon:L.blockquote,run:R(tn()),active:t=>dt(t,f.nodes.blockquote)},bulletList:{type:"button",label:"bulletList",icon:L.bulletList,run:R(ht(f.nodes.bullet_list)),active:t=>ut(t)===f.nodes.bullet_list},orderedList:{type:"button",label:"orderedList",icon:L.orderedList,run:R(ht(f.nodes.ordered_list)),active:t=>ut(t)===f.nodes.ordered_list},outdent:{type:"button",label:"outdent",icon:L.outdent,run:R($e),enabled:t=>$e(t)},indent:{type:"button",label:"indent",icon:L.indent,run:R(Oe),enabled:t=>Oe(t)},alignLeft:{type:"button",label:"alignLeft",icon:L.alignLeft,run:R(Q("left")),active:t=>xe(t)==="left",enabled:t=>Q("left")(t)},alignCenter:{type:"button",label:"alignCenter",icon:L.alignCenter,run:R(Q("center")),active:t=>xe(t)==="center",enabled:t=>Q("center")(t)},alignRight:{type:"button",label:"alignRight",icon:L.alignRight,run:R(Q("right")),active:t=>xe(t)==="right",enabled:t=>Q("right")(t)},alignJustify:{type:"button",label:"alignJustify",icon:L.alignJustify,run:R(Q("justify")),active:t=>xe(t)==="justify",enabled:t=>Q("justify")(t)},hr:{type:"button",label:"hr",icon:L.hr,run:R(nn)},clear:{type:"button",label:"clear",icon:L.clear,run:R(rn)},pasteText:{type:"button",label:"pasteText",icon:L.pasteText,run:t=>t.togglePlainPaste(),active:(t,e)=>e.isPlainPaste()},source:{type:"button",label:"source",icon:L.source,run:t=>t.toggleSource(),active:(t,e)=>e.isSourceMode(),inSource:!0},fullscreen:{type:"button",label:"fullscreen",icon:L.fullscreen,run:t=>t.toggleFullscreen(),active:(t,e)=>e.isFullscreen(),inSource:!0}},mt=["undo","redo","|","blocks","|","bold","italic","underline","strike","code","textColor","highlight","|","link","image","file","table","blockquote","bulletList","orderedList","outdent","indent","|","alignLeft","alignCenter","alignRight","alignJustify","|","hr","clear","pasteText","|","source","fullscreen"],bn=[["paragraph","paragraph"],["heading1","heading1"],["heading2","heading2"],["heading3","heading3"],["heading4","heading4"],["codeBlock","codeBlock"]],wn=typeof navigator<"u"&&/Mac|iP(hone|ad|od)/.test(navigator.platform||navigator.userAgent),yn=t=>t.replace("Mod",wn?"⌘":"Ctrl");function vn(t,e,n){const r=document.createElement("div");r.className="wds-toolbar",r.setAttribute("role","toolbar"),r.setAttribute("aria-label",n.toolbarLabel);const i=[];let a=document.createElement("div");a.className="wds-group",r.append(a);for(const d of e){if(d==="|"){a.childElementCount&&(a=document.createElement("div"),a.className="wds-group",r.append(a));continue}const o=pt[d];if(!o){console.warn(`[WDS Editor] Unknown toolbar item "${d}".`);continue}if(o.type==="blocks"){const u=document.createElement("select");u.className="wds-select",u.setAttribute("aria-label",n.blockType),u.title=n.blockType;for(const[g,v]of bn){const I=document.createElement("option");I.value=g,I.textContent=n[v],u.append(I)}const p=document.createElement("option");p.value="",p.textContent="—",p.hidden=!0,u.append(p),u.addEventListener("change",()=>{u.value&&t.exec(en(u.value)),t.focus()}),a.append(u),i.push(g=>{u.value=Zt(g)??"",u.disabled=t.isSourceMode()||t.isReadOnly()});continue}if(o.available&&!o.available(t))continue;const s=document.createElement("button");s.type="button",s.className="wds-button-tool",s.innerHTML=o.icon;const c=n[o.label];s.setAttribute("aria-label",c),s.title=o.shortcut?`${c} (${yn(o.shortcut)})`:c,s.dataset.item=d,o.popup&&(s.setAttribute("aria-haspopup","true"),s.setAttribute("aria-expanded","false")),s.addEventListener("mousedown",u=>u.preventDefault()),s.addEventListener("click",()=>{s.disabled||o.run(t,s)}),a.append(s),i.push(u=>{const p=t.isSourceMode()&&!o.inSource||t.isReadOnly()&&!o.inSource;if(s.disabled=p||(o.enabled?!o.enabled(u,t):!1),o.swatch){const g=p?null:o.swatch(u);g?s.style.setProperty("--wds-swatch",g):s.style.removeProperty("--wds-swatch")}if(o.active){const g=!p&&o.active(u,t);s.classList.toggle("is-active",g),s.setAttribute("aria-pressed",String(g))}})}return r.addEventListener("keydown",d=>{if(d.key!=="ArrowRight"&&d.key!=="ArrowLeft"&&d.key!=="Home"&&d.key!=="End"||d.target.tagName==="SELECT"&&(d.key==="Home"||d.key==="End"))return;const o=[...r.querySelectorAll("button:not([disabled]), select:not([disabled])")],s=o.indexOf(document.activeElement);if(s<0)return;d.preventDefault();const c=d.key==="Home"?0:d.key==="End"?o.length-1:(s+(d.key==="ArrowRight"?1:-1)+o.length)%o.length;o.forEach(u=>u.tabIndex=-1),o[c].tabIndex=0,o[c].focus()}),{element:r,update:d=>{i.forEach(s=>s(d));const o=[...r.querySelectorAll("button, select")];if(!o.some(s=>s.tabIndex===0&&!s.disabled)){o.forEach(c=>c.tabIndex=-1);const s=o.find(c=>!c.disabled);s&&(s.tabIndex=0)}}}}function gt(t,e,n,r){const i=document.createElement("span");i.className="wds-image";const a=document.createElement("img");a.draggable=!1;const l=document.createElement("span");l.className="wds-resize-handle",l.title=r.resizeLabel,l.setAttribute("aria-hidden","true"),i.append(a,l);const d=()=>{const c=e();c!==void 0&&t.dispatch(t.state.tr.setSelection($.NodeSelection.create(t.state.doc,c)))};let o=!1;return l.addEventListener("pointerdown",c=>{if(!t.editable)return;c.preventDefault(),c.stopPropagation(),d(),o=!0;try{l.setPointerCapture(c.pointerId)}catch{}const u=c.clientX,p=a.getBoundingClientRect().width,g=Math.max(40,t.dom.clientWidth-8);let v=p;const I=C=>{v=Math.round(Math.min(g,Math.max(40,p+C.clientX-u))),a.style.width=`${v}px`,a.style.height="auto",i.dataset.size=`${v}px`},D=()=>{o=!1,window.removeEventListener("pointermove",I),window.removeEventListener("pointerup",D),window.removeEventListener("pointercancel",D),delete i.dataset.size,a.style.width="",a.style.height="";const C=e();if(C===void 0||Math.abs(v-p)<2)return;const H=n(),y=t.state.tr.setNodeMarkup(C,void 0,{...H.attrs,width:v,height:null});t.dispatch(y.setSelection($.NodeSelection.create(y.doc,C)))};window.addEventListener("pointermove",I),window.addEventListener("pointerup",D),window.addEventListener("pointercancel",D)}),i.addEventListener("dblclick",c=>{if(!t.editable)return;c.preventDefault(),d();const u=e();u!==void 0&&r.onEdit(u)}),{box:i,img:a,handle:l,select:d,render:c=>{const u=Ie(c.attrs,!1);for(const p of["src","alt","title","width","height"])u[p]!==void 0?a.setAttribute(p,u[p]):a.removeAttribute(p)},isResizing:()=>o}}const bt=(t,e)=>{t.classList.remove("wds-align-left","wds-align-center","wds-align-right"),e&&t.classList.add(`wds-align-${e}`)};class kn{constructor(e,n,r,i){this.node=e,this.parts=gt(n,r,()=>this.node,i),this.dom=this.parts.box,this.render()}render(){this.parts.render(this.node),bt(this.dom,this.node.attrs.align)}update(e){return e.type!==this.node.type?!1:(this.node=e,this.render(),!0)}stopEvent(e){return e.target===this.parts.handle||this.parts.isResizing()}ignoreMutation(){return!0}}class Mn{constructor(e,n,r,i){this.node=e,this.dom=document.createElement("figure"),this.dom.className="wds-figure",this.parts=gt(n,r,()=>this.node,i),this.parts.box.contentEditable="false",this.parts.box.addEventListener("mousedown",a=>{a.target===this.parts.handle||a.detail>1||(a.preventDefault(),this.parts.select(),n.focus())}),this.contentDOM=document.createElement("figcaption"),this.contentDOM.dataset.placeholder=i.captionPlaceholder,this.dom.append(this.parts.box,this.contentDOM),this.render()}render(){this.parts.render(this.node),bt(this.dom,this.node.attrs.align),this.dom.classList.toggle("is-empty",this.node.content.size===0)}update(e){return e.type!==this.node.type?!1:(this.node=e,this.render(),!0)}stopEvent(e){return this.parts.box.contains(e.target)&&!e.type.startsWith("drag")}ignoreMutation(e){return!this.contentDOM.contains(e.target)}}let Ae=null;function wt(){Ae?.close()}function Pe(t,e,n,r){wt();const i=document.createElement("div");i.className=`wds-menu ${n}`,e.append(i);const a=()=>{const u=t.getBoundingClientRect();i.style.maxHeight="";const p=i.offsetWidth,g=i.offsetHeight;i.style.left=`${Math.max(4,Math.min(u.left,window.innerWidth-p-4))}px`;const v=window.innerHeight-u.bottom-8,I=u.top-8;g<=v||v>=I?(i.style.top=`${u.bottom+4}px`,g>v&&(i.style.maxHeight=`${v}px`)):(i.style.top=`${Math.max(4,u.top-Math.min(g,I)-4)}px`,g>I&&(i.style.maxHeight=`${I}px`))},l=u=>{if(u.target instanceof Node&&i.contains(u.target))return;const p=t.getBoundingClientRect();p.bottom<0||p.top>window.innerHeight||!t.isConnected?c():a()};t.setAttribute("aria-expanded","true");const d=u=>{!i.contains(u.target)&&u.target!==t&&!t.contains(u.target)&&c()},o=u=>{u.key==="Escape"&&(u.preventDefault(),u.stopPropagation(),c(!0))};let s=!1;function c(u=!1){s||(s=!0,i.remove(),t.setAttribute("aria-expanded","false"),document.removeEventListener("mousedown",d,!0),window.removeEventListener("scroll",l,!0),window.removeEventListener("resize",l),i.removeEventListener("keydown",o),Ae?.close===c&&(Ae=null),u&&t.focus())}return document.addEventListener("mousedown",d,!0),window.addEventListener("scroll",l,!0),window.addEventListener("resize",l),i.addEventListener("keydown",o),Ae={close:c},{popup:i,place:a,close:c}}function Ln(t,e,n,r){const{popup:i,place:a,close:l}=Pe(t,e,"wds-menu-list");i.setAttribute("role","menu"),i.setAttribute("aria-label",r);for(const o of n){if(o==="|"){const c=document.createElement("div");c.className="wds-menu-sep",c.setAttribute("role","separator"),i.append(c);continue}const s=document.createElement("button");s.type="button",s.className=`wds-menu-item${o.danger?" is-danger":""}`,s.setAttribute("role","menuitem"),s.tabIndex=-1,s.innerHTML=o.icon??"",s.append(document.createTextNode(o.label)),o.enabled===!1&&(s.disabled=!0),s.addEventListener("mousedown",c=>c.preventDefault()),s.addEventListener("click",()=>{l(),o.run()}),i.append(s)}const d=()=>[...i.querySelectorAll(".wds-menu-item:not(:disabled)")];i.addEventListener("keydown",o=>{const s=d(),c=s.indexOf(document.activeElement);let u=-1;o.key==="ArrowDown"?u=(c+1)%s.length:o.key==="ArrowUp"?u=(c-1+s.length)%s.length:o.key==="Home"?u=0:o.key==="End"?u=s.length-1:o.key==="Tab"&&l(),u>=0&&(o.preventDefault(),s[u]?.focus())}),a(),d()[0]?.focus()}function xn(t,e,n,r,i){const{popup:d,place:o,close:s}=Pe(t,e,"wds-table-picker");d.setAttribute("role","dialog"),d.setAttribute("aria-label",n);const c=document.createElement("div");c.className="wds-picker-grid",c.style.gridTemplateColumns="repeat(10, 1fr)",c.tabIndex=0,c.setAttribute("role","grid"),c.setAttribute("aria-label",n);const u=document.createElement("div");u.className="wds-picker-label",u.setAttribute("aria-live","polite");const p=[];let g=3,v=3;const I=()=>{p.forEach((D,C)=>D.classList.toggle("is-on",Math.floor(C/10)<g&&C%10<v)),u.textContent=r(g,v),c.setAttribute("aria-valuetext",u.textContent)};for(let D=0;D<8;D++)for(let C=0;C<10;C++){const H=document.createElement("span");H.className="wds-picker-cell",H.addEventListener("mouseenter",()=>{g=D+1,v=C+1,I()}),H.addEventListener("mousedown",y=>y.preventDefault()),H.addEventListener("click",()=>{s(),i(D+1,C+1)}),p.push(H),c.append(H)}c.addEventListener("keydown",D=>{const C={ArrowRight:[0,1],ArrowLeft:[0,-1],ArrowDown:[1,0],ArrowUp:[-1,0]};C[D.key]?(D.preventDefault(),g=Math.min(8,Math.max(1,g+C[D.key][0])),v=Math.min(10,Math.max(1,v+C[D.key][1])),I()):D.key==="Enter"||D.key===" "?(D.preventDefault(),s(),i(g,v)):D.key==="Tab"&&s()}),d.append(c,u),I(),o(),c.focus()}function An(t,e,n){const{popup:r,place:i,close:a}=Pe(t,e,"wds-color-picker");r.setAttribute("role","dialog"),r.setAttribute("aria-label",n.label);const l=s=>{a(),n.onPick(s)},d=document.createElement("button");d.type="button",d.className="wds-menu-item wds-color-remove",d.innerHTML='<span class="wds-swatch is-none" aria-hidden="true"></span>',d.append(document.createTextNode(n.removeLabel)),d.addEventListener("mousedown",s=>s.preventDefault()),d.addEventListener("click",()=>l(null));const o=document.createElement("div");o.className="wds-swatches",o.style.gridTemplateColumns=`repeat(${n.columns}, 1fr)`;for(const s of n.swatches){const c=document.createElement("button");c.type="button",c.className="wds-swatch",c.style.background=s.color,c.title=s.label,c.setAttribute("aria-label",s.label);const u=s.color===n.current;c.setAttribute("aria-pressed",String(u)),u&&c.classList.add("is-current"),c.addEventListener("mousedown",p=>p.preventDefault()),c.addEventListener("click",()=>l(s.color)),o.append(c)}r.append(d,o),r.addEventListener("keydown",s=>{const c=[d,...o.querySelectorAll(".wds-swatch")],u=c.indexOf(document.activeElement);if(u<0)return;const p=n.columns;let g=-1;s.key==="ArrowRight"?g=Math.min(c.length-1,u+1):s.key==="ArrowLeft"?g=Math.max(0,u-1):s.key==="ArrowDown"?g=u===0?1:Math.min(c.length-1,u+p):s.key==="ArrowUp"?g=u<=p?0:u-p:s.key==="Tab"&&a(),g>=0&&(s.preventDefault(),c[g].focus())}),i(),(o.querySelector(".is-current")??o.querySelector(".wds-swatch"))?.focus()}const ge={undo:"Undo",redo:"Redo",blockType:"Text style",paragraph:"Paragraph",heading1:"Heading 1",heading2:"Heading 2",heading3:"Heading 3",heading4:"Heading 4",codeBlock:"Code block",bold:"Bold",italic:"Italic",underline:"Underline",strike:"Strikethrough",code:"Inline code",link:"Insert link",blockquote:"Quote",bulletList:"Bulleted list",orderedList:"Numbered list",indent:"Increase indent",outdent:"Decrease indent",alignLeft:"Align left",alignCenter:"Align center",alignRight:"Align right",alignJustify:"Justify",hr:"Horizontal line",clear:"Clear formatting",source:"Source code",fullscreen:"Fullscreen",linkUrl:"URL",linkText:"Text to display",linkTitle:"Title",linkNewTab:"Open in a new tab",linkInvalid:"Enter a valid web address, email address or relative URL.",save:"Save",cancel:"Cancel",remove:"Remove link",close:"Close",words:"words",characters:"characters",poweredBy:"Powered by",editorLabel:"Rich text editor",toolbarLabel:"Editor toolbar",sourceLabel:"HTML source",image:"Insert image",file:"Insert file",imageEdit:"Image",imageUrl:"Image URL",imageAlt:"Alternative text",imageAltHint:"Describe the image for screen readers and search engines.",imageWidth:"Width (px)",imageAlign:"Alignment",alignNone:"None",alignLeftShort:"Left",alignCenterShort:"Center",alignRightShort:"Right",imageInvalid:"Enter a valid image address (https:// or a relative URL).",insert:"Insert",fmTitle:"File manager",fmRoot:"Files",fmBreadcrumb:"Folders",fmSearch:"Search files",fmSort:"Sort",fmSortNewest:"Newest first",fmSortName:"Name",fmSortLargest:"Largest first",fmGrid:"Grid view",fmList:"List view",fmUpload:"Upload",fmDrop:"Drop files to upload",fmLoading:"Loading…",fmEmpty:"No files here yet.",fmNoResults:"No files match your search.",fmLoadMore:"Load more",fmRetry:"Try again",fmDelete:"Delete",fmDeleteConfirm:'Delete "{name}"? This cannot be undone.',fmFromUrl:"Insert from URL",fmLinkText:"Link text",fmFolder:"Folder",fmNoSelection:"Select a file to see its details.",fmNotAllowed:"{name}: this file type is not allowed here.",fmUploadFailed:"{name}: upload failed. {error}",fmListFailed:"The file list could not be loaded. {error}",fmDeleteFailed:"The file could not be deleted. {error}",fmUploading:"Uploading {name}",table:"Table",tableInsert:"Insert table",tableSize:"{rows} × {cols} table",rowAbove:"Insert row above",rowBelow:"Insert row below",colLeft:"Insert column left",colRight:"Insert column right",deleteRow:"Delete row",deleteCol:"Delete column",headerRow:"Toggle header row",headerCol:"Toggle header column",mergeCells:"Merge cells",splitCell:"Split cell",deleteTable:"Delete table",caption:"Show caption",captionPlaceholder:"Write a caption…",resizeImage:"Drag to resize",pasteText:"Paste as plain text",textColor:"Text color",highlight:"Highlight",removeColor:"Default color",removeHighlight:"No highlight",colorRed:"Red",colorOrange:"Orange",colorAmber:"Amber",colorYellow:"Yellow",colorGreen:"Green",colorTeal:"Teal",colorBlue:"Blue",colorPurple:"Purple",colorPink:"Pink",colorSlate:"Slate",colorGray:"Gray"},yt={undo:"Geri al",redo:"Yinele",blockType:"Metin stili",paragraph:"Paragraf",heading1:"Başlık 1",heading2:"Başlık 2",heading3:"Başlık 3",heading4:"Başlık 4",codeBlock:"Kod bloğu",bold:"Kalın",italic:"İtalik",underline:"Altı çizili",strike:"Üstü çizili",code:"Satır içi kod",link:"Bağlantı ekle",blockquote:"Alıntı",bulletList:"Madde işaretli liste",orderedList:"Numaralı liste",indent:"Girintiyi artır",outdent:"Girintiyi azalt",alignLeft:"Sola hizala",alignCenter:"Ortala",alignRight:"Sağa hizala",alignJustify:"İki yana yasla",hr:"Yatay çizgi",clear:"Biçimi temizle",source:"Kaynak kodu",fullscreen:"Tam ekran",linkUrl:"Adres (URL)",linkText:"Görünen metin",linkTitle:"Başlık",linkNewTab:"Yeni sekmede aç",linkInvalid:"Geçerli bir web adresi, e-posta adresi ya da göreli adres girin.",save:"Kaydet",cancel:"Vazgeç",remove:"Bağlantıyı kaldır",close:"Kapat",words:"kelime",characters:"karakter",poweredBy:"Destekleyen:",editorLabel:"Zengin metin editörü",toolbarLabel:"Editör araç çubuğu",sourceLabel:"HTML kaynağı",image:"Görsel ekle",file:"Dosya ekle",imageEdit:"Görsel",imageUrl:"Görsel adresi",imageAlt:"Alternatif metin",imageAltHint:"Ekran okuyucular ve arama motorları için görseli kısaca anlatın.",imageWidth:"Genişlik (px)",imageAlign:"Hizalama",alignNone:"Yok",alignLeftShort:"Sol",alignCenterShort:"Orta",alignRightShort:"Sağ",imageInvalid:"Geçerli bir görsel adresi girin (https:// ya da göreli adres).",insert:"Ekle",fmTitle:"Dosya yöneticisi",fmRoot:"Dosyalar",fmBreadcrumb:"Klasörler",fmSearch:"Dosyalarda ara",fmSort:"Sırala",fmSortNewest:"En yeni",fmSortName:"Ada göre",fmSortLargest:"En büyük",fmGrid:"Izgara görünümü",fmList:"Liste görünümü",fmUpload:"Yükle",fmDrop:"Yüklemek için dosyaları bırakın",fmLoading:"Yükleniyor…",fmEmpty:"Burada henüz dosya yok.",fmNoResults:"Aramanızla eşleşen dosya yok.",fmLoadMore:"Daha fazla yükle",fmRetry:"Tekrar dene",fmDelete:"Sil",fmDeleteConfirm:'"{name}" silinsin mi? Bu işlem geri alınamaz.',fmFromUrl:"Adresten ekle",fmLinkText:"Bağlantı metni",fmFolder:"Klasör",fmNoSelection:"Ayrıntıları görmek için bir dosya seçin.",fmNotAllowed:"{name}: bu dosya türüne burada izin verilmiyor.",fmUploadFailed:"{name}: yüklenemedi. {error}",fmListFailed:"Dosya listesi yüklenemedi. {error}",fmDeleteFailed:"Dosya silinemedi. {error}",fmUploading:"{name} yükleniyor",table:"Tablo",tableInsert:"Tablo ekle",tableSize:"{rows} × {cols} tablo",rowAbove:"Üste satır ekle",rowBelow:"Alta satır ekle",colLeft:"Sola sütun ekle",colRight:"Sağa sütun ekle",deleteRow:"Satırı sil",deleteCol:"Sütunu sil",headerRow:"Başlık satırı aç/kapat",headerCol:"Başlık sütunu aç/kapat",mergeCells:"Hücreleri birleştir",splitCell:"Hücreyi böl",deleteTable:"Tabloyu sil",caption:"Açıklama göster",captionPlaceholder:"Açıklama yazın…",resizeImage:"Boyutlandırmak için sürükleyin",pasteText:"Düz metin olarak yapıştır",textColor:"Yazı rengi",highlight:"Vurgu",removeColor:"Varsayılan renk",removeHighlight:"Vurgu yok",colorRed:"Kırmızı",colorOrange:"Turuncu",colorAmber:"Kehribar",colorYellow:"Sarı",colorGreen:"Yeşil",colorTeal:"Camgöbeği",colorBlue:"Mavi",colorPurple:"Mor",colorPink:"Pembe",colorSlate:"Arduvaz",colorGray:"Gri"},Ee={en:ge,tr:yt};function vt(t,e){Ee[t.toLowerCase()]={...ge,...Ee[t.toLowerCase()],...e}}function En(t){if(t&&typeof t=="object")return{...ge,...t};const e=(t||(typeof navigator<"u"?navigator.language:"en")||"en").toLowerCase();return Ee[e]??Ee[e.split("-")[0]]??ge}function Z(t,e){return t.replace(/\{(\w+)\}/g,(n,r)=>e[r]??n)}let Sn=0;function kt(t,e){const n=`wds-dlg-${++Sn}`,r=document.createElement("dialog");r.className="wds-dialog",r.setAttribute("aria-labelledby",`${n}-title`);const i=document.createElement("form");i.method="dialog",i.noValidate=!0;const a=document.createElement("div");a.className="wds-dialog-header";const l=document.createElement("h2");l.id=`${n}-title`,l.textContent=e.title;const d=document.createElement("button");d.type="button",d.className="wds-icon-button",d.setAttribute("aria-label",e.closeLabel),d.innerHTML=L.close,a.append(l,d);const o=document.createElement("div");o.className="wds-dialog-body";const s=new Map;for(const y of e.fields){if(y.type==="select"){const S=document.createElement("select");S.id=`${n}-${y.name}`,S.name=y.name,S.className="wds-input";for(const P of y.options??[]){const te=document.createElement("option");te.value=P.value,te.textContent=P.label,S.append(te)}S.value=typeof y.value=="string"?y.value:"";const z=document.createElement("label");z.className="wds-label",z.htmlFor=S.id,z.textContent=y.label,o.append(z,S),s.set(y.name,S);continue}const x=document.createElement("input");if(x.id=`${n}-${y.name}`,x.name=y.name,y.type==="checkbox"){x.type="checkbox",x.checked=!!y.value;const S=document.createElement("label");S.className="wds-check",S.htmlFor=x.id,S.append(x,document.createTextNode(y.label)),o.append(S)}else{x.type="text",y.type==="url"&&(x.inputMode="url"),y.type==="number"&&(x.inputMode="numeric"),x.className="wds-input",x.value=typeof y.value=="string"?y.value:"",x.autocomplete="off",x.spellcheck=!1,y.placeholder&&(x.placeholder=y.placeholder);const S=document.createElement("label");if(S.className="wds-label",S.htmlFor=x.id,S.textContent=y.label,o.append(S,x),y.hint){const z=document.createElement("p");z.className="wds-hint",z.id=`${x.id}-hint`,z.textContent=y.hint,x.setAttribute("aria-describedby",z.id),o.append(z)}}s.set(y.name,x)}const c=document.createElement("p");c.className="wds-dialog-error",c.setAttribute("role","alert"),c.hidden=!0,o.append(c);const u=document.createElement("div");if(u.className="wds-dialog-footer",e.extraAction){const y=document.createElement("button");y.type="button",y.className="wds-button wds-button-danger",y.textContent=e.extraAction.label,y.addEventListener("click",()=>{e.extraAction.onClick(),C()}),u.append(y)}const p=document.createElement("span");p.className="wds-spacer";const g=document.createElement("button");g.type="button",g.className="wds-button",g.textContent=e.cancelLabel;const v=document.createElement("button");v.type="submit",v.className="wds-button wds-button-primary",v.textContent=e.submitLabel,u.append(p,g,v),i.append(a,o,u),r.append(i),t.append(r);const I=()=>{const y={};return s.forEach((x,S)=>y[S]=x instanceof HTMLInputElement&&x.type==="checkbox"?x.checked:x.value),y};let D=!1;function C(){D||(D=!0,r.open&&r.close(),r.remove(),e.onClose?.())}i.addEventListener("submit",y=>{y.preventDefault();const x=I(),S=e.validate?.(x)??null;if(S){c.textContent=S,c.hidden=!1,[...s.values()][0]?.focus();return}e.onSubmit(x),C()}),g.addEventListener("click",C),d.addEventListener("click",C),r.addEventListener("close",C),r.addEventListener("click",y=>{y.target===r&&C()}),r.showModal();const H=[...s.values()].find(y=>y instanceof HTMLInputElement&&y.type!=="checkbox");return H?.focus(),H?.select(),C}const ee=t=>typeof t=="string"&&t.trim()?t:void 0,Be=t=>typeof t=="number"&&Number.isFinite(t)&&t>=0?t:void 0;function Mt(t){if(!t||typeof t!="object")return null;const e=t,n=V(ee(e.url)),r=ee(e.name);if(!n||!r)return null;const i={url:n,name:r},a=Be(e.size),l=Be(e.width),d=Be(e.height);a!==void 0&&(i.size=a),l!==void 0&&(i.width=l),d!==void 0&&(i.height=d),ee(e.type)&&(i.type=e.type.toLowerCase());const o=V(ee(e.thumb));return o&&(i.thumb=o),ee(e.modified)&&!Number.isNaN(Date.parse(e.modified))&&(i.modified=e.modified),i}function Lt(t,e="/"){const n=Array.isArray(t)?{files:t}:t&&typeof t=="object"?t:{},r=(Array.isArray(n.files)?n.files:[]).map(Mt).filter(a=>!!a),i=(Array.isArray(n.folders)?n.folders:[]).map(a=>a&&typeof a=="object"?a:{}).filter(a=>ee(a.name)&&ee(a.path)).map(a=>({name:a.name,path:Fe(a.path)}));return{path:Fe(ee(n.path)??e),folders:i,files:r,hasMore:n.hasMore===!0,serverSearch:typeof n.q=="string"}}function Fe(t){return"/"+t.split("/").filter(n=>n&&n!=="."&&n!=="..").join("/")}const Cn=/\.(jpe?g|png|gif|webp|avif|svg|bmp|ico)$/i,Tn={jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",gif:"image/gif",webp:"image/webp",avif:"image/avif",svg:"image/svg+xml",bmp:"image/bmp",ico:"image/x-icon",pdf:"application/pdf",zip:"application/zip",txt:"text/plain",csv:"text/csv",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",xls:"application/vnd.ms-excel",xlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",mp4:"video/mp4",mp3:"audio/mpeg"},xt=t=>(/\.([a-z0-9]+)$/i.exec(t)?.[1]??"").toLowerCase();function At(t){return t.type||Tn[xt(t.name)]||""}function le(t){const e=At(t);return e?e.startsWith("image/"):Cn.test(t.url??t.name)}function Ue(t,e){if(!e||!e.trim())return!0;const n=At(t),r="."+xt(t.name);return e.split(",").some(i=>{const a=i.trim().toLowerCase();return a?a.startsWith(".")?r===a:a.endsWith("/*")?n.startsWith(a.slice(0,-1)):n===a:!1})}function Et(t){if(t===void 0)return"";if(t<1024)return`${t} B`;const e=["KB","MB","GB"];let n=t/1024,r=0;for(;n>=1024&&r<e.length-1;)n/=1024,r++;return`${n<10?n.toFixed(1):Math.round(n)} ${e[r]}`}class q extends Error{}async function St(t){try{const e=await t.clone().json();if(e&&typeof e.error=="string")return e.error}catch{}return`HTTP ${t.status}`}function Dn(t,e){const n=new URL(t,document.baseURI);for(const[r,i]of Object.entries(e))i&&n.searchParams.set(r,i);return n.href}class Nn{constructor(e){this.options=e}get canUpload(){return!!this.options.uploadUrl}get canDelete(){return!!this.options.deleteUrl}init(e={}){return{...e,credentials:this.options.withCredentials?"include":"same-origin",headers:{Accept:"application/json",...this.options.headers,...e.headers}}}async list(e,n,r,i){const a=Dn(this.options.listUrl,{path:e,q:n,page:r>1?String(r):""});let l;try{l=await fetch(a,{...this.init(),signal:i})}catch(o){throw o.name==="AbortError"?o:new q(o.message||"Network error")}if(!l.ok)throw new q(await St(l));let d;try{d=await l.json()}catch{throw new q("Invalid JSON")}return Lt(d,e)}upload(e,n,r){const{uploadUrl:i,headers:a={},withCredentials:l}=this.options;return i?new Promise((d,o)=>{const s=new XMLHttpRequest;s.open("POST",new URL(i,document.baseURI).href),s.withCredentials=!!l,s.setRequestHeader("Accept","application/json");for(const[u,p]of Object.entries(a))s.setRequestHeader(u,p);s.upload.onprogress=u=>u.lengthComputable&&r?.(u.loaded/u.total),s.onerror=()=>o(new q("Network error")),s.onload=()=>{let u=null;try{u=JSON.parse(s.responseText)}catch{}if(s.status<200||s.status>=300){o(new q(typeof u?.error=="string"?u.error:`HTTP ${s.status}`));return}const p=Mt(u?.file);p?d(p):o(new q("Invalid upload response"))};const c=new FormData;c.append("file",e,e.name),c.append("path",n),s.send(c)}):Promise.reject(new q("Upload is not configured"))}async remove(e){const{deleteUrl:n}=this.options;if(!n)throw new q("Delete is not configured");let r;try{r=await fetch(new URL(n,document.baseURI).href,this.init({method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({url:e})}))}catch(i){throw new q(i.message||"Network error")}if(!r.ok)throw new q(await St(r))}}const b=(t,e,n)=>{const r=document.createElement(t);return e&&(r.className=e),n!==void 0&&(r.textContent=n),r},_e=(t,e,n="wds-icon-button")=>{const r=b("button",n);return r.type="button",r.innerHTML=t,r.setAttribute("aria-label",e),r.title=e,r},In=[["","alignNone"],["left","alignLeftShort"],["center","alignCenterShort"],["right","alignRightShort"]];class On{constructor(e,n,r){this.host=e,this.api=n,this.t=r,this.path="/",this.view="grid",this.sort="newest"}open(e){const n=this.t,r=e.accept??"";let i=[],a=[],l=1,d=!1,o=!1,s="",c=null,u=null,p=0,g=!1;const v=b("dialog","wds-dialog wds-fm");v.setAttribute("aria-labelledby","wds-fm-title");const I=b("div","wds-dialog-header"),D=b("h2",void 0,n.fmTitle);D.id="wds-fm-title";const C=_e(L.close,n.close);I.append(D,C);const H=b("div","wds-fm-bar"),y=b("nav","wds-fm-crumbs");y.setAttribute("aria-label",n.fmBreadcrumb);const x=b("input","wds-input wds-fm-search");x.type="search",x.placeholder=n.fmSearch,x.setAttribute("aria-label",n.fmSearch);const S=b("select","wds-input wds-fm-sort");S.setAttribute("aria-label",n.fmSort),S.title=n.fmSort;for(const[h,m]of[["newest","fmSortNewest"],["name","fmSortName"],["largest","fmSortLargest"]]){const M=b("option",void 0,n[m]);M.value=h,S.append(M)}S.value=this.sort;const z=_e(this.view==="grid"?L.list:L.grid,this.view==="grid"?n.fmList:n.fmGrid),P=b("input");P.type="file",P.multiple=!0,P.hidden=!0,r&&(P.accept=r);const te=b("button","wds-button wds-button-primary wds-fm-upload");te.type="button",te.innerHTML=`${L.upload}<span>${qe(n.fmUpload)}</span>`;const Ge=b("div","wds-fm-tools");Ge.append(x,S,z),this.api.canUpload&&Ge.append(te,P),H.append(y,Ge);const Tt=b("div","wds-fm-main"),K=b("div","wds-fm-browser"),je=b("div","wds-fm-uploads"),W=b("ul",`wds-fm-items is-${this.view}`);W.setAttribute("aria-label",n.fmTitle);const O=b("p","wds-fm-status");O.setAttribute("role","status");const ue=b("button","wds-button",n.fmRetry);ue.type="button",ue.hidden=!0;const he=b("button","wds-button wds-fm-more",n.fmLoadMore);he.type="button",he.hidden=!0;const Dt=b("div","wds-fm-drop",n.fmDrop);Dt.setAttribute("aria-hidden","true"),K.append(je,W,O,ue,he,Dt);const G=b("aside","wds-fm-details");G.setAttribute("aria-label",n.imageEdit),Tt.append(K,G);const Ve=b("div","wds-dialog-footer");if(e.onFromUrl){const h=b("button","wds-button wds-fm-fromurl");h.type="button",h.innerHTML=`${L.globe}<span>${qe(n.fmFromUrl)}</span>`,h.addEventListener("click",()=>{oe(),e.onFromUrl()}),Ve.append(h)}const Ke=b("button","wds-button",n.cancel);Ke.type="button";const be=b("button","wds-button wds-button-primary",n.insert);be.type="button",be.disabled=!0,Ve.append(b("span","wds-spacer"),Ke,be),v.append(I,H,Tt,Ve),this.host.append(v);let we=null,j=null,ye=null,re=null,ve=null;const Se=(h,m,M,w)=>{m.id=M;const E=b("label","wds-label",h);if(E.htmlFor=M,G.append(E,m),w){const k=b("p","wds-hint",w);k.id=`${M}-hint`,m.setAttribute("aria-describedby",k.id),G.append(k)}},Ce=()=>{if(G.replaceChildren(),we=j=ve=re=null,ye=null,be.disabled=!c,!c){G.append(b("p","wds-fm-placeholder",n.fmNoSelection));return}const h=c,m=b("div","wds-fm-preview"),M=b("p","wds-fm-filename",h.name),w=b("p","wds-fm-facts"),E=()=>[h.width&&h.height?`${h.width} × ${h.height}`:"",Et(h.size),h.modified?new Date(h.modified).toLocaleDateString():""].filter(Boolean).join(" · ");if(w.textContent=E(),le(h)){const k=b("img");k.alt="",!h.thumb&&!(h.width&&h.height)&&k.addEventListener("load",()=>{!k.naturalWidth||c!==h||(h.width=k.naturalWidth,h.height=k.naturalHeight,w.textContent=E(),j&&!j.placeholder&&(j.placeholder=String(h.width)))},{once:!0}),k.src=h.thumb??h.url,m.append(k)}else m.innerHTML=L.file;if(G.append(m,M,w),e.mode==="image"&&le(h)){we=b("input","wds-input"),we.value=h.name.replace(/\.[a-z0-9]+$/i,"").replace(/[-_]+/g," "),Se(n.imageAlt,we,"wds-fm-alt",n.imageAltHint),j=b("input","wds-input"),j.inputMode="numeric",j.placeholder=h.width?String(h.width):"",Se(n.imageWidth,j,"wds-fm-width"),ye=b("select","wds-input");for(const[B,F]of In){const fe=b("option",void 0,n[F]);fe.value=B,ye.append(fe)}Se(n.imageAlign,ye,"wds-fm-align"),re=b("input"),re.type="checkbox",re.id="wds-fm-caption";const k=b("label","wds-check");k.htmlFor=re.id,k.append(re,document.createTextNode(n.caption)),G.append(k)}else ve=b("input","wds-input"),ve.value=h.name,Se(n.fmLinkText,ve,"wds-fm-text");if(this.api.canDelete){const k=b("button","wds-button wds-button-danger wds-fm-delete");k.type="button",k.innerHTML=`${L.trash}<span>${qe(n.fmDelete)}</span>`,k.addEventListener("click",()=>Pn(h)),G.append(k)}},Hn=()=>{const h=s.trim().toLocaleLowerCase(),m=i.filter(w=>Ue(w,r)&&(o||!h||w.name.toLocaleLowerCase().includes(h))),M=w=>w.modified?Date.parse(w.modified):-1/0;return this.sort==="name"?m.sort((w,E)=>w.name.localeCompare(E.name,void 0,{numeric:!0,sensitivity:"base"})):this.sort==="largest"?m.sort((w,E)=>(E.size??-1)-(w.size??-1)):m.sort((w,E)=>M(E)-M(w)),m},Ye=()=>{y.replaceChildren();const h=this.path.split("/").filter(Boolean),m=[[n.fmRoot,"/"],...h.map((M,w)=>[M,"/"+h.slice(0,w+1).join("/")])];m.forEach(([M,w],E)=>{if(E&&y.append(b("span","wds-fm-sep","/")),E===m.length-1){const k=b("span","wds-fm-crumb is-current",M);k.setAttribute("aria-current","location"),y.append(k)}else{const k=b("button","wds-fm-crumb",M);k.type="button",k.addEventListener("click",()=>Ot(w)),y.append(k)}})},ie=()=>{W.className=`wds-fm-items is-${this.view}`,W.replaceChildren();const h=!s.trim();if(h)for(const w of a){const E=It(L.folder,w.name,n.fmFolder,!0);E.addEventListener("click",()=>Ot(w.path)),W.append(Nt(E))}const m=Hn();for(const w of m){const E=le(w)?w.thumb??w.url:null,k=It(E?"":L.file,w.name,[Et(w.size),w.width&&w.height?`${w.width}×${w.height}`:""].filter(Boolean).join(" · "),!1);if(E){const F=b("img");F.loading="lazy",F.decoding="async",F.alt="",F.src=E,k.querySelector(".wds-fm-thumb").append(F)}k.dataset.url=w.url;const B=c?.url===w.url;k.classList.toggle("is-selected",B),k.setAttribute("aria-pressed",String(B)),k.addEventListener("click",()=>Je(w)),k.addEventListener("dblclick",()=>{Je(w),Xe()}),W.append(Nt(k))}const M=!m.length&&!(h&&a.length);!O.dataset.busy&&!O.dataset.error&&(O.textContent=M?s.trim()?n.fmNoResults:n.fmEmpty:""),he.hidden=!d||!!O.dataset.busy},Nt=h=>{const m=b("li");return m.append(h),m},It=(h,m,M,w)=>{const E=b("button",`wds-fm-item${w?" is-folder":""}`);E.type="button";const k=b("span","wds-fm-thumb");k.innerHTML=h;const B=b("span","wds-fm-name",m);B.title=m;const F=b("span","wds-fm-meta",M);return E.append(k,B,F),E},Je=h=>{c=h,W.querySelectorAll(".wds-fm-item[data-url]").forEach(m=>{const M=m.dataset.url===h.url;m.classList.toggle("is-selected",M),m.setAttribute("aria-pressed",String(M))}),Ce()},ke=async h=>{u?.abort(),u=new AbortController,h&&(l=1,i=[],a=[]),O.dataset.busy="1",delete O.dataset.error,O.textContent=n.fmLoading,ue.hidden=!0,he.hidden=!0,h&&ie();try{const m=await this.api.list(this.path,s.trim(),l,u.signal);if(g)return;this.path=m.path,o=m.serverSearch,d=m.hasMore,a=h?m.folders:a;const M=new Set(i.map(w=>w.url));i=[...i,...m.files.filter(w=>!M.has(w.url))],delete O.dataset.busy,O.textContent="",Ye(),ie()}catch(m){if(m.name==="AbortError"||g)return;delete O.dataset.busy,O.dataset.error="1",O.textContent=Z(n.fmListFailed,{error:m.message}),O.setAttribute("role","alert"),ue.hidden=!1}},Ot=h=>{this.path=Fe(h),s="",x.value="",c=null,Ce(),Ye(),ke(!0).then(()=>W.querySelector(".wds-fm-item")?.focus())},$t=h=>{for(const m of Array.from(h)){const M=b("div","wds-fm-upload-row"),w=b("span","wds-fm-upload-name",Z(n.fmUploading,{name:m.name}));if(!Ue(m,r)){Rt(M,Z(n.fmNotAllowed,{name:m.name})),je.append(M);continue}const E=b("progress");E.max=1,E.value=0,M.append(w,E),je.append(M),this.api.upload(m,this.path,k=>E.value=k).then(k=>{g||(M.remove(),i=[k,...i.filter(B=>B.url!==k.url)],ie(),Je(k),e.onUpload?.(k))}).catch(k=>{g||(M.replaceChildren(),Rt(M,Z(n.fmUploadFailed,{name:m.name,error:k.message})))})}},Rt=(h,m)=>{h.classList.add("is-error");const M=b("span","wds-fm-upload-name",m);M.setAttribute("role","alert");const w=_e(L.close,n.close);w.addEventListener("click",()=>h.remove()),h.append(M,w)},Pn=async h=>{if(window.confirm(Z(n.fmDeleteConfirm,{name:h.name})))try{await this.api.remove(h.url),i=i.filter(m=>m.url!==h.url),c=null,Ce(),ie()}catch(m){O.dataset.error="1",O.setAttribute("role","alert"),O.textContent=Z(n.fmDeleteFailed,{error:m.message})}},Xe=()=>{if(!c)return;const h=j?parseInt(j.value,10):NaN;e.onPick({file:c,alt:we?.value.trim()??"",width:Number.isFinite(h)&&h>0?h:null,align:ye?.value||null,text:ve?.value.trim()||c.name,caption:!!re?.checked}),oe()};function oe(){g||(g=!0,u?.abort(),window.clearTimeout(p),v.open&&v.close(),v.remove(),e.onClose?.())}if(C.addEventListener("click",oe),Ke.addEventListener("click",oe),be.addEventListener("click",Xe),v.addEventListener("close",oe),v.addEventListener("click",h=>h.target===v&&oe()),ue.addEventListener("click",()=>{O.setAttribute("role","status"),ke(!0)}),he.addEventListener("click",()=>{l++,ke(!1)}),S.addEventListener("change",()=>{this.sort=S.value,ie()}),z.addEventListener("click",()=>{this.view=this.view==="grid"?"list":"grid",z.innerHTML=this.view==="grid"?L.list:L.grid;const h=this.view==="grid"?n.fmList:n.fmGrid;z.setAttribute("aria-label",h),z.title=h,ie()}),x.addEventListener("input",()=>{window.clearTimeout(p),p=window.setTimeout(()=>{s=x.value,!o&&!d?ie():ke(!0)},250)}),te.addEventListener("click",()=>P.click()),P.addEventListener("change",()=>{P.files?.length&&$t(P.files),P.value=""}),this.api.canUpload){let h=0;K.addEventListener("dragenter",m=>{m.dataTransfer?.types.includes("Files")&&(h++,K.classList.add("is-dragging"))}),K.addEventListener("dragleave",()=>{h=Math.max(0,h-1),h||K.classList.remove("is-dragging")}),K.addEventListener("dragover",m=>{m.dataTransfer?.types.includes("Files")&&m.preventDefault()}),K.addEventListener("drop",m=>{m.preventDefault(),h=0,K.classList.remove("is-dragging"),m.dataTransfer?.files.length&&$t(m.dataTransfer.files)})}return W.addEventListener("keydown",h=>{if(!["ArrowRight","ArrowLeft","ArrowDown","ArrowUp","Home","End"].includes(h.key))return;const M=[...W.querySelectorAll(".wds-fm-item")],w=M.indexOf(document.activeElement);if(w<0)return;h.preventDefault();const E=M[0].offsetTop,k=this.view==="list"?1:Math.max(1,M.findIndex(fe=>fe.offsetTop!==E)===-1?M.length:M.findIndex(fe=>fe.offsetTop!==E)),B={ArrowRight:1,ArrowLeft:-1,ArrowDown:k,ArrowUp:-k},F=h.key==="Home"?0:h.key==="End"?M.length-1:Math.min(M.length-1,Math.max(0,w+B[h.key]));M[F].focus()}),G.addEventListener("keydown",h=>{h.key==="Enter"&&h.target.tagName==="INPUT"&&(h.preventDefault(),Xe())}),Ye(),Ce(),v.showModal(),x.focus(),ke(!0),oe}}function qe(t){const e=document.createElement("span");return e.textContent=t,e.innerHTML}const ce=new WeakMap,Ct=t=>t===void 0?void 0:typeof t=="number"?`${t}px`:t;function $n(t){return t===!1?[]:t===void 0||t==="default"?mt:Array.isArray(t)?t:t.split(/\s+/).filter(Boolean)}const de=class de{constructor(e,n={}){if(this.listeners=new Map,this.notice=null,this.noticeTimer=0,this.onFormSubmit=()=>this.syncTarget(),this.onKeydown=o=>{o.key==="Escape"&&this.fullscreen&&this.toggleFullscreen()},this.sourceMode=!1,this.plainPaste=!1,this.fullscreen=!1,this.destroyed=!1,ce.has(e))throw new Error("[WDS Editor] This element already has an editor. Use WDSEditor.get() or destroy() first.");this.target=e,this.options=n,this.t=En(n.language),this.readOnly=!!n.readOnly,this.textarea=e instanceof HTMLTextAreaElement?e:null,this.originalContent=this.textarea?this.textarea.value:e.innerHTML;const r=n.content??this.originalContent;this.root=document.createElement("div"),this.root.className="wds-editor",this.root.dataset.theme=n.theme??"light",this.fileManager=n.fileManager?.listUrl?new On(this.root,new Nn(n.fileManager),this.t):null,this.contentWrap=document.createElement("div"),this.contentWrap.className="wds-content-wrap";const i=Ct(n.height);i?(this.contentWrap.style.height=i,this.root.classList.add("wds-fixed-height")):this.contentWrap.style.minHeight=Ct(n.minHeight??240),this.sourceArea=document.createElement("textarea"),this.sourceArea.className="wds-source",this.sourceArea.spellcheck=!1,this.sourceArea.hidden=!0,this.sourceArea.setAttribute("aria-label",this.t.sourceLabel);const a=$.EditorState.create({schema:f,doc:Me(r),plugins:[N.tableEditing(),Te.keymap({Tab:ln,"Shift-Tab":cn}),un(),hn({link:()=>(this.openLinkDialog(),!0)}),fn(),Y.history(),pn(n.placeholder??""),mn(),zt.gapCursor(),Ht.dropCursor({class:"wds-dropcursor",color:!1})]}),l={onEdit:()=>this.openImageUrlDialog(),resizeLabel:this.t.resizeImage,captionPlaceholder:this.t.captionPlaceholder};this.view=new pe.EditorView(this.contentWrap,{state:a,editable:()=>!this.readOnly,attributes:{class:"wds-content",role:"textbox","aria-multiline":"true","aria-label":this.t.editorLabel},dispatchTransaction:o=>this.dispatch(o),transformPastedHTML:Bt,handlePaste:(o,s)=>{const c=s.clipboardData;if(this.plainPaste&&c){const p=c.getData("text/plain");if(p)return o.dispatch(o.state.tr.replaceSelection(Rn(p)).scrollIntoView()),!0}if(!c?.files.length||!this.canUploadInline()||c.getData("text/plain"))return!1;const u=[...c.files].filter(p=>p.type.startsWith("image/"));return u.length?(this.uploadFiles(u),!0):!1},handleDrop:(o,s,c,u)=>{const p=s.dataTransfer?.files;if(u||!p?.length||!this.canUploadInline())return!1;const g=o.posAtCoords({left:s.clientX,top:s.clientY})?.pos;return s.preventDefault(),this.uploadFiles([...p],g),!0},nodeViews:{image:(o,s,c)=>new kn(o,s,c,l),figure:(o,s,c)=>new Mn(o,s,c,l)},handleDOMEvents:{focus:()=>(this.root.classList.add("is-focused"),this.emit("focus"),!1),blur:()=>(this.root.classList.remove("is-focused"),this.emit("blur"),!1)}}),this.contentWrap.append(this.sourceArea),this.toolbar=vn(this,$n(n.toolbar),this.t),this.toolbar.element.childElementCount&&this.toolbar.element.firstElementChild.childElementCount&&this.root.append(this.toolbar.element),this.root.append(this.contentWrap);const d=document.createElement("div");if(d.className="wds-statusbar",this.counter=n.wordCount===!1?null:document.createElement("span"),this.counter&&(this.counter.className="wds-counter",this.counter.setAttribute("aria-live","off"),d.append(this.counter)),n.branding!==!1){const o=document.createElement("a");o.className="wds-branding",o.href="https://webdevsnippets.com/wds-editor",o.target="_blank",o.rel="noopener",o.innerHTML=`${zn(this.t.poweredBy)} <strong>WDS Editor</strong>`,d.append(o)}d.childElementCount&&this.root.append(d),this.textarea?(this.textarea.style.display="none",this.textarea.after(this.root),this.textarea.form?.addEventListener("submit",this.onFormSubmit)):e.replaceChildren(this.root),document.addEventListener("keydown",this.onKeydown),ce.set(e,this),this.lastHtml=this.getHTML(),this.syncTarget(),this.refresh(),this.emit("init")}static init(e){const n=typeof e.selector=="string"?document.querySelector(e.selector):e.selector;if(!n)throw new Error(`[WDS Editor] No element matches "${String(e.selector)}".`);return ce.get(n)??new de(n,e)}static initAll(e){return[...document.querySelectorAll(e.selector)].map(n=>ce.get(n)??new de(n,e))}static get(e){const n=typeof e=="string"?document.querySelector(e):e;return n?ce.get(n):void 0}getHTML(){return this.sourceMode&&this.applySource(),Le(this.view.state.doc)}setHTML(e){this.sourceMode&&(this.sourceArea.value=ct(e));const n=Me(e),r=this.view.state.tr.replaceWith(0,this.view.state.doc.content.size,n.content);this.dispatch(r.setSelection($.TextSelection.atStart(r.doc)))}insertHTML(e){const n=Me(e),r=J.Slice.maxOpen(n.content);this.dispatch(this.view.state.tr.replaceSelection(r).scrollIntoView())}getText(){const e=this.view.state.doc;return e.textBetween(0,e.content.size,`
1
+ (function(D,H){typeof exports=="object"&&typeof module<"u"?H(exports,require("prosemirror-state"),require("prosemirror-view"),require("prosemirror-history"),require("prosemirror-model"),require("prosemirror-schema-list"),require("prosemirror-tables"),require("prosemirror-inputrules"),require("prosemirror-keymap"),require("prosemirror-commands"),require("prosemirror-gapcursor"),require("prosemirror-dropcursor")):typeof define=="function"&&define.amd?define(["exports","prosemirror-state","prosemirror-view","prosemirror-history","prosemirror-model","prosemirror-schema-list","prosemirror-tables","prosemirror-inputrules","prosemirror-keymap","prosemirror-commands","prosemirror-gapcursor","prosemirror-dropcursor"],H):(D=typeof globalThis<"u"?globalThis:D||self,H(D.WDSEditor={},D.PMState,D.PMView,D.PMHistory,D.PMModel,D["PMSchema-list"],D.PMTables,D.PMInputrules,D.PMKeymap,D.PMCommands,D.PMGapcursor,D.PMDropcursor))})(this,(function(D,H,pe,Y,J,oe,I,X,Ce,_,Gt,jt){"use strict";const Vt=/^(https?:|mailto:|tel:)/i,rt=/^[a-z][a-z0-9+.-]*:/i;function V(t){if(t==null)return null;const e=t.trim();if(!e)return null;const n=e.replace(/[\u0000- \u007f-\u009f]/g,"");return rt.test(n)&&!Vt.test(n)?null:e}function it(t){const e=t.trim();return e?/^[^\s@/]+@[^\s@/]+\.[^\s@/]+$/.test(e)?`mailto:${e}`:!rt.test(e)&&!/^[/#?.]/.test(e)&&/^[\w-]+(\.[\w-]+)+/.test(e)?`https://${e}`:V(e):null}function Kt(t){return t.replace(/<!--[\s\S]*?-->/g,"").replace(/<\/?o:p[^>]*>/gi,"").replace(/<\/?(w|m|v):[^>]*>/gi,"").replace(/<xml[\s\S]*?<\/xml>/gi,"").replace(/<style[\s\S]*?<\/style>/gi,"").replace(/<meta[^>]*>/gi,"").replace(/<link[^>]*>/gi,"")}const ot={black:"#000000",white:"#ffffff",red:"#ff0000",green:"#008000",blue:"#0000ff",yellow:"#ffff00",orange:"#ffa500",purple:"#800080",pink:"#ffc0cb",gray:"#808080",grey:"#808080",silver:"#c0c0c0",navy:"#000080",teal:"#008080",maroon:"#800000",olive:"#808000",lime:"#00ff00",aqua:"#00ffff",cyan:"#00ffff",fuchsia:"#ff00ff",magenta:"#ff00ff",darkred:"#8b0000",darkblue:"#00008b",darkgreen:"#006400",lightgray:"#d3d3d3",lightgrey:"#d3d3d3",darkgray:"#a9a9a9",darkgrey:"#a9a9a9"},De=t=>Math.max(0,Math.min(255,Math.round(t))).toString(16).padStart(2,"0");function ae(t){if(!t)return null;const e=t.trim().toLowerCase().replace(/\s*!important$/,"");if(ot[e])return ot[e];let n=/^#([0-9a-f]{3})$/.exec(e);return n?"#"+[...n[1]].map(r=>r+r).join(""):(n=/^#([0-9a-f]{6})(ff)?$/.exec(e),n?"#"+n[1]:(n=/^rgba?\(\s*(\d+(?:\.\d+)?)[\s,]+(\d+(?:\.\d+)?)[\s,]+(\d+(?:\.\d+)?)(?:\s*[,/]\s*([\d.]+%?))?\s*\)$/.exec(e),n?n[4]!==void 0&&(n[4].endsWith("%")?parseFloat(n[4])/100:parseFloat(n[4]))<1?null:"#"+De(+n[1])+De(+n[2])+De(+n[3]):null))}function at(t){const e=ae(t);return e&&e!=="#000000"?e:null}function Ne(t){const e=ae(t)??ae((t??"").split(/\s+(?![^(]*\))/).find(n=>ae(n)));return e&&e!=="#ffffff"?e:null}const Yt=[{color:"#dc2626",name:"colorRed"},{color:"#ea580c",name:"colorOrange"},{color:"#ca8a04",name:"colorAmber"},{color:"#16a34a",name:"colorGreen"},{color:"#0d9488",name:"colorTeal"},{color:"#2563eb",name:"colorBlue"},{color:"#7c3aed",name:"colorPurple"},{color:"#db2777",name:"colorPink"},{color:"#475569",name:"colorSlate"},{color:"#94a3b8",name:"colorGray"}],Jt=[{color:"#fef08a",name:"colorYellow"},{color:"#bbf7d0",name:"colorGreen"},{color:"#bae6fd",name:"colorBlue"},{color:"#fbcfe8",name:"colorPink"},{color:"#fed7aa",name:"colorOrange"},{color:"#e9d5ff",name:"colorPurple"}],Xt=["left","center","right","justify"];function st(t){const e=(t.style.textAlign||t.getAttribute("align")||"").toLowerCase();return Xt.includes(e)&&e!=="left"?e:null}function lt(t){return t?{style:`text-align: ${t}`}:{}}const Qt={left:"float: left; margin: 0 1em 1em 0",right:"float: right; margin: 0 0 1em 1em",center:"display: block; margin-left: auto; margin-right: auto"},Zt={left:"float: left; margin: 0 1em 1em 0",right:"float: right; margin: 0 0 1em 1em",center:"display: table; margin-left: auto; margin-right: auto"};function en(t){const e=t.style.float||t.getAttribute("align")||"";return e==="left"||e==="right"?e:(t.style.display==="block"||t.style.display==="table")&&t.style.marginLeft==="auto"&&t.style.marginRight==="auto"?"center":null}const ct={src:{},alt:{default:""},title:{default:null},width:{default:null},height:{default:null},align:{default:null}};function dt(t,e){const n=V(t.getAttribute("src"));return n?{src:n,alt:t.getAttribute("alt")??"",title:t.getAttribute("title"),width:ut(t.getAttribute("width")??t.style.width),height:ut(t.getAttribute("height")??t.style.height),align:en(e)}:!1}function Ie(t,e){const{src:n,alt:r,title:i,width:s,height:c,align:d}=t,o={src:n,alt:r??""};i&&(o.title=i),s&&(o.width=String(s)),s&&c&&(o.height=String(c));const a=e?Qt[d]:void 0;return a&&(o.style=a),o}function ut(t){const e=/^\s*(\d{1,5})(px)?\s*$/.exec(t??"");return e?Number(e[1]):null}const tn={doc:{content:"block+"},paragraph:{content:"inline*",group:"block",attrs:{align:{default:null}},parseDOM:[{tag:"p",getAttrs:t=>({align:st(t)})}],toDOM:t=>["p",lt(t.attrs.align),0]},heading:{content:"inline*",group:"block",defining:!0,attrs:{level:{default:2},align:{default:null}},parseDOM:[1,2,3,4,5,6].map(t=>({tag:`h${t}`,getAttrs:e=>({level:Math.min(t,4),align:st(e)})})),toDOM:t=>[`h${t.attrs.level}`,lt(t.attrs.align),0]},blockquote:{content:"block+",group:"block",defining:!0,parseDOM:[{tag:"blockquote"}],toDOM:()=>["blockquote",0]},horizontal_rule:{group:"block",parseDOM:[{tag:"hr"}],toDOM:()=>["hr"]},code_block:{content:"text*",marks:"",group:"block",code:!0,defining:!0,attrs:{language:{default:null}},parseDOM:[{tag:"pre",preserveWhitespace:"full",getAttrs:t=>{const e=t.querySelector("code"),n=/language-([\w-]+)/.exec(e?.className??"");return{language:n?n[1]:null}}}],toDOM:t=>["pre",["code",t.attrs.language?{class:`language-${t.attrs.language}`}:{},0]]},...I.tableNodes({tableGroup:"block",cellContent:"block+",cellAttributes:{}}),text:{group:"inline"},image:{inline:!0,group:"inline",draggable:!0,attrs:ct,parseDOM:[{tag:"img[src]",getAttrs:t=>dt(t,t)}],toDOM:t=>["img",Ie(t.attrs,!0)]},figure:{group:"block",content:"inline*",marks:"_",draggable:!0,isolating:!0,attrs:ct,parseDOM:[{tag:"figure",getAttrs:t=>{const e=t.querySelector("img");return e?dt(e,t):!1},contentElement:t=>t.querySelector("figcaption")??document.createElement("figcaption")}],toDOM:t=>{const e=Zt[t.attrs.align];return["figure",e?{style:e}:{},["img",Ie(t.attrs,!1)],["figcaption",0]]}},hard_break:{inline:!0,group:"inline",selectable:!1,parseDOM:[{tag:"br"}],toDOM:()=>["br"]}},nn={link:{attrs:{href:{},title:{default:null},target:{default:null}},inclusive:!1,parseDOM:[{tag:"a[href]",getAttrs:t=>{const e=t,n=V(e.getAttribute("href"));return n?{href:n,title:e.getAttribute("title"),target:e.getAttribute("target")==="_blank"?"_blank":null}:!1}}],toDOM:t=>{const e={href:t.attrs.href};return t.attrs.title&&(e.title=t.attrs.title),t.attrs.target==="_blank"&&(e.target="_blank",e.rel="noopener noreferrer"),["a",e,0]}},strong:{parseDOM:[{tag:"strong"},{tag:"b",getAttrs:t=>t.style.fontWeight!=="normal"&&null},{style:"font-weight=400",clearMark:t=>t.type.name==="strong"},{style:"font-weight",getAttrs:t=>/^(bold(er)?|[5-9]\d{2,})$/.test(t)&&null}],toDOM:()=>["strong",0]},em:{parseDOM:[{tag:"i"},{tag:"em"},{style:"font-style=italic"},{style:"font-style=normal",clearMark:t=>t.type.name==="em"}],toDOM:()=>["em",0]},underline:{parseDOM:[{tag:"u"},{style:"text-decoration=underline"},{style:"text-decoration-line=underline"}],toDOM:()=>["u",0]},strike:{parseDOM:[{tag:"s"},{tag:"del"},{tag:"strike"},{style:"text-decoration=line-through"},{style:"text-decoration-line=line-through"}],toDOM:()=>["s",0]},textColor:{attrs:{color:{}},parseDOM:[{tag:"span",getAttrs:t=>{const e=at(t.style.color);return e?{color:e}:!1}},{tag:"font[color]",getAttrs:t=>{const e=at(t.getAttribute("color"));return e?{color:e}:!1}}],toDOM:t=>["span",{style:`color: ${t.attrs.color}`},0]},highlight:{attrs:{color:{default:"#fef08a"}},parseDOM:[{tag:"mark",getAttrs:t=>({color:Ne(t.style.backgroundColor)??"#fef08a"})},{style:"background-color",getAttrs:t=>{const e=Ne(t);return e?{color:e}:!1}},{style:"background",getAttrs:t=>{const e=Ne(t);return e?{color:e}:!1}}],toDOM:t=>["mark",{style:`background-color: ${ae(t.attrs.color)??"#fef08a"}`},0]},code:{parseDOM:[{tag:"code"}],toDOM:()=>["code",0]}},ht=new J.Schema({nodes:tn,marks:nn}),f=new J.Schema({nodes:oe.addListNodes(ht.spec.nodes,"paragraph block*","block"),marks:ht.spec.marks}),rn=J.DOMSerializer.fromSchema(f),on=J.DOMParser.fromSchema(f);function Le(t){const e=new window.DOMParser().parseFromString(`<!doctype html><body>${t}`,"text/html");return on.parse(e.body)}function xe(t){if(ft(t))return"";const e=document.createElement("div");return e.append(rn.serializeFragment(t.content)),e.querySelectorAll("[style]").forEach(n=>n.setAttribute("style",sn(n.getAttribute("style")??""))),e.innerHTML}const an=(t,e,n,r)=>"#"+[e,n,r].map(i=>(+i).toString(16).padStart(2,"0")).join("");function sn(t){return t.split(";").map(e=>e.trim()).filter(Boolean).map(e=>e.replace(/rgb\(\s*(\d+),\s*(\d+),\s*(\d+)\s*\)/g,an).replace(/(^|[\s:])0px(?![\w.])/g,(n,r)=>`${r}0`).replace(/\s*:\s*/,": ")).join("; ")}function ft(t){const e=t.firstChild;return t.childCount===1&&!!e&&e.type===f.nodes.paragraph&&e.content.size===0&&!e.attrs.align}const Oe=new Set(["UL","OL","BLOCKQUOTE","TABLE","THEAD","TBODY","TFOOT","TR","FIGURE"]),Re=new Set(["LI","TH","TD"]),pt=t=>t.nodeType===1&&(Oe.has(t.tagName)||Re.has(t.tagName)||/^(P|H[1-6]|PRE|HR|FIGCAPTION|IMG|DIV)$/.test(t.tagName)),ln=t=>{const n=t.cloneNode(!1).outerHTML;return n.slice(0,n.length-`</${t.localName}>`.length)};function mt(t){const e=document.createElement("div");e.innerHTML=t;const n=[],r=(i,s)=>{const c=" ".repeat(s);let d="";const o=()=>{d.trim()&&n.push(c+d.trim()),d=""};i.childNodes.forEach(a=>{if(!pt(a)){d+=a.nodeType===1?a.outerHTML:a.nodeType===3?cn(a.textContent??""):"";return}o();const l=a,u=Array.from(l.childNodes).filter(pt);(Re.has(l.tagName)?u.length<=1&&u.every(g=>!Oe.has(g.tagName)&&!Re.has(g.tagName)):!Oe.has(l.tagName))?n.push(c+l.outerHTML):(n.push(c+ln(l)),r(l,s+1),n.push(`${c}</${l.localName}>`))}),o()};return r(e,0),n.join(`
2
+ `)}const cn=t=>t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/ /g,"&nbsp;");function me(t,e){const{from:n,$from:r,to:i,empty:s}=t.selection;return s?!!e.isInSet(t.storedMarks||r.marks()):t.doc.rangeHasMark(n,i,e)}function dn(t){const e=t.selection.$from.parent;return e.type===f.nodes.paragraph?"paragraph":e.type===f.nodes.code_block?"codeBlock":e.type===f.nodes.heading?`heading${e.attrs.level}`:null}function un(t){return t==="paragraph"?_.setBlockType(f.nodes.paragraph):t==="codeBlock"?_.setBlockType(f.nodes.code_block):_.setBlockType(f.nodes.heading,{level:Number(t.slice(-1))})}const W=t=>_.toggleMark(f.marks[t]);function gt(t,e){const{$from:n}=t.selection;for(let r=n.depth;r>0;r--)if(n.node(r).type===e)return!0;return!1}function bt(t){const{$from:e}=t.selection;for(let n=e.depth;n>0;n--){const r=e.node(n).type;if(r===f.nodes.bullet_list||r===f.nodes.ordered_list)return r}return null}function wt(t){return(e,n,r)=>{const{$from:i}=e.selection;for(let s=i.depth;s>0;s--){const c=i.node(s);if(c.type===f.nodes.bullet_list||c.type===f.nodes.ordered_list)return c.type===t?oe.liftListItem(f.nodes.list_item)(e,n,r):(n&&n(e.tr.setNodeMarkup(i.before(s),t)),!0)}return oe.wrapInList(t)(e,n,r)}}const He=oe.sinkListItem(f.nodes.list_item),$e=(t,e,n)=>oe.liftListItem(f.nodes.list_item)(t,e,n)||_.lift(t,e);function hn(){return(t,e)=>gt(t,f.nodes.blockquote)?_.lift(t,e):_.wrapIn(f.nodes.blockquote)(t,e)}function yt(t,e="left"){return(n,r)=>{const i=t===e?null:t,{from:s,to:c}=n.selection,d=n.tr;let o=!1;return n.doc.nodesBetween(s,c,(a,l)=>a.type===f.nodes.paragraph||a.type===f.nodes.heading?(o=!0,a.attrs.align!==i&&d.setNodeMarkup(l,void 0,{...a.attrs,align:i}),!1):!0),o?(r&&r(d),!0):!1}}function fn(t,e="left"){return t.selection.$from.parent.attrs.align??e}const pn=(t,e)=>{const n=f.nodes.horizontal_rule;if(!e)return!0;const r=t.tr.replaceSelectionWith(n.create()),i=r.selection.$from;return!i.nodeAfter&&i.parent.type===f.nodes.doc&&r.insert(i.pos,f.nodes.paragraph.create()),e(r.scrollIntoView()),!0},mn=(t,e)=>{const{from:n,to:r,empty:i}=t.selection,s=t.tr;if(i)s.setStoredMarks([]);else for(const c of Object.values(f.marks))c!==f.marks.link&&s.removeMark(n,r,c);return t.doc.nodesBetween(n,r,(c,d)=>c.isTextblock&&c.type!==f.nodes.paragraph?(s.setBlockType(d,d+c.nodeSize,f.nodes.paragraph),!1):(c.type===f.nodes.paragraph&&c.attrs.align&&s.setNodeMarkup(d,void 0,{align:null}),!0)),e&&e(s),!0};function ze(t){const e=f.marks.link,{$from:n,from:r,to:i,empty:s}=t.selection;if(!s){let u=null;return t.doc.nodesBetween(r,i,(p,g)=>{const k=e.isInSet(p.marks);k&&!u&&(u={from:Math.max(g,r),to:Math.min(g+p.nodeSize,i),...k.attrs})}),u}const c=e.isInSet(n.marks())??e.isInSet(n.nodeBefore?.marks??[]);if(!c)return null;const d=n.start(),o=[];let a=0;n.parent.forEach(u=>{const p=d+a,g=p+u.nodeSize;if(c.isInSet(u.marks)){const k=o[o.length-1];k&&k[1]===p?k[1]=g:o.push([p,g])}a+=u.nodeSize});const l=o.find(([u,p])=>u<=n.pos&&n.pos<=p);return l?{from:l[0],to:l[1],...c.attrs}:null}function Pe(t){const e=t.selection;return e instanceof H.NodeSelection&&(e.node.type===f.nodes.image||e.node.type===f.nodes.figure)?{pos:e.from,attrs:e.node.attrs,figure:e.node.type===f.nodes.figure,node:e.node}:null}function vt(t,e,n){const r=f.nodes.figure.create(n),i=t.doc.resolve(e),s=i.parent;s.type===f.nodes.paragraph&&s.childCount===1?t.replaceWith(i.before(),i.after(),r):t.replaceRangeWith(e,e+1,r);let c=-1;return t.doc.descendants((d,o)=>c>=0?!1:(d.type===f.nodes.figure&&d.attrs.src===n.src&&d.content.size===0&&(c=o),!0)),c>=0&&t.setSelection(H.TextSelection.create(t.doc,c+1)),t}function gn(t,e,n,r){const i=f.nodes.image.create(r),s=[f.nodes.paragraph.create(null,i)];return n.content.size&&s.push(f.nodes.paragraph.create(null,n.content)),t.replaceWith(e,e+n.nodeSize,J.Fragment.from(s)),t.setSelection(H.NodeSelection.create(t.doc,e+1))}function bn(t,e,n=!0){const r=f.nodes,i=s=>r.table_row.create(null,Array.from({length:e},()=>s.createAndFill()));return r.table.create(null,Array.from({length:t},(s,c)=>i(n&&c===0?r.table_header:r.table_cell)))}function wn(t,e){return(n,r)=>{if(I.isInTable(n))return!1;if(!r)return!0;const i=bn(t,e),s=n.tr,c=n.selection.$from;c.parent.type===f.nodes.paragraph&&c.parent.content.size===0&&c.depth===1?s.replaceWith(c.before(),c.after(),i):s.replaceSelectionWith(i);let o=-1;if(s.doc.descendants((a,l)=>o>=0?!1:(a===i&&(o=l),o<0&&a.type!==f.nodes.table)),o>=0){const a=o+s.doc.nodeAt(o).nodeSize;a>=s.doc.content.size&&s.insert(a,f.nodes.paragraph.create()),s.setSelection(H.TextSelection.create(s.doc,o+4))}return r(s.scrollIntoView()),!0}}const yn=(t,e,n)=>I.isInTable(t)?I.goToNextCell(1)(t,e)||!e||!n?!0:(I.addRowAfter(t,e),I.goToNextCell(1)(n.state,e)):!1,vn=(t,e)=>I.isInTable(t)&&I.goToNextCell(-1)(t,e);function Be(t,e){const n=f.marks[e],{from:r,to:i,empty:s,$from:c}=t.selection;if(s)return n.isInSet(t.storedMarks||c.marks())?.attrs.color??null;let d;return t.doc.nodesBetween(r,i,o=>{if(!o.isText||d===null)return;const a=n.isInSet(o.marks)?.attrs.color??null;d=d===void 0||d===a?a:null}),d??null}function kn(t,e){return(n,r)=>{const i=f.marks[t],{from:s,to:c,empty:d}=n.selection;if(!r)return!0;const o=n.tr;return d?(o.removeStoredMark(i),e&&o.addStoredMark(i.create({color:e}))):(o.removeMark(s,c,i),e&&o.addMark(s,c,i.create({color:e}))),r(o.scrollIntoView()),!0}}function Mn(){const t=f.nodes;return X.inputRules({rules:[X.textblockTypeInputRule(/^(#{1,4})\s$/,t.heading,e=>({level:e[1].length})),X.wrappingInputRule(/^\s*>\s$/,t.blockquote),X.wrappingInputRule(/^\s*([-+*])\s$/,t.bullet_list),X.wrappingInputRule(/^(\d+)\.\s$/,t.ordered_list,e=>({order:+e[1]}),(e,n)=>n.childCount+n.attrs.order===+e[1]),X.textblockTypeInputRule(/^```$/,t.code_block),new X.InputRule(/^(?:---|\*\*\*|___)$/,(e,n,r,i)=>{const s=e.doc.resolve(r);if(s.parent.type!==t.paragraph)return null;const c=s.before();return e.tr.replaceWith(c,i+1,[t.horizontal_rule.create(),t.paragraph.create()])})]})}function Ln(t){const e=_.chainCommands(_.exitCode,(n,r)=>(r&&r(n.tr.replaceSelectionWith(f.nodes.hard_break.create()).scrollIntoView()),!0));return Ce.keymap({"Mod-z":Y.undo,"Mod-y":Y.redo,"Shift-Mod-z":Y.redo,Backspace:X.undoInputRule,"Mod-b":W("strong"),"Mod-i":W("em"),"Mod-u":W("underline"),"Mod-Shift-x":W("strike"),"Mod-e":W("code"),"Mod-k":t.link,"Shift-Enter":e,"Mod-Enter":e,Enter:oe.splitListItem(f.nodes.list_item),Tab:He,"Shift-Tab":$e})}const xn=()=>Ce.keymap(_.baseKeymap);function En(t){return new H.Plugin({props:{decorations(e){const n=e.doc,r=n.firstChild;return!t||n.childCount!==1||!r||!r.isTextblock||r.content.size>0?null:pe.DecorationSet.create(n,[pe.Decoration.node(0,r.nodeSize,{class:"wds-placeholder","data-placeholder":t})])}}})}const te=new H.PluginKey("wds-upload");function An(){return new H.Plugin({key:te,state:{init:()=>pe.DecorationSet.empty,apply(t,e){e=e.map(t.mapping,t.doc);const n=t.getMeta(te);if(n&&"add"in n){const r=document.createElement("span");r.className="wds-upload-placeholder",r.setAttribute("aria-hidden","true"),e=e.add(t.doc,[pe.Decoration.widget(n.add.pos,r,{id:n.add.id})])}else n&&"remove"in n&&(e=e.remove(e.find(void 0,void 0,r=>r.id===n.remove.id)));return e}},props:{decorations:t=>te.getState(t)}})}function Sn(t,e){const n=te.getState(t)?.find(void 0,void 0,r=>r.id===e);return n&&n.length?n[0].from:null}const E=t=>`<svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false">${t}</svg>`,L={undo:E('<path d="M9 14 4 9l5-5"/><path d="M4 9h11a5 5 0 0 1 0 10h-3"/>'),redo:E('<path d="m15 14 5-5-5-5"/><path d="M20 9H9a5 5 0 0 0 0 10h3"/>'),bold:E('<path d="M7 5h6a3.5 3.5 0 0 1 0 7H7z"/><path d="M7 12h7a3.5 3.5 0 0 1 0 7H7z"/>'),italic:E('<path d="M14 5h-4"/><path d="M14 19h-4"/><path d="m14 5-4 14"/><path d="M18 5h-4M10 19H6"/>'),underline:E('<path d="M7 4v7a5 5 0 0 0 10 0V4"/><path d="M5 20h14"/>'),strike:E('<path d="M4 12h16"/><path d="M16.5 7.5C16 5.6 14.2 4.5 12 4.5c-2.6 0-4.5 1.4-4.5 3.4 0 1.3.8 2.3 2.4 3"/><path d="M8 16.5c.6 1.9 2.2 3 4.3 3 2.7 0 4.6-1.4 4.6-3.6 0-.9-.3-1.6-.9-2.2"/>'),code:E('<path d="m9 8-4 4 4 4"/><path d="m15 8 4 4-4 4"/>'),link:E('<path d="M10 14a4.5 4.5 0 0 0 6.4 0l3-3a4.5 4.5 0 0 0-6.4-6.4l-1 1"/><path d="M14 10a4.5 4.5 0 0 0-6.4 0l-3 3a4.5 4.5 0 0 0 6.4 6.4l1-1"/>'),blockquote:E('<path d="M5 18c2.5-1 4-3.2 4-6.5V7H5v5h3"/><path d="M14 18c2.5-1 4-3.2 4-6.5V7h-4v5h3"/>'),bulletList:E('<circle cx="5" cy="7" r="1" fill="currentColor"/><circle cx="5" cy="12" r="1" fill="currentColor"/><circle cx="5" cy="17" r="1" fill="currentColor"/><path d="M9 7h11M9 12h11M9 17h11"/>'),orderedList:E('<path d="M10 7h10M10 12h10M10 17h10"/><path d="M4 5.5 5.5 5v4"/><path d="M4 14.2c.3-.6.8-.9 1.4-.9.7 0 1.1.4 1.1 1 0 .9-1.4 1.6-2.5 2.7h2.6"/>'),indent:E('<path d="M4 6h16M10 10h10M10 14h10M4 18h16"/><path d="m4 9.5 3 2.5-3 2.5"/>'),outdent:E('<path d="M4 6h16M10 10h10M10 14h10M4 18h16"/><path d="m7 9.5-3 2.5 3 2.5"/>'),alignLeft:E('<path d="M4 6h16M4 10h10M4 14h16M4 18h10"/>'),alignCenter:E('<path d="M4 6h16M7 10h10M4 14h16M7 18h10"/>'),alignRight:E('<path d="M4 6h16M10 10h10M4 14h16M10 18h10"/>'),alignJustify:E('<path d="M4 6h16M4 10h16M4 14h16M4 18h16"/>'),hr:E('<path d="M3 12h18"/><path d="M8 7h8M8 17h8" opacity=".45"/>'),clear:E('<path d="M6 5h12"/><path d="M12 5 9 19"/><path d="m15 14 5 5M20 14l-5 5"/>'),source:E('<path d="m8 7-5 5 5 5"/><path d="m16 7 5 5-5 5"/><path d="m14 4-4 16"/>'),fullscreen:E('<path d="M4 9V4h5M20 9V4h-5M4 15v5h5M20 15v5h-5"/>'),chevron:'<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false"><path d="m6 9 6 6 6-6"/></svg>',close:E('<path d="M6 6l12 12M18 6 6 18"/>'),image:E('<rect x="3" y="4" width="18" height="16" rx="2"/><circle cx="8.5" cy="9.5" r="1.5"/><path d="m21 16-5-5-9 9"/>'),file:E('<path d="M14 3H7a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8z"/><path d="M14 3v5h5"/><path d="M9 13h6M9 17h4"/>'),folder:E('<path d="M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/>'),upload:E('<path d="M12 16V4"/><path d="m7 9 5-5 5 5"/><path d="M4 16v3a1 1 0 0 0 1 1h14a1 1 0 0 0 1-1v-3"/>'),grid:E('<rect x="4" y="4" width="6" height="6" rx="1"/><rect x="14" y="4" width="6" height="6" rx="1"/><rect x="4" y="14" width="6" height="6" rx="1"/><rect x="14" y="14" width="6" height="6" rx="1"/>'),list:E('<path d="M9 6h11M9 12h11M9 18h11"/><path d="M4 6h1M4 12h1M4 18h1"/>'),trash:E('<path d="M4 7h16"/><path d="M10 11v6M14 11v6"/><path d="M6 7l1 12a2 2 0 0 0 2 2h6a2 2 0 0 0 2-2l1-12"/><path d="M9 7V4h6v3"/>'),table:E('<rect x="3" y="4" width="18" height="16" rx="2"/><path d="M3 10h18M3 15h18M9 4v16M15 4v16"/>'),pasteText:E('<path d="M9 4h6v3H9z"/><path d="M15 5h2a2 2 0 0 1 2 2v12a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V7a2 2 0 0 1 2-2h2"/><path d="M9 12h6M12 12v6"/>'),textColor:E('<path d="m6 16 6-12 6 12"/><path d="M8.5 11h7"/><rect class="wds-swatch-bar" x="3" y="19" width="18" height="3" rx="1" stroke="none"/>'),highlight:E('<path d="m14 4 5 5-7 7H7v-5z"/><path d="M7 16l-2 2"/><rect class="wds-swatch-bar" x="3" y="19" width="18" height="3" rx="1" stroke="none"/>'),globe:E('<circle cx="12" cy="12" r="9"/><path d="M3 12h18"/><path d="M12 3a14 14 0 0 1 0 18 14 14 0 0 1 0-18"/>')},se=t=>getComputedStyle(t).direction==="rtl";let Ee=null;function kt(){Ee?.close()}function Fe(t,e,n,r){kt();const i=document.createElement("div");i.className=`wds-menu ${n}`,e.append(i);const s=()=>{const u=t.getBoundingClientRect();i.style.maxHeight="";const p=i.offsetWidth,g=i.offsetHeight,k=se(e)?u.right-p:u.left;i.style.left=`${Math.max(4,Math.min(k,window.innerWidth-p-4))}px`;const N=window.innerHeight-u.bottom-8,S=u.top-8;g<=N||N>=S?(i.style.top=`${u.bottom+4}px`,g>N&&(i.style.maxHeight=`${N}px`)):(i.style.top=`${Math.max(4,u.top-Math.min(g,S)-4)}px`,g>S&&(i.style.maxHeight=`${S}px`))},c=u=>{if(u.target instanceof Node&&i.contains(u.target))return;const p=t.getBoundingClientRect();p.bottom<0||p.top>window.innerHeight||!t.isConnected?l():s()};t.setAttribute("aria-expanded","true");const d=u=>{!i.contains(u.target)&&u.target!==t&&!t.contains(u.target)&&l()},o=u=>{u.key==="Escape"&&(u.preventDefault(),u.stopPropagation(),l(!0))};let a=!1;function l(u=!1){a||(a=!0,i.remove(),t.setAttribute("aria-expanded","false"),document.removeEventListener("mousedown",d,!0),window.removeEventListener("scroll",c,!0),window.removeEventListener("resize",c),i.removeEventListener("keydown",o),Ee?.close===l&&(Ee=null),u&&t.focus())}return document.addEventListener("mousedown",d,!0),window.addEventListener("scroll",c,!0),window.addEventListener("resize",c),i.addEventListener("keydown",o),Ee={close:l},{popup:i,place:s,close:l}}function Tn(t,e,n,r){const{popup:i,place:s,close:c}=Fe(t,e,"wds-menu-list");i.setAttribute("role","menu"),i.setAttribute("aria-label",r);for(const o of n){if(o==="|"){const l=document.createElement("div");l.className="wds-menu-sep",l.setAttribute("role","separator"),i.append(l);continue}const a=document.createElement("button");a.type="button",a.className=`wds-menu-item${o.danger?" is-danger":""}`,a.setAttribute("role","menuitem"),a.tabIndex=-1,a.innerHTML=o.icon??"",a.append(document.createTextNode(o.label)),o.enabled===!1&&(a.disabled=!0),a.addEventListener("mousedown",l=>l.preventDefault()),a.addEventListener("click",()=>{c(),o.run()}),i.append(a)}const d=()=>[...i.querySelectorAll(".wds-menu-item:not(:disabled)")];i.addEventListener("keydown",o=>{const a=d(),l=a.indexOf(document.activeElement);let u=-1;o.key==="ArrowDown"?u=(l+1)%a.length:o.key==="ArrowUp"?u=(l-1+a.length)%a.length:o.key==="Home"?u=0:o.key==="End"?u=a.length-1:o.key==="Tab"&&c(),u>=0&&(o.preventDefault(),a[u]?.focus())}),s(),d()[0]?.focus()}function Cn(t,e,n,r,i){const{popup:d,place:o,close:a}=Fe(t,e,"wds-table-picker");d.setAttribute("role","dialog"),d.setAttribute("aria-label",n);const l=document.createElement("div");l.className="wds-picker-grid",l.style.gridTemplateColumns="repeat(10, 1fr)",l.tabIndex=0,l.setAttribute("role","grid"),l.setAttribute("aria-label",n);const u=document.createElement("div");u.className="wds-picker-label",u.setAttribute("aria-live","polite");const p=[];let g=3,k=3;const N=()=>{p.forEach((S,C)=>S.classList.toggle("is-on",Math.floor(C/10)<g&&C%10<k)),u.textContent=r(g,k),l.setAttribute("aria-valuetext",u.textContent)};for(let S=0;S<8;S++)for(let C=0;C<10;C++){const R=document.createElement("span");R.className="wds-picker-cell",R.addEventListener("mouseenter",()=>{g=S+1,k=C+1,N()}),R.addEventListener("mousedown",y=>y.preventDefault()),R.addEventListener("click",()=>{a(),i(S+1,C+1)}),p.push(R),l.append(R)}l.addEventListener("keydown",S=>{const C=se(l)?-1:1,R={ArrowRight:[0,C],ArrowLeft:[0,-C],ArrowDown:[1,0],ArrowUp:[-1,0]};R[S.key]?(S.preventDefault(),g=Math.min(8,Math.max(1,g+R[S.key][0])),k=Math.min(10,Math.max(1,k+R[S.key][1])),N()):S.key==="Enter"||S.key===" "?(S.preventDefault(),a(),i(g,k)):S.key==="Tab"&&a()}),d.append(l,u),N(),o(),l.focus()}function Dn(t,e,n){const{popup:r,place:i,close:s}=Fe(t,e,"wds-color-picker");r.setAttribute("role","dialog"),r.setAttribute("aria-label",n.label);const c=a=>{s(),n.onPick(a)},d=document.createElement("button");d.type="button",d.className="wds-menu-item wds-color-remove",d.innerHTML='<span class="wds-swatch is-none" aria-hidden="true"></span>',d.append(document.createTextNode(n.removeLabel)),d.addEventListener("mousedown",a=>a.preventDefault()),d.addEventListener("click",()=>c(null));const o=document.createElement("div");o.className="wds-swatches",o.style.gridTemplateColumns=`repeat(${n.columns}, 1fr)`;for(const a of n.swatches){const l=document.createElement("button");l.type="button",l.className="wds-swatch",l.style.background=a.color,l.title=a.label,l.setAttribute("aria-label",a.label);const u=a.color===n.current;l.setAttribute("aria-pressed",String(u)),u&&l.classList.add("is-current"),l.addEventListener("mousedown",p=>p.preventDefault()),l.addEventListener("click",()=>c(a.color)),o.append(l)}r.append(d,o),r.addEventListener("keydown",a=>{const l=[d,...o.querySelectorAll(".wds-swatch")],u=l.indexOf(document.activeElement);if(u<0)return;const p=n.columns;let g=-1;const k=se(r)?"ArrowLeft":"ArrowRight",N=se(r)?"ArrowRight":"ArrowLeft";a.key===k?g=Math.min(l.length-1,u+1):a.key===N?g=Math.max(0,u-1):a.key==="ArrowDown"?g=u===0?1:Math.min(l.length-1,u+p):a.key==="ArrowUp"?g=u<=p?0:u-p:a.key==="Tab"&&s(),g>=0&&(a.preventDefault(),l[g].focus())}),i(),(o.querySelector(".is-current")??o.querySelector(".wds-swatch"))?.focus()}const P=t=>e=>e.exec(t),Ue=t=>se(t.root)?"right":"left",Ae=t=>{const e=`align${t[0].toUpperCase()}${t.slice(1)}`;return{type:"button",label:e,icon:L[e],run:n=>n.exec(yt(t,Ue(n))),active:(n,r)=>fn(n,Ue(r))===t,enabled:(n,r)=>yt(t,Ue(r))(n)}},Mt={undo:{type:"button",label:"undo",icon:L.undo,shortcut:"Mod+Z",run:t=>t.undo(),enabled:t=>Y.undoDepth(t)>0},redo:{type:"button",label:"redo",icon:L.redo,shortcut:"Mod+Y",run:t=>t.redo(),enabled:t=>Y.redoDepth(t)>0},blocks:{type:"blocks"},bold:{type:"button",label:"bold",icon:L.bold,shortcut:"Mod+B",run:P(W("strong")),active:t=>me(t,f.marks.strong)},italic:{type:"button",label:"italic",icon:L.italic,shortcut:"Mod+I",run:P(W("em")),active:t=>me(t,f.marks.em)},underline:{type:"button",label:"underline",icon:L.underline,shortcut:"Mod+U",run:P(W("underline")),active:t=>me(t,f.marks.underline)},strike:{type:"button",label:"strike",icon:L.strike,run:P(W("strike")),active:t=>me(t,f.marks.strike)},textColor:{type:"button",label:"textColor",icon:L.textColor,popup:!0,run:(t,e)=>t.openColorPicker("textColor",e),swatch:t=>Be(t,"textColor")},highlight:{type:"button",label:"highlight",icon:L.highlight,popup:!0,run:(t,e)=>t.openColorPicker("highlight",e),swatch:t=>Be(t,"highlight")},code:{type:"button",label:"code",icon:L.code,run:P(W("code")),active:t=>me(t,f.marks.code)},link:{type:"button",label:"link",icon:L.link,shortcut:"Mod+K",run:t=>t.openLinkDialog(),active:t=>!!ze(t)},image:{type:"button",label:"image",icon:L.image,run:t=>t.openImageDialog(),active:t=>!!Pe(t)},file:{type:"button",label:"file",icon:L.file,run:t=>t.openFileManager("file"),available:t=>t.hasFileManager()},table:{type:"button",label:"table",icon:L.table,popup:!0,run:(t,e)=>t.openTableMenu(e),active:t=>I.isInTable(t)},blockquote:{type:"button",label:"blockquote",icon:L.blockquote,run:P(hn()),active:t=>gt(t,f.nodes.blockquote)},bulletList:{type:"button",label:"bulletList",icon:L.bulletList,run:P(wt(f.nodes.bullet_list)),active:t=>bt(t)===f.nodes.bullet_list},orderedList:{type:"button",label:"orderedList",icon:L.orderedList,run:P(wt(f.nodes.ordered_list)),active:t=>bt(t)===f.nodes.ordered_list},outdent:{type:"button",label:"outdent",icon:L.outdent,run:P($e),enabled:t=>$e(t)},indent:{type:"button",label:"indent",icon:L.indent,run:P(He),enabled:t=>He(t)},alignLeft:Ae("left"),alignCenter:Ae("center"),alignRight:Ae("right"),alignJustify:Ae("justify"),hr:{type:"button",label:"hr",icon:L.hr,run:P(pn)},clear:{type:"button",label:"clear",icon:L.clear,run:P(mn)},pasteText:{type:"button",label:"pasteText",icon:L.pasteText,run:t=>t.togglePlainPaste(),active:(t,e)=>e.isPlainPaste()},source:{type:"button",label:"source",icon:L.source,run:t=>t.toggleSource(),active:(t,e)=>e.isSourceMode(),inSource:!0},fullscreen:{type:"button",label:"fullscreen",icon:L.fullscreen,run:t=>t.toggleFullscreen(),active:(t,e)=>e.isFullscreen(),inSource:!0}},Lt=["undo","redo","|","blocks","|","bold","italic","underline","strike","code","textColor","highlight","|","link","image","file","table","blockquote","bulletList","orderedList","outdent","indent","|","alignLeft","alignCenter","alignRight","alignJustify","|","hr","clear","pasteText","|","source","fullscreen"],Nn=[["paragraph","paragraph"],["heading1","heading1"],["heading2","heading2"],["heading3","heading3"],["heading4","heading4"],["codeBlock","codeBlock"]],In=typeof navigator<"u"&&/Mac|iP(hone|ad|od)/.test(navigator.platform||navigator.userAgent),On=t=>t.replace("Mod",In?"⌘":"Ctrl");function Rn(t,e,n){const r=document.createElement("div");r.className="wds-toolbar",r.setAttribute("role","toolbar"),r.setAttribute("aria-label",n.toolbarLabel);const i=[];let s=document.createElement("div");s.className="wds-group",r.append(s);for(const d of e){if(d==="|"){s.childElementCount&&(s=document.createElement("div"),s.className="wds-group",r.append(s));continue}const o=Mt[d];if(!o){console.warn(`[WDS Editor] Unknown toolbar item "${d}".`);continue}if(o.type==="blocks"){const u=document.createElement("select");u.className="wds-select",u.setAttribute("aria-label",n.blockType),u.title=n.blockType;for(const[g,k]of Nn){const N=document.createElement("option");N.value=g,N.textContent=n[k],u.append(N)}const p=document.createElement("option");p.value="",p.textContent="—",p.hidden=!0,u.append(p),u.addEventListener("change",()=>{u.value&&t.exec(un(u.value)),t.focus()}),s.append(u),i.push(g=>{u.value=dn(g)??"",u.disabled=t.isSourceMode()||t.isReadOnly()});continue}if(o.available&&!o.available(t))continue;const a=document.createElement("button");a.type="button",a.className="wds-button-tool",a.innerHTML=o.icon;const l=n[o.label];a.setAttribute("aria-label",l),a.title=o.shortcut?`${l} (${On(o.shortcut)})`:l,a.dataset.item=d,o.popup&&(a.setAttribute("aria-haspopup","true"),a.setAttribute("aria-expanded","false")),a.addEventListener("mousedown",u=>u.preventDefault()),a.addEventListener("click",()=>{a.disabled||o.run(t,a)}),s.append(a),i.push(u=>{const p=t.isSourceMode()&&!o.inSource||t.isReadOnly()&&!o.inSource;if(a.disabled=p||(o.enabled?!o.enabled(u,t):!1),o.swatch){const g=p?null:o.swatch(u);g?a.style.setProperty("--wds-swatch",g):a.style.removeProperty("--wds-swatch")}if(o.active){const g=!p&&o.active(u,t);a.classList.toggle("is-active",g),a.setAttribute("aria-pressed",String(g))}})}return r.addEventListener("keydown",d=>{if(d.key!=="ArrowRight"&&d.key!=="ArrowLeft"&&d.key!=="Home"&&d.key!=="End"||d.target.tagName==="SELECT"&&(d.key==="Home"||d.key==="End"))return;const o=[...r.querySelectorAll("button:not([disabled]), select:not([disabled])")],a=o.indexOf(document.activeElement);if(a<0)return;d.preventDefault();const l=d.key==="Home"?0:d.key==="End"?o.length-1:(a+(d.key==="ArrowRight"!==se(r)?1:-1)+o.length)%o.length;o.forEach(u=>u.tabIndex=-1),o[l].tabIndex=0,o[l].focus()}),{element:r,update:d=>{i.forEach(a=>a(d));const o=[...r.querySelectorAll("button, select")];if(!o.some(a=>a.tabIndex===0&&!a.disabled)){o.forEach(l=>l.tabIndex=-1);const a=o.find(l=>!l.disabled);a&&(a.tabIndex=0)}}}}function xt(t,e,n,r){const i=document.createElement("span");i.className="wds-image";const s=document.createElement("img");s.draggable=!1;const c=document.createElement("span");c.className="wds-resize-handle",c.title=r.resizeLabel,c.setAttribute("aria-hidden","true"),i.append(s,c);const d=()=>{const l=e();l!==void 0&&t.dispatch(t.state.tr.setSelection(H.NodeSelection.create(t.state.doc,l)))};let o=!1;return c.addEventListener("pointerdown",l=>{if(!t.editable)return;l.preventDefault(),l.stopPropagation(),d(),o=!0;try{c.setPointerCapture(l.pointerId)}catch{}const u=l.clientX,p=s.getBoundingClientRect().width,g=Math.max(40,t.dom.clientWidth-8);let k=p;const N=C=>{k=Math.round(Math.min(g,Math.max(40,p+C.clientX-u))),s.style.width=`${k}px`,s.style.height="auto",i.dataset.size=`${k}px`},S=()=>{o=!1,window.removeEventListener("pointermove",N),window.removeEventListener("pointerup",S),window.removeEventListener("pointercancel",S),delete i.dataset.size,s.style.width="",s.style.height="";const C=e();if(C===void 0||Math.abs(k-p)<2)return;const R=n(),y=t.state.tr.setNodeMarkup(C,void 0,{...R.attrs,width:k,height:null});t.dispatch(y.setSelection(H.NodeSelection.create(y.doc,C)))};window.addEventListener("pointermove",N),window.addEventListener("pointerup",S),window.addEventListener("pointercancel",S)}),i.addEventListener("dblclick",l=>{if(!t.editable)return;l.preventDefault(),d();const u=e();u!==void 0&&r.onEdit(u)}),{box:i,img:s,handle:c,select:d,render:l=>{const u=Ie(l.attrs,!1);for(const p of["src","alt","title","width","height"])u[p]!==void 0?s.setAttribute(p,u[p]):s.removeAttribute(p)},isResizing:()=>o}}const Et=(t,e)=>{t.classList.remove("wds-align-left","wds-align-center","wds-align-right"),e&&t.classList.add(`wds-align-${e}`)};class Hn{constructor(e,n,r,i){this.node=e,this.parts=xt(n,r,()=>this.node,i),this.dom=this.parts.box,this.render()}render(){this.parts.render(this.node),Et(this.dom,this.node.attrs.align)}update(e){return e.type!==this.node.type?!1:(this.node=e,this.render(),!0)}stopEvent(e){return e.target===this.parts.handle||this.parts.isResizing()}ignoreMutation(){return!0}}class $n{constructor(e,n,r,i){this.node=e,this.dom=document.createElement("figure"),this.dom.className="wds-figure",this.parts=xt(n,r,()=>this.node,i),this.parts.box.contentEditable="false",this.parts.box.addEventListener("mousedown",s=>{s.target===this.parts.handle||s.detail>1||(s.preventDefault(),this.parts.select(),n.focus())}),this.contentDOM=document.createElement("figcaption"),this.contentDOM.dataset.placeholder=i.captionPlaceholder,this.dom.append(this.parts.box,this.contentDOM),this.render()}render(){this.parts.render(this.node),Et(this.dom,this.node.attrs.align),this.dom.classList.toggle("is-empty",this.node.content.size===0)}update(e){return e.type!==this.node.type?!1:(this.node=e,this.render(),!0)}stopEvent(e){return this.parts.box.contains(e.target)&&!e.type.startsWith("drag")}ignoreMutation(e){return!this.contentDOM.contains(e.target)}}const ge={undo:"Undo",redo:"Redo",blockType:"Text style",paragraph:"Paragraph",heading1:"Heading 1",heading2:"Heading 2",heading3:"Heading 3",heading4:"Heading 4",codeBlock:"Code block",bold:"Bold",italic:"Italic",underline:"Underline",strike:"Strikethrough",code:"Inline code",link:"Insert link",blockquote:"Quote",bulletList:"Bulleted list",orderedList:"Numbered list",indent:"Increase indent",outdent:"Decrease indent",alignLeft:"Align left",alignCenter:"Align center",alignRight:"Align right",alignJustify:"Justify",hr:"Horizontal line",clear:"Clear formatting",source:"Source code",fullscreen:"Fullscreen",linkUrl:"URL",linkText:"Text to display",linkTitle:"Title",linkNewTab:"Open in a new tab",linkInvalid:"Enter a valid web address, email address or relative URL.",save:"Save",cancel:"Cancel",remove:"Remove link",close:"Close",words:"words",characters:"characters",poweredBy:"Powered by",editorLabel:"Rich text editor",toolbarLabel:"Editor toolbar",sourceLabel:"HTML source",image:"Insert image",file:"Insert file",imageEdit:"Image",imageUrl:"Image URL",imageAlt:"Alternative text",imageAltHint:"Describe the image for screen readers and search engines.",imageWidth:"Width (px)",imageAlign:"Alignment",alignNone:"None",alignLeftShort:"Left",alignCenterShort:"Center",alignRightShort:"Right",imageInvalid:"Enter a valid image address (https:// or a relative URL).",insert:"Insert",fmTitle:"File manager",fmRoot:"Files",fmBreadcrumb:"Folders",fmSearch:"Search files",fmSort:"Sort",fmSortNewest:"Newest first",fmSortName:"Name",fmSortLargest:"Largest first",fmGrid:"Grid view",fmList:"List view",fmUpload:"Upload",fmDrop:"Drop files to upload",fmLoading:"Loading…",fmEmpty:"No files here yet.",fmNoResults:"No files match your search.",fmLoadMore:"Load more",fmRetry:"Try again",fmDelete:"Delete",fmDeleteConfirm:'Delete "{name}"? This cannot be undone.',fmFromUrl:"Insert from URL",fmLinkText:"Link text",fmFolder:"Folder",fmNoSelection:"Select a file to see its details.",fmNotAllowed:"{name}: this file type is not allowed here.",fmUploadFailed:"{name}: upload failed. {error}",fmListFailed:"The file list could not be loaded. {error}",fmDeleteFailed:"The file could not be deleted. {error}",fmUploading:"Uploading {name}",fmNetworkError:"Check your connection and try again.",fmInvalidResponse:"The server sent an unexpected response.",table:"Table",tableInsert:"Insert table",tableSize:"{rows} × {cols} table",rowAbove:"Insert row above",rowBelow:"Insert row below",colLeft:"Insert column left",colRight:"Insert column right",deleteRow:"Delete row",deleteCol:"Delete column",headerRow:"Toggle header row",headerCol:"Toggle header column",mergeCells:"Merge cells",splitCell:"Split cell",deleteTable:"Delete table",caption:"Show caption",captionPlaceholder:"Write a caption…",resizeImage:"Drag to resize",pasteText:"Paste as plain text",textColor:"Text color",highlight:"Highlight",removeColor:"Default color",removeHighlight:"No highlight",colorRed:"Red",colorOrange:"Orange",colorAmber:"Amber",colorYellow:"Yellow",colorGreen:"Green",colorTeal:"Teal",colorBlue:"Blue",colorPurple:"Purple",colorPink:"Pink",colorSlate:"Slate",colorGray:"Gray"},At={undo:"Geri al",redo:"Yinele",blockType:"Metin stili",paragraph:"Paragraf",heading1:"Başlık 1",heading2:"Başlık 2",heading3:"Başlık 3",heading4:"Başlık 4",codeBlock:"Kod bloğu",bold:"Kalın",italic:"İtalik",underline:"Altı çizili",strike:"Üstü çizili",code:"Satır içi kod",link:"Bağlantı ekle",blockquote:"Alıntı",bulletList:"Madde işaretli liste",orderedList:"Numaralı liste",indent:"Girintiyi artır",outdent:"Girintiyi azalt",alignLeft:"Sola hizala",alignCenter:"Ortala",alignRight:"Sağa hizala",alignJustify:"İki yana yasla",hr:"Yatay çizgi",clear:"Biçimi temizle",source:"Kaynak kodu",fullscreen:"Tam ekran",linkUrl:"Adres (URL)",linkText:"Görünen metin",linkTitle:"Başlık",linkNewTab:"Yeni sekmede aç",linkInvalid:"Geçerli bir web adresi, e-posta adresi ya da göreli adres girin.",save:"Kaydet",cancel:"Vazgeç",remove:"Bağlantıyı kaldır",close:"Kapat",words:"kelime",characters:"karakter",poweredBy:"Destekleyen:",editorLabel:"Zengin metin editörü",toolbarLabel:"Editör araç çubuğu",sourceLabel:"HTML kaynağı",image:"Görsel ekle",file:"Dosya ekle",imageEdit:"Görsel",imageUrl:"Görsel adresi",imageAlt:"Alternatif metin",imageAltHint:"Ekran okuyucular ve arama motorları için görseli kısaca anlatın.",imageWidth:"Genişlik (px)",imageAlign:"Hizalama",alignNone:"Yok",alignLeftShort:"Sol",alignCenterShort:"Orta",alignRightShort:"Sağ",imageInvalid:"Geçerli bir görsel adresi girin (https:// ya da göreli adres).",insert:"Ekle",fmTitle:"Dosya yöneticisi",fmRoot:"Dosyalar",fmBreadcrumb:"Klasörler",fmSearch:"Dosyalarda ara",fmSort:"Sırala",fmSortNewest:"En yeni",fmSortName:"Ada göre",fmSortLargest:"En büyük",fmGrid:"Izgara görünümü",fmList:"Liste görünümü",fmUpload:"Yükle",fmDrop:"Yüklemek için dosyaları bırakın",fmLoading:"Yükleniyor…",fmEmpty:"Burada henüz dosya yok.",fmNoResults:"Aramanızla eşleşen dosya yok.",fmLoadMore:"Daha fazla yükle",fmRetry:"Tekrar dene",fmDelete:"Sil",fmDeleteConfirm:'"{name}" silinsin mi? Bu işlem geri alınamaz.',fmFromUrl:"Adresten ekle",fmLinkText:"Bağlantı metni",fmFolder:"Klasör",fmNoSelection:"Ayrıntıları görmek için bir dosya seçin.",fmNotAllowed:"{name}: bu dosya türüne burada izin verilmiyor.",fmUploadFailed:"{name}: yüklenemedi. {error}",fmListFailed:"Dosya listesi yüklenemedi. {error}",fmDeleteFailed:"Dosya silinemedi. {error}",fmUploading:"{name} yükleniyor",fmNetworkError:"Bağlantınızı kontrol edip tekrar deneyin.",fmInvalidResponse:"Sunucu beklenmeyen bir yanıt gönderdi.",table:"Tablo",tableInsert:"Tablo ekle",tableSize:"{rows} × {cols} tablo",rowAbove:"Üste satır ekle",rowBelow:"Alta satır ekle",colLeft:"Sola sütun ekle",colRight:"Sağa sütun ekle",deleteRow:"Satırı sil",deleteCol:"Sütunu sil",headerRow:"Başlık satırı aç/kapat",headerCol:"Başlık sütunu aç/kapat",mergeCells:"Hücreleri birleştir",splitCell:"Hücreyi böl",deleteTable:"Tabloyu sil",caption:"Açıklama göster",captionPlaceholder:"Açıklama yazın…",resizeImage:"Boyutlandırmak için sürükleyin",pasteText:"Düz metin olarak yapıştır",textColor:"Yazı rengi",highlight:"Vurgu",removeColor:"Varsayılan renk",removeHighlight:"Vurgu yok",colorRed:"Kırmızı",colorOrange:"Turuncu",colorAmber:"Kehribar",colorYellow:"Sarı",colorGreen:"Yeşil",colorTeal:"Camgöbeği",colorBlue:"Mavi",colorPurple:"Mor",colorPink:"Pembe",colorSlate:"Arduvaz",colorGray:"Gri"},be={en:ge,tr:At};function _e(t,e){be[t.toLowerCase()]={...ge,...be[t.toLowerCase()],...e}}function St(t){return globalThis.WDSEditorLang?.[t]}function Tt(t){return!be[t]&&St(t)&&_e(t,St(t)),be[t]}function Ct(t){const e=(t||(typeof navigator<"u"?navigator.language:"en")||"en").toLowerCase();if(Tt(e))return e;const n=e.split("-")[0];return Tt(n)?n:"en"}function zn(t){return t&&typeof t=="object"?{...ge,...t}:be[Ct(t)]??ge}const Pn=new Set(["ar","he","fa","ur","ps","yi","dv","ckb"]);function Bn(t){return Pn.has(t.toLowerCase().split("-")[0])}function Q(t,e){return t.replace(/\{(\w+)\}/g,(n,r)=>e[r]??n)}let Fn=0;function Dt(t,e){const n=`wds-dlg-${++Fn}`,r=document.createElement("dialog");r.className="wds-dialog",r.setAttribute("aria-labelledby",`${n}-title`);const i=document.createElement("form");i.method="dialog",i.noValidate=!0;const s=document.createElement("div");s.className="wds-dialog-header";const c=document.createElement("h2");c.id=`${n}-title`,c.textContent=e.title;const d=document.createElement("button");d.type="button",d.className="wds-icon-button",d.setAttribute("aria-label",e.closeLabel),d.innerHTML=L.close,s.append(c,d);const o=document.createElement("div");o.className="wds-dialog-body";const a=new Map;for(const y of e.fields){if(y.type==="select"){const T=document.createElement("select");T.id=`${n}-${y.name}`,T.name=y.name,T.className="wds-input";for(const z of y.options??[]){const ee=document.createElement("option");ee.value=z.value,ee.textContent=z.label,T.append(ee)}T.value=typeof y.value=="string"?y.value:"";const $=document.createElement("label");$.className="wds-label",$.htmlFor=T.id,$.textContent=y.label,o.append($,T),a.set(y.name,T);continue}const x=document.createElement("input");if(x.id=`${n}-${y.name}`,x.name=y.name,y.type==="checkbox"){x.type="checkbox",x.checked=!!y.value;const T=document.createElement("label");T.className="wds-check",T.htmlFor=x.id,T.append(x,document.createTextNode(y.label)),o.append(T)}else{x.type="text",y.type==="url"&&(x.inputMode="url"),y.type==="number"&&(x.inputMode="numeric"),x.className="wds-input",x.value=typeof y.value=="string"?y.value:"",x.autocomplete="off",x.spellcheck=!1,y.placeholder&&(x.placeholder=y.placeholder);const T=document.createElement("label");if(T.className="wds-label",T.htmlFor=x.id,T.textContent=y.label,o.append(T,x),y.hint){const $=document.createElement("p");$.className="wds-hint",$.id=`${x.id}-hint`,$.textContent=y.hint,x.setAttribute("aria-describedby",$.id),o.append($)}}a.set(y.name,x)}const l=document.createElement("p");l.className="wds-dialog-error",l.setAttribute("role","alert"),l.hidden=!0,o.append(l);const u=document.createElement("div");if(u.className="wds-dialog-footer",e.extraAction){const y=document.createElement("button");y.type="button",y.className="wds-button wds-button-danger",y.textContent=e.extraAction.label,y.addEventListener("click",()=>{e.extraAction.onClick(),C()}),u.append(y)}const p=document.createElement("span");p.className="wds-spacer";const g=document.createElement("button");g.type="button",g.className="wds-button",g.textContent=e.cancelLabel;const k=document.createElement("button");k.type="submit",k.className="wds-button wds-button-primary",k.textContent=e.submitLabel,u.append(p,g,k),i.append(s,o,u),r.append(i),t.append(r);const N=()=>{const y={};return a.forEach((x,T)=>y[T]=x instanceof HTMLInputElement&&x.type==="checkbox"?x.checked:x.value),y};let S=!1;function C(){S||(S=!0,r.open&&r.close(),r.remove(),e.onClose?.())}i.addEventListener("submit",y=>{y.preventDefault();const x=N(),T=e.validate?.(x)??null;if(T){l.textContent=T,l.hidden=!1,[...a.values()][0]?.focus();return}e.onSubmit(x),C()}),g.addEventListener("click",C),d.addEventListener("click",C),r.addEventListener("close",C),r.addEventListener("click",y=>{y.target===r&&C()}),r.showModal();const R=[...a.values()].find(y=>y instanceof HTMLInputElement&&y.type!=="checkbox");return R?.focus(),R?.select(),C}const Z=t=>typeof t=="string"&&t.trim()?t:void 0,We=t=>typeof t=="number"&&Number.isFinite(t)&&t>=0?t:void 0;function Nt(t){if(!t||typeof t!="object")return null;const e=t,n=V(Z(e.url)),r=Z(e.name);if(!n||!r)return null;const i={url:n,name:r},s=We(e.size),c=We(e.width),d=We(e.height);s!==void 0&&(i.size=s),c!==void 0&&(i.width=c),d!==void 0&&(i.height=d),Z(e.type)&&(i.type=e.type.toLowerCase());const o=V(Z(e.thumb));return o&&(i.thumb=o),Z(e.modified)&&!Number.isNaN(Date.parse(e.modified))&&(i.modified=e.modified),i}function It(t,e="/"){const n=Array.isArray(t)?{files:t}:t&&typeof t=="object"?t:{},r=(Array.isArray(n.files)?n.files:[]).map(Nt).filter(s=>!!s),i=(Array.isArray(n.folders)?n.folders:[]).map(s=>s&&typeof s=="object"?s:{}).filter(s=>Z(s.name)&&Z(s.path)).map(s=>({name:s.name,path:qe(s.path)}));return{path:qe(Z(n.path)??e),folders:i,files:r,hasMore:n.hasMore===!0,serverSearch:typeof n.q=="string"}}function qe(t){return"/"+t.split("/").filter(n=>n&&n!=="."&&n!=="..").join("/")}const Un=/\.(jpe?g|png|gif|webp|avif|svg|bmp|ico)$/i,_n={jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",gif:"image/gif",webp:"image/webp",avif:"image/avif",svg:"image/svg+xml",bmp:"image/bmp",ico:"image/x-icon",pdf:"application/pdf",zip:"application/zip",txt:"text/plain",csv:"text/csv",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",xls:"application/vnd.ms-excel",xlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",mp4:"video/mp4",mp3:"audio/mpeg"},Ot=t=>(/\.([a-z0-9]+)$/i.exec(t)?.[1]??"").toLowerCase();function Rt(t){return t.type||_n[Ot(t.name)]||""}function le(t){const e=Rt(t);return e?e.startsWith("image/"):Un.test(t.url??t.name)}function Ge(t,e){if(!e||!e.trim())return!0;const n=Rt(t),r="."+Ot(t.name);return e.split(",").some(i=>{const s=i.trim().toLowerCase();return s?s.startsWith(".")?r===s:s.endsWith("/*")?n.startsWith(s.slice(0,-1)):n===s:!1})}function Ht(t){if(t===void 0)return"";if(t<1024)return`${t} B`;const e=["KB","MB","GB"];let n=t/1024,r=0;for(;n>=1024&&r<e.length-1;)n/=1024,r++;return`${n<10?n.toFixed(1):Math.round(n)} ${e[r]}`}class B extends Error{constructor(e,n){super(e),this.code=n}}async function $t(t){try{const e=await t.clone().json();if(e&&typeof e.error=="string")return e.error}catch{}return`HTTP ${t.status}`}function Wn(t,e){const n=new URL(t,document.baseURI);for(const[r,i]of Object.entries(e))i&&n.searchParams.set(r,i);return n.href}class qn{constructor(e){this.options=e}get canUpload(){return!!this.options.uploadUrl}get canDelete(){return!!this.options.deleteUrl}init(e={}){return{...e,credentials:this.options.withCredentials?"include":"same-origin",headers:{Accept:"application/json",...this.options.headers,...e.headers}}}async list(e,n,r,i){const s=Wn(this.options.listUrl,{path:e,q:n,page:r>1?String(r):""});let c;try{c=await fetch(s,{...this.init(),signal:i})}catch(o){throw o.name==="AbortError"?o:new B(o.message||"Network error","network")}if(!c.ok)throw new B(await $t(c));let d;try{d=await c.json()}catch{throw new B("Invalid JSON","response")}return It(d,e)}upload(e,n,r){const{uploadUrl:i,headers:s={},withCredentials:c}=this.options;return i?new Promise((d,o)=>{const a=new XMLHttpRequest;a.open("POST",new URL(i,document.baseURI).href),a.withCredentials=!!c,a.setRequestHeader("Accept","application/json");for(const[u,p]of Object.entries(s))a.setRequestHeader(u,p);a.upload.onprogress=u=>u.lengthComputable&&r?.(u.loaded/u.total),a.onerror=()=>o(new B("Network error","network")),a.onload=()=>{let u=null;try{u=JSON.parse(a.responseText)}catch{}if(a.status<200||a.status>=300){o(new B(typeof u?.error=="string"?u.error:`HTTP ${a.status}`));return}const p=Nt(u?.file);p?d(p):o(new B("Invalid upload response","response"))};const l=new FormData;l.append("file",e,e.name),l.append("path",n),a.send(l)}):Promise.reject(new B("Upload is not configured"))}async remove(e){const{deleteUrl:n}=this.options;if(!n)throw new B("Delete is not configured");let r;try{r=await fetch(new URL(n,document.baseURI).href,this.init({method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({url:e})}))}catch(i){throw new B(i.message||"Network error","network")}if(!r.ok)throw new B(await $t(r))}}function je(t,e){return t instanceof B&&t.code==="network"?e.fmNetworkError:t instanceof B&&t.code==="response"?e.fmInvalidResponse:t?.message??""}const b=(t,e,n)=>{const r=document.createElement(t);return e&&(r.className=e),n!==void 0&&(r.textContent=n),r},Ve=(t,e,n="wds-icon-button")=>{const r=b("button",n);return r.type="button",r.innerHTML=t,r.setAttribute("aria-label",e),r.title=e,r},Gn=[["","alignNone"],["left","alignLeftShort"],["center","alignCenterShort"],["right","alignRightShort"]];class jn{constructor(e,n,r){this.host=e,this.api=n,this.t=r,this.path="/",this.view="grid",this.sort="newest"}open(e){const n=this.t,r=e.accept??"";let i=[],s=[],c=1,d=!1,o=!1,a="",l=null,u=null,p=0,g=!1;const k=b("dialog","wds-dialog wds-fm");k.setAttribute("aria-labelledby","wds-fm-title");const N=b("div","wds-dialog-header"),S=b("h2",void 0,n.fmTitle);S.id="wds-fm-title";const C=Ve(L.close,n.close);N.append(S,C);const R=b("div","wds-fm-bar"),y=b("nav","wds-fm-crumbs");y.setAttribute("aria-label",n.fmBreadcrumb);const x=b("input","wds-input wds-fm-search");x.type="search",x.placeholder=n.fmSearch,x.setAttribute("aria-label",n.fmSearch);const T=b("select","wds-input wds-fm-sort");T.setAttribute("aria-label",n.fmSort),T.title=n.fmSort;for(const[h,m]of[["newest","fmSortNewest"],["name","fmSortName"],["largest","fmSortLargest"]]){const M=b("option",void 0,n[m]);M.value=h,T.append(M)}T.value=this.sort;const $=Ve(this.view==="grid"?L.list:L.grid,this.view==="grid"?n.fmList:n.fmGrid),z=b("input");z.type="file",z.multiple=!0,z.hidden=!0,r&&(z.accept=r);const ee=b("button","wds-button wds-button-primary wds-fm-upload");ee.type="button",ee.innerHTML=`${L.upload}<span>${Ke(n.fmUpload)}</span>`;const Je=b("div","wds-fm-tools");Je.append(x,T,$),this.api.canUpload&&Je.append(ee,z),R.append(y,Je);const Pt=b("div","wds-fm-main"),K=b("div","wds-fm-browser"),Xe=b("div","wds-fm-uploads"),q=b("ul",`wds-fm-items is-${this.view}`);q.setAttribute("aria-label",n.fmTitle);const O=b("p","wds-fm-status");O.setAttribute("role","status");const ue=b("button","wds-button",n.fmRetry);ue.type="button",ue.hidden=!0;const he=b("button","wds-button wds-fm-more",n.fmLoadMore);he.type="button",he.hidden=!0;const Bt=b("div","wds-fm-drop",n.fmDrop);Bt.setAttribute("aria-hidden","true"),K.append(Xe,q,O,ue,he,Bt);const G=b("aside","wds-fm-details");G.setAttribute("aria-label",n.imageEdit),Pt.append(K,G);const Qe=b("div","wds-dialog-footer");if(e.onFromUrl){const h=b("button","wds-button wds-fm-fromurl");h.type="button",h.innerHTML=`${L.globe}<span>${Ke(n.fmFromUrl)}</span>`,h.addEventListener("click",()=>{ie(),e.onFromUrl()}),Qe.append(h)}const Ze=b("button","wds-button",n.cancel);Ze.type="button";const we=b("button","wds-button wds-button-primary",n.insert);we.type="button",we.disabled=!0,Qe.append(b("span","wds-spacer"),Ze,we),k.append(N,R,Pt,Qe),this.host.append(k);let ye=null,j=null,ve=null,ne=null,ke=null;const Se=(h,m,M,w)=>{m.id=M;const A=b("label","wds-label",h);if(A.htmlFor=M,G.append(A,m),w){const v=b("p","wds-hint",w);v.id=`${M}-hint`,m.setAttribute("aria-describedby",v.id),G.append(v)}},Te=()=>{if(G.replaceChildren(),ye=j=ke=ne=null,ve=null,we.disabled=!l,!l){G.append(b("p","wds-fm-placeholder",n.fmNoSelection));return}const h=l,m=b("div","wds-fm-preview"),M=b("p","wds-fm-filename",h.name),w=b("p","wds-fm-facts"),A=()=>[h.width&&h.height?`${h.width} × ${h.height}`:"",Ht(h.size),h.modified?new Date(h.modified).toLocaleDateString():""].filter(Boolean).join(" · ");if(w.textContent=A(),le(h)){const v=b("img");v.alt="",!h.thumb&&!(h.width&&h.height)&&v.addEventListener("load",()=>{!v.naturalWidth||l!==h||(h.width=v.naturalWidth,h.height=v.naturalHeight,w.textContent=A(),j&&!j.placeholder&&(j.placeholder=String(h.width)))},{once:!0}),v.src=h.thumb??h.url,m.append(v)}else m.innerHTML=L.file;if(G.append(m,M,w),e.mode==="image"&&le(h)){ye=b("input","wds-input"),ye.value=h.name.replace(/\.[a-z0-9]+$/i,"").replace(/[-_]+/g," "),Se(n.imageAlt,ye,"wds-fm-alt",n.imageAltHint),j=b("input","wds-input"),j.inputMode="numeric",j.placeholder=h.width?String(h.width):"",Se(n.imageWidth,j,"wds-fm-width"),ve=b("select","wds-input");for(const[F,U]of Gn){const fe=b("option",void 0,n[U]);fe.value=F,ve.append(fe)}Se(n.imageAlign,ve,"wds-fm-align"),ne=b("input"),ne.type="checkbox",ne.id="wds-fm-caption";const v=b("label","wds-check");v.htmlFor=ne.id,v.append(ne,document.createTextNode(n.caption)),G.append(v)}else ke=b("input","wds-input"),ke.value=h.name,Se(n.fmLinkText,ke,"wds-fm-text");if(this.api.canDelete){const v=b("button","wds-button wds-button-danger wds-fm-delete");v.type="button",v.innerHTML=`${L.trash}<span>${Ke(n.fmDelete)}</span>`,v.addEventListener("click",()=>Xn(h)),G.append(v)}},Jn=()=>{const h=a.trim().toLocaleLowerCase(),m=i.filter(w=>Ge(w,r)&&(o||!h||w.name.toLocaleLowerCase().includes(h))),M=w=>w.modified?Date.parse(w.modified):-1/0;return this.sort==="name"?m.sort((w,A)=>w.name.localeCompare(A.name,void 0,{numeric:!0,sensitivity:"base"})):this.sort==="largest"?m.sort((w,A)=>(A.size??-1)-(w.size??-1)):m.sort((w,A)=>M(A)-M(w)),m},et=()=>{y.replaceChildren();const h=this.path.split("/").filter(Boolean),m=[[n.fmRoot,"/"],...h.map((M,w)=>[M,"/"+h.slice(0,w+1).join("/")])];m.forEach(([M,w],A)=>{if(A&&y.append(b("span","wds-fm-sep","/")),A===m.length-1){const v=b("span","wds-fm-crumb is-current",M);v.setAttribute("aria-current","location"),y.append(v)}else{const v=b("button","wds-fm-crumb",M);v.type="button",v.addEventListener("click",()=>_t(w)),y.append(v)}})},re=()=>{q.className=`wds-fm-items is-${this.view}`,q.replaceChildren();const h=!a.trim();if(h)for(const w of s){const A=Ut(L.folder,w.name,n.fmFolder,!0);A.addEventListener("click",()=>_t(w.path)),q.append(Ft(A))}const m=Jn();for(const w of m){const A=le(w)?w.thumb??w.url:null,v=Ut(A?"":L.file,w.name,[Ht(w.size),w.width&&w.height?`${w.width}×${w.height}`:""].filter(Boolean).join(" · "),!1);if(A){const U=b("img");U.loading="lazy",U.decoding="async",U.alt="",U.src=A,v.querySelector(".wds-fm-thumb").append(U)}v.dataset.url=w.url;const F=l?.url===w.url;v.classList.toggle("is-selected",F),v.setAttribute("aria-pressed",String(F)),v.addEventListener("click",()=>tt(w)),v.addEventListener("dblclick",()=>{tt(w),nt()}),q.append(Ft(v))}const M=!m.length&&!(h&&s.length);!O.dataset.busy&&!O.dataset.error&&(O.textContent=M?a.trim()?n.fmNoResults:n.fmEmpty:""),he.hidden=!d||!!O.dataset.busy},Ft=h=>{const m=b("li");return m.append(h),m},Ut=(h,m,M,w)=>{const A=b("button",`wds-fm-item${w?" is-folder":""}`);A.type="button";const v=b("span","wds-fm-thumb");v.innerHTML=h;const F=b("span","wds-fm-name",m);F.title=m;const U=b("span","wds-fm-meta",M);return A.append(v,F,U),A},tt=h=>{l=h,q.querySelectorAll(".wds-fm-item[data-url]").forEach(m=>{const M=m.dataset.url===h.url;m.classList.toggle("is-selected",M),m.setAttribute("aria-pressed",String(M))}),Te()},Me=async h=>{u?.abort(),u=new AbortController,h&&(c=1,i=[],s=[]),O.dataset.busy="1",delete O.dataset.error,O.textContent=n.fmLoading,ue.hidden=!0,he.hidden=!0,h&&re();try{const m=await this.api.list(this.path,a.trim(),c,u.signal);if(g)return;this.path=m.path,o=m.serverSearch,d=m.hasMore,s=h?m.folders:s;const M=new Set(i.map(w=>w.url));i=[...i,...m.files.filter(w=>!M.has(w.url))],delete O.dataset.busy,O.textContent="",et(),re()}catch(m){if(m.name==="AbortError"||g)return;delete O.dataset.busy,O.dataset.error="1",O.textContent=Q(n.fmListFailed,{error:je(m,n)}),O.setAttribute("role","alert"),ue.hidden=!1}},_t=h=>{this.path=qe(h),a="",x.value="",l=null,Te(),et(),Me(!0).then(()=>q.querySelector(".wds-fm-item")?.focus())},Wt=h=>{for(const m of Array.from(h)){const M=b("div","wds-fm-upload-row"),w=b("span","wds-fm-upload-name",Q(n.fmUploading,{name:m.name}));if(!Ge(m,r)){qt(M,Q(n.fmNotAllowed,{name:m.name})),Xe.append(M);continue}const A=b("progress");A.max=1,A.value=0,M.append(w,A),Xe.append(M),this.api.upload(m,this.path,v=>A.value=v).then(v=>{g||(M.remove(),i=[v,...i.filter(F=>F.url!==v.url)],re(),tt(v),e.onUpload?.(v))}).catch(v=>{g||(M.replaceChildren(),qt(M,Q(n.fmUploadFailed,{name:m.name,error:je(v,n)})))})}},qt=(h,m)=>{h.classList.add("is-error");const M=b("span","wds-fm-upload-name",m);M.setAttribute("role","alert");const w=Ve(L.close,n.close);w.addEventListener("click",()=>h.remove()),h.append(M,w)},Xn=async h=>{if(window.confirm(Q(n.fmDeleteConfirm,{name:h.name})))try{await this.api.remove(h.url),i=i.filter(m=>m.url!==h.url),l=null,Te(),re()}catch(m){O.dataset.error="1",O.setAttribute("role","alert"),O.textContent=Q(n.fmDeleteFailed,{error:je(m,n)})}},nt=()=>{if(!l)return;const h=j?parseInt(j.value,10):NaN;e.onPick({file:l,alt:ye?.value.trim()??"",width:Number.isFinite(h)&&h>0?h:null,align:ve?.value||null,text:ke?.value.trim()||l.name,caption:!!ne?.checked}),ie()};function ie(){g||(g=!0,u?.abort(),window.clearTimeout(p),k.open&&k.close(),k.remove(),e.onClose?.())}if(C.addEventListener("click",ie),Ze.addEventListener("click",ie),we.addEventListener("click",nt),k.addEventListener("close",ie),k.addEventListener("click",h=>h.target===k&&ie()),ue.addEventListener("click",()=>{O.setAttribute("role","status"),Me(!0)}),he.addEventListener("click",()=>{c++,Me(!1)}),T.addEventListener("change",()=>{this.sort=T.value,re()}),$.addEventListener("click",()=>{this.view=this.view==="grid"?"list":"grid",$.innerHTML=this.view==="grid"?L.list:L.grid;const h=this.view==="grid"?n.fmList:n.fmGrid;$.setAttribute("aria-label",h),$.title=h,re()}),x.addEventListener("input",()=>{window.clearTimeout(p),p=window.setTimeout(()=>{a=x.value,!o&&!d?re():Me(!0)},250)}),ee.addEventListener("click",()=>z.click()),z.addEventListener("change",()=>{z.files?.length&&Wt(z.files),z.value=""}),this.api.canUpload){let h=0;K.addEventListener("dragenter",m=>{m.dataTransfer?.types.includes("Files")&&(h++,K.classList.add("is-dragging"))}),K.addEventListener("dragleave",()=>{h=Math.max(0,h-1),h||K.classList.remove("is-dragging")}),K.addEventListener("dragover",m=>{m.dataTransfer?.types.includes("Files")&&m.preventDefault()}),K.addEventListener("drop",m=>{m.preventDefault(),h=0,K.classList.remove("is-dragging"),m.dataTransfer?.files.length&&Wt(m.dataTransfer.files)})}return q.addEventListener("keydown",h=>{if(!["ArrowRight","ArrowLeft","ArrowDown","ArrowUp","Home","End"].includes(h.key))return;const M=[...q.querySelectorAll(".wds-fm-item")],w=M.indexOf(document.activeElement);if(w<0)return;h.preventDefault();const A=M[0].offsetTop,v=this.view==="list"?1:Math.max(1,M.findIndex(fe=>fe.offsetTop!==A)===-1?M.length:M.findIndex(fe=>fe.offsetTop!==A)),F={ArrowRight:1,ArrowLeft:-1,ArrowDown:v,ArrowUp:-v},U=h.key==="Home"?0:h.key==="End"?M.length-1:Math.min(M.length-1,Math.max(0,w+F[h.key]));M[U].focus()}),G.addEventListener("keydown",h=>{h.key==="Enter"&&h.target.tagName==="INPUT"&&(h.preventDefault(),nt())}),et(),Te(),k.showModal(),x.focus(),Me(!0),ie}}function Ke(t){const e=document.createElement("span");return e.textContent=t,e.innerHTML}const ce=new WeakMap,zt=t=>t===void 0?void 0:typeof t=="number"?`${t}px`:t;function Vn(t){return t===!1?[]:t===void 0||t==="default"?Lt:Array.isArray(t)?t:t.split(/\s+/).filter(Boolean)}const de=class de{constructor(e,n={}){if(this.listeners=new Map,this.notice=null,this.noticeTimer=0,this.onFormSubmit=()=>this.syncTarget(),this.onKeydown=o=>{o.key==="Escape"&&this.fullscreen&&this.toggleFullscreen()},this.sourceMode=!1,this.plainPaste=!1,this.fullscreen=!1,this.destroyed=!1,ce.has(e))throw new Error("[WDS Editor] This element already has an editor. Use WDSEditor.get() or destroy() first.");this.target=e,this.options=n,this.t=zn(n.language),this.readOnly=!!n.readOnly,this.textarea=e instanceof HTMLTextAreaElement?e:null,this.originalContent=this.textarea?this.textarea.value:e.innerHTML;const r=n.content??this.originalContent;if(this.root=document.createElement("div"),this.root.className="wds-editor",this.root.dataset.theme=n.theme??"light",typeof n.language!="object"){const o=Ct(n.language);this.root.lang=o;const a=n.dir??"auto";a==="rtl"||a==="auto"&&Bn(o)?this.root.dir="rtl":a==="ltr"&&(this.root.dir="ltr")}else n.dir&&n.dir!=="auto"&&(this.root.dir=n.dir);this.fileManager=n.fileManager?.listUrl?new jn(this.root,new qn(n.fileManager),this.t):null,this.contentWrap=document.createElement("div"),this.contentWrap.className="wds-content-wrap";const i=zt(n.height);i?(this.contentWrap.style.height=i,this.root.classList.add("wds-fixed-height")):this.contentWrap.style.minHeight=zt(n.minHeight??240),this.sourceArea=document.createElement("textarea"),this.sourceArea.className="wds-source",this.sourceArea.spellcheck=!1,this.sourceArea.dir="ltr",this.sourceArea.hidden=!0,this.sourceArea.setAttribute("aria-label",this.t.sourceLabel);const s=H.EditorState.create({schema:f,doc:Le(r),plugins:[I.tableEditing(),Ce.keymap({Tab:yn,"Shift-Tab":vn}),Mn(),Ln({link:()=>(this.openLinkDialog(),!0)}),xn(),Y.history(),En(n.placeholder??""),An(),Gt.gapCursor(),jt.dropCursor({class:"wds-dropcursor",color:!1})]}),c={onEdit:()=>this.openImageUrlDialog(),resizeLabel:this.t.resizeImage,captionPlaceholder:this.t.captionPlaceholder};this.view=new pe.EditorView(this.contentWrap,{state:s,editable:()=>!this.readOnly,attributes:{class:"wds-content",role:"textbox","aria-multiline":"true","aria-label":this.t.editorLabel},dispatchTransaction:o=>this.dispatch(o),transformPastedHTML:Kt,handlePaste:(o,a)=>{const l=a.clipboardData;if(this.plainPaste&&l){const p=l.getData("text/plain");if(p)return o.dispatch(o.state.tr.replaceSelection(Kn(p)).scrollIntoView()),!0}if(!l?.files.length||!this.canUploadInline()||l.getData("text/plain"))return!1;const u=[...l.files].filter(p=>p.type.startsWith("image/"));return u.length?(this.uploadFiles(u),!0):!1},handleDrop:(o,a,l,u)=>{const p=a.dataTransfer?.files;if(u||!p?.length||!this.canUploadInline())return!1;const g=o.posAtCoords({left:a.clientX,top:a.clientY})?.pos;return a.preventDefault(),this.uploadFiles([...p],g),!0},nodeViews:{image:(o,a,l)=>new Hn(o,a,l,c),figure:(o,a,l)=>new $n(o,a,l,c)},handleDOMEvents:{focus:()=>(this.root.classList.add("is-focused"),this.emit("focus"),!1),blur:()=>(this.root.classList.remove("is-focused"),this.emit("blur"),!1)}}),this.contentWrap.append(this.sourceArea),this.toolbar=Rn(this,Vn(n.toolbar),this.t),this.toolbar.element.childElementCount&&this.toolbar.element.firstElementChild.childElementCount&&this.root.append(this.toolbar.element),this.root.append(this.contentWrap);const d=document.createElement("div");if(d.className="wds-statusbar",this.counter=n.wordCount===!1?null:document.createElement("span"),this.counter&&(this.counter.className="wds-counter",this.counter.setAttribute("aria-live","off"),d.append(this.counter)),n.branding!==!1){const o=document.createElement("a");o.className="wds-branding",o.href="https://webdevsnippets.com/wds-editor",o.target="_blank",o.rel="noopener",o.innerHTML=`${Yn(this.t.poweredBy)} <strong>WDS Editor</strong>`,d.append(o)}d.childElementCount&&this.root.append(d),this.textarea?(this.textarea.style.display="none",this.textarea.after(this.root),this.textarea.form?.addEventListener("submit",this.onFormSubmit)):e.replaceChildren(this.root),document.addEventListener("keydown",this.onKeydown),ce.set(e,this),this.lastHtml=this.getHTML(),this.syncTarget(),this.refresh(),this.emit("init")}static init(e){const n=typeof e.selector=="string"?document.querySelector(e.selector):e.selector;if(!n)throw new Error(`[WDS Editor] No element matches "${String(e.selector)}".`);return ce.get(n)??new de(n,e)}static initAll(e){return[...document.querySelectorAll(e.selector)].map(n=>ce.get(n)??new de(n,e))}static get(e){const n=typeof e=="string"?document.querySelector(e):e;return n?ce.get(n):void 0}getHTML(){return this.sourceMode&&this.applySource(),xe(this.view.state.doc)}setHTML(e){this.sourceMode&&(this.sourceArea.value=mt(e));const n=Le(e),r=this.view.state.tr.replaceWith(0,this.view.state.doc.content.size,n.content);this.dispatch(r.setSelection(H.TextSelection.atStart(r.doc)))}insertHTML(e){const n=Le(e),r=J.Slice.maxOpen(n.content);this.dispatch(this.view.state.tr.replaceSelection(r).scrollIntoView())}getText(){const e=this.view.state.doc;return e.textBetween(0,e.content.size,`
6
3
 
7
4
  `,`
8
- `)}isEmpty(){return lt(this.view.state.doc)}focus(){this.sourceMode?this.sourceArea.focus():this.view.focus()}setReadOnly(e){this.readOnly=e,this.root.classList.toggle("is-readonly",e),this.sourceArea.readOnly=e,this.view.setProps({}),this.refresh()}isReadOnly(){return this.readOnly}exec(e){if(this.readOnly||this.sourceMode)return!1;const n=e(this.view.state,r=>this.dispatch(r),this.view);return this.view.focus(),n}undo(){this.exec(Y.undo)}redo(){this.exec(Y.redo)}isSourceMode(){return this.sourceMode}toggleSource(){this.sourceMode?(this.applySource(),this.sourceMode=!1,this.sourceArea.hidden=!0,this.view.dom.hidden=!1,this.root.classList.remove("is-source"),this.view.focus()):(this.sourceArea.value=ct(Le(this.view.state.doc)),this.sourceMode=!0,this.view.dom.hidden=!0,this.sourceArea.hidden=!1,this.root.classList.add("is-source"),this.sourceArea.focus()),this.refresh()}isFullscreen(){return this.fullscreen}toggleFullscreen(){this.fullscreen=!this.fullscreen,this.root.classList.toggle("is-fullscreen",this.fullscreen),document.documentElement.classList.toggle("wds-noscroll",this.fullscreen),this.refresh(),this.focus()}openLinkDialog(){if(this.readOnly||this.sourceMode)return;const e=this.view.state,n=Re(e),{from:r,to:i,empty:a}=e.selection,l=a?"":e.doc.textBetween(r,i," "),d=a&&!n,o=this.t;kt(this.root,{title:o.link,closeLabel:o.close,submitLabel:o.save,cancelLabel:o.cancel,fields:[{name:"href",label:o.linkUrl,type:"url",value:n?.href??"",placeholder:"https://"},...d?[{name:"text",label:o.linkText,type:"text",value:l}]:[],{name:"title",label:o.linkTitle,type:"text",value:n?.title??""},{name:"newTab",label:o.linkNewTab,type:"checkbox",value:n?.target==="_blank"}],extraAction:n?{label:o.remove,onClick:()=>this.removeLink()}:void 0,validate:s=>Ze(String(s.href))?null:o.linkInvalid,onSubmit:s=>{const c=Ze(String(s.href)),u={href:c,title:String(s.title).trim()||null,target:s.newTab?"_blank":null},p=f.marks.link.create(u),g=this.view.state;let v=g.tr;if(n)v=v.removeMark(n.from,n.to,f.marks.link).addMark(n.from,n.to,p);else if(d){const I=String(s.text??"").trim()||c.replace(/^mailto:/,"");v=v.replaceSelectionWith(f.text(I,[p]),!1)}else v=v.addMark(g.selection.from,g.selection.to,p);this.dispatch(v.scrollIntoView())},onClose:()=>this.view.focus()})}removeLink(){const e=Re(this.view.state);e&&this.dispatch(this.view.state.tr.removeMark(e.from,e.to,f.marks.link))}hasFileManager(){return!!this.fileManager}insertImage(e){const n=V(e.src);if(!n||this.readOnly||this.sourceMode)return!1;const r=f.nodes.image.create({src:n,alt:e.alt??"",title:e.title??null,width:e.width??null,height:e.width?e.height??null:null,align:e.align??null}),i=this.view.state.tr.replaceSelectionWith(r);return e.caption&&ft(i,i.selection.from-1,r.attrs),this.dispatch(i.scrollIntoView()),!0}openImageDialog(){if(this.readOnly||this.sourceMode)return;ze(this.view.state)||!this.fileManager?this.openImageUrlDialog():this.openFileManager("image")}openFileManager(e="image"){!this.fileManager||this.readOnly||this.sourceMode||this.fileManager.open({mode:e,accept:e==="image"?this.options.fileManager?.accept??"image/*":"",onFromUrl:e==="image"?()=>this.openImageUrlDialog():void 0,onUpload:n=>this.emit("upload",n),onPick:({file:n,alt:r,width:i,align:a,text:l,caption:d})=>{e==="image"&&le(n)?this.insertImage({src:n.url,alt:r,width:i,align:a,caption:d}):this.insertFileLink(n,l),this.emit("fileSelect",n)},onClose:()=>this.view.focus()})}openImageUrlDialog(){const e=this.t,n=ze(this.view.state),r=n?.attrs??{};kt(this.root,{title:n?e.imageEdit:e.image,closeLabel:e.close,submitLabel:n?e.save:e.insert,cancelLabel:e.cancel,fields:[{name:"src",label:e.imageUrl,type:"url",value:r.src??"",placeholder:"https://"},{name:"alt",label:e.imageAlt,type:"text",value:r.alt??"",hint:e.imageAltHint},{name:"width",label:e.imageWidth,type:"number",value:r.width?String(r.width):""},{name:"align",label:e.imageAlign,type:"select",value:r.align??"",options:[{value:"",label:e.alignNone},{value:"left",label:e.alignLeftShort},{value:"center",label:e.alignCenterShort},{value:"right",label:e.alignRightShort}]},{name:"caption",label:e.caption,type:"checkbox",value:!!n?.figure}],validate:i=>V(String(i.src))&&!/^(mailto|tel):/i.test(String(i.src).trim())?null:e.imageInvalid,onSubmit:i=>{const a=parseInt(String(i.width),10),l={src:V(String(i.src)),alt:String(i.alt).trim(),width:a>0?a:null,align:String(i.align)||null},d=!!i.caption;if(n){const o=l.width&&l.width===r.width?r.height??null:null,s={...r,...l,height:o},c=this.view.state.tr;d&&!n.figure?ft(c,n.pos,s):!d&&n.figure?on(c,n.pos,n.node,s):c.setNodeMarkup(n.pos,void 0,s).setSelection($.NodeSelection.create(c.doc,n.pos)),this.dispatch(c.scrollIntoView())}else this.insertImage({...l,caption:d})},onClose:()=>this.view.focus()})}openTableMenu(e){if(this.readOnly||this.sourceMode)return;const n=this.t,r=this.view.state;if(!N.isInTable(r)){xn(e,this.root,n.tableInsert,(l,d)=>Z(n.tableSize,{rows:String(l),cols:String(d)}),(l,d)=>this.exec(sn(l,d)));return}const i=(l,d,o=!1)=>({label:l,danger:o,enabled:d(r),run:()=>this.exec(d)}),a=[i(n.rowAbove,N.addRowBefore),i(n.rowBelow,N.addRowAfter),i(n.colLeft,N.addColumnBefore),i(n.colRight,N.addColumnAfter),"|",i(n.deleteRow,N.deleteRow),i(n.deleteCol,N.deleteColumn),"|",i(n.headerRow,N.toggleHeaderRow),i(n.headerCol,N.toggleHeaderColumn),i(n.mergeCells,N.mergeCells),i(n.splitCell,N.splitCell),"|",i(n.deleteTable,N.deleteTable,!0)];Ln(e,this.root,a,n.table)}openColorPicker(e,n){if(this.readOnly||this.sourceMode)return;const r=this.t,a=((e==="textColor"?this.options.colors?.text:this.options.colors?.highlight)??(e==="textColor"?Ft:Ut)).map(l=>typeof l=="string"?{color:l,name:l}:l).map(l=>({color:se(l.color),label:r[l.name]??l.name})).filter(l=>!!l.color);An(n,this.root,{label:e==="textColor"?r.textColor:r.highlight,removeLabel:e==="textColor"?r.removeColor:r.removeHighlight,swatches:a,columns:e==="textColor"?5:6,current:He(this.view.state,e),onPick:l=>this.exec(dn(e,l))})}togglePlainPaste(e=!this.plainPaste){this.plainPaste=e,this.refresh(),this.view.focus()}isPlainPaste(){return this.plainPaste}insertFileLink(e,n){const r=V(e.url);if(!r||this.readOnly||this.sourceMode)return;const i=f.marks.link.create({href:r}),a=this.view.state,l=a.selection.empty?a.tr.replaceSelectionWith(f.text(n||e.name,[i]),!1):a.tr.addMark(a.selection.from,a.selection.to,i);this.dispatch(l.scrollIntoView())}canUploadInline(){return!!this.fileManager?.api.canUpload&&!this.readOnly&&!this.sourceMode}uploadFiles(e,n){if(!this.canUploadInline())return;const r=this.fileManager.api;for(const i of e){const a={};let l=this.view.state.tr;n===void 0&&!l.selection.empty&&(l=l.deleteSelection());const d=n??l.selection.from;this.dispatch(l.setMeta(ne,{add:{id:a,pos:d}})),r.upload(i,this.fileManager.path).then(o=>{if(this.destroyed)return;const s=gn(this.view.state,a);if(s===null)return;const c=le(o)?f.nodes.image.create({src:o.url,alt:""}):f.text(o.name,[f.marks.link.create({href:o.url})]);this.dispatch(this.view.state.tr.replaceWith(s,s,c).setMeta(ne,{remove:{id:a}})),this.emit("upload",o)}).catch(o=>{this.destroyed||(this.dispatch(this.view.state.tr.setMeta(ne,{remove:{id:a}})),this.showNotice(Z(this.t.fmUploadFailed,{name:i.name,error:o.message})))})}}showNotice(e){this.notice||(this.notice=document.createElement("div"),this.notice.className="wds-notice",this.notice.setAttribute("role","alert"),this.root.append(this.notice)),this.notice.textContent=e,this.notice.hidden=!1,window.clearTimeout(this.noticeTimer),this.noticeTimer=window.setTimeout(()=>this.notice&&(this.notice.hidden=!0),6e3)}on(e,n){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(n),this}off(e,n){return this.listeners.get(e)?.delete(n),this}destroy(){if(this.destroyed)return;this.emit("destroy");const e=this.getHTML();this.destroyed=!0,window.clearTimeout(this.noticeTimer),wt(),this.view.destroy(),document.removeEventListener("keydown",this.onKeydown),this.fullscreen&&document.documentElement.classList.remove("wds-noscroll"),this.textarea?(this.textarea.form?.removeEventListener("submit",this.onFormSubmit),this.textarea.value=e,this.textarea.style.display="",this.root.remove()):this.target.innerHTML=e||this.originalContent,ce.delete(this.target),this.listeners.clear()}dispatch(e){if(this.destroyed)return;const n=this.view.state.apply(e);if(this.view.updateState(n),e.docChanged){const r=Le(n.doc);r!==this.lastHtml&&(this.lastHtml=r,this.syncTarget(r),this.options.onChange?.(r,this),this.emit("change"))}this.refresh()}applySource(){const e=this.sourceArea.value,n=Me(e);if(n.eq(this.view.state.doc))return;const r=this.view.state.tr.replaceWith(0,this.view.state.doc.content.size,n.content),i=this.view.state.apply(r);this.view.updateState(i),this.lastHtml=Le(i.doc),this.syncTarget(this.lastHtml),this.options.onChange?.(this.lastHtml,this),this.emit("change")}syncTarget(e){this.textarea&&(this.textarea.value=e??this.getHTML())}refresh(){const e=this.view.state;if(this.toolbar.update(e),this.counter){const n=this.getText(),r=(n.match(/[\p{L}\p{N}][\p{L}\p{N}'’-]*/gu)??[]).length,i=n.replace(/\n/g,"").length;this.counter.textContent=`${r} ${this.t.words} · ${i} ${this.t.characters}`}}emit(e,n){this.listeners.get(e)?.forEach(r=>{try{r(this,n)}catch(i){console.error(i)}})}};de.version="1.0.0",de.addLanguage=vt;let We=de;function Rn(t){const e=t.replace(/\r\n?/g,`
5
+ `)}isEmpty(){return ft(this.view.state.doc)}focus(){this.sourceMode?this.sourceArea.focus():this.view.focus()}setReadOnly(e){this.readOnly=e,this.root.classList.toggle("is-readonly",e),this.sourceArea.readOnly=e,this.view.setProps({}),this.refresh()}isReadOnly(){return this.readOnly}exec(e){if(this.readOnly||this.sourceMode)return!1;const n=e(this.view.state,r=>this.dispatch(r),this.view);return this.view.focus(),n}undo(){this.exec(Y.undo)}redo(){this.exec(Y.redo)}isSourceMode(){return this.sourceMode}toggleSource(){this.sourceMode?(this.applySource(),this.sourceMode=!1,this.sourceArea.hidden=!0,this.view.dom.hidden=!1,this.root.classList.remove("is-source"),this.view.focus()):(this.sourceArea.value=mt(xe(this.view.state.doc)),this.sourceMode=!0,this.view.dom.hidden=!0,this.sourceArea.hidden=!1,this.root.classList.add("is-source"),this.sourceArea.focus()),this.refresh()}isFullscreen(){return this.fullscreen}toggleFullscreen(){this.fullscreen=!this.fullscreen,this.root.classList.toggle("is-fullscreen",this.fullscreen),document.documentElement.classList.toggle("wds-noscroll",this.fullscreen),this.refresh(),this.focus()}openLinkDialog(){if(this.readOnly||this.sourceMode)return;const e=this.view.state,n=ze(e),{from:r,to:i,empty:s}=e.selection,c=s?"":e.doc.textBetween(r,i," "),d=s&&!n,o=this.t;Dt(this.root,{title:o.link,closeLabel:o.close,submitLabel:o.save,cancelLabel:o.cancel,fields:[{name:"href",label:o.linkUrl,type:"url",value:n?.href??"",placeholder:"https://"},...d?[{name:"text",label:o.linkText,type:"text",value:c}]:[],{name:"title",label:o.linkTitle,type:"text",value:n?.title??""},{name:"newTab",label:o.linkNewTab,type:"checkbox",value:n?.target==="_blank"}],extraAction:n?{label:o.remove,onClick:()=>this.removeLink()}:void 0,validate:a=>it(String(a.href))?null:o.linkInvalid,onSubmit:a=>{const l=it(String(a.href)),u={href:l,title:String(a.title).trim()||null,target:a.newTab?"_blank":null},p=f.marks.link.create(u),g=this.view.state;let k=g.tr;if(n)k=k.removeMark(n.from,n.to,f.marks.link).addMark(n.from,n.to,p);else if(d){const N=String(a.text??"").trim()||l.replace(/^mailto:/,"");k=k.replaceSelectionWith(f.text(N,[p]),!1)}else k=k.addMark(g.selection.from,g.selection.to,p);this.dispatch(k.scrollIntoView())},onClose:()=>this.view.focus()})}removeLink(){const e=ze(this.view.state);e&&this.dispatch(this.view.state.tr.removeMark(e.from,e.to,f.marks.link))}hasFileManager(){return!!this.fileManager}insertImage(e){const n=V(e.src);if(!n||this.readOnly||this.sourceMode)return!1;const r=f.nodes.image.create({src:n,alt:e.alt??"",title:e.title??null,width:e.width??null,height:e.width?e.height??null:null,align:e.align??null}),i=this.view.state.tr.replaceSelectionWith(r);return e.caption&&vt(i,i.selection.from-1,r.attrs),this.dispatch(i.scrollIntoView()),!0}openImageDialog(){if(this.readOnly||this.sourceMode)return;Pe(this.view.state)||!this.fileManager?this.openImageUrlDialog():this.openFileManager("image")}openFileManager(e="image"){!this.fileManager||this.readOnly||this.sourceMode||this.fileManager.open({mode:e,accept:e==="image"?this.options.fileManager?.accept??"image/*":"",onFromUrl:e==="image"?()=>this.openImageUrlDialog():void 0,onUpload:n=>this.emit("upload",n),onPick:({file:n,alt:r,width:i,align:s,text:c,caption:d})=>{e==="image"&&le(n)?this.insertImage({src:n.url,alt:r,width:i,align:s,caption:d}):this.insertFileLink(n,c),this.emit("fileSelect",n)},onClose:()=>this.view.focus()})}openImageUrlDialog(){const e=this.t,n=Pe(this.view.state),r=n?.attrs??{};Dt(this.root,{title:n?e.imageEdit:e.image,closeLabel:e.close,submitLabel:n?e.save:e.insert,cancelLabel:e.cancel,fields:[{name:"src",label:e.imageUrl,type:"url",value:r.src??"",placeholder:"https://"},{name:"alt",label:e.imageAlt,type:"text",value:r.alt??"",hint:e.imageAltHint},{name:"width",label:e.imageWidth,type:"number",value:r.width?String(r.width):""},{name:"align",label:e.imageAlign,type:"select",value:r.align??"",options:[{value:"",label:e.alignNone},{value:"left",label:e.alignLeftShort},{value:"center",label:e.alignCenterShort},{value:"right",label:e.alignRightShort}]},{name:"caption",label:e.caption,type:"checkbox",value:!!n?.figure}],validate:i=>V(String(i.src))&&!/^(mailto|tel):/i.test(String(i.src).trim())?null:e.imageInvalid,onSubmit:i=>{const s=parseInt(String(i.width),10),c={src:V(String(i.src)),alt:String(i.alt).trim(),width:s>0?s:null,align:String(i.align)||null},d=!!i.caption;if(n){const o=c.width&&c.width===r.width?r.height??null:null,a={...r,...c,height:o},l=this.view.state.tr;d&&!n.figure?vt(l,n.pos,a):!d&&n.figure?gn(l,n.pos,n.node,a):l.setNodeMarkup(n.pos,void 0,a).setSelection(H.NodeSelection.create(l.doc,n.pos)),this.dispatch(l.scrollIntoView())}else this.insertImage({...c,caption:d})},onClose:()=>this.view.focus()})}openTableMenu(e){if(this.readOnly||this.sourceMode)return;const n=this.t,r=this.view.state;if(!I.isInTable(r)){Cn(e,this.root,n.tableInsert,(c,d)=>Q(n.tableSize,{rows:String(c),cols:String(d)}),(c,d)=>this.exec(wn(c,d)));return}const i=(c,d,o=!1)=>({label:c,danger:o,enabled:d(r),run:()=>this.exec(d)}),s=[i(n.rowAbove,I.addRowBefore),i(n.rowBelow,I.addRowAfter),i(n.colLeft,I.addColumnBefore),i(n.colRight,I.addColumnAfter),"|",i(n.deleteRow,I.deleteRow),i(n.deleteCol,I.deleteColumn),"|",i(n.headerRow,I.toggleHeaderRow),i(n.headerCol,I.toggleHeaderColumn),i(n.mergeCells,I.mergeCells),i(n.splitCell,I.splitCell),"|",i(n.deleteTable,I.deleteTable,!0)];Tn(e,this.root,s,n.table)}openColorPicker(e,n){if(this.readOnly||this.sourceMode)return;const r=this.t,s=((e==="textColor"?this.options.colors?.text:this.options.colors?.highlight)??(e==="textColor"?Yt:Jt)).map(c=>typeof c=="string"?{color:c,name:c}:c).map(c=>({color:ae(c.color),label:r[c.name]??c.name})).filter(c=>!!c.color);Dn(n,this.root,{label:e==="textColor"?r.textColor:r.highlight,removeLabel:e==="textColor"?r.removeColor:r.removeHighlight,swatches:s,columns:e==="textColor"?5:6,current:Be(this.view.state,e),onPick:c=>this.exec(kn(e,c))})}togglePlainPaste(e=!this.plainPaste){this.plainPaste=e,this.refresh(),this.view.focus()}isPlainPaste(){return this.plainPaste}insertFileLink(e,n){const r=V(e.url);if(!r||this.readOnly||this.sourceMode)return;const i=f.marks.link.create({href:r}),s=this.view.state,c=s.selection.empty?s.tr.replaceSelectionWith(f.text(n||e.name,[i]),!1):s.tr.addMark(s.selection.from,s.selection.to,i);this.dispatch(c.scrollIntoView())}canUploadInline(){return!!this.fileManager?.api.canUpload&&!this.readOnly&&!this.sourceMode}uploadFiles(e,n){if(!this.canUploadInline())return;const r=this.fileManager.api;for(const i of e){const s={};let c=this.view.state.tr;n===void 0&&!c.selection.empty&&(c=c.deleteSelection());const d=n??c.selection.from;this.dispatch(c.setMeta(te,{add:{id:s,pos:d}})),r.upload(i,this.fileManager.path).then(o=>{if(this.destroyed)return;const a=Sn(this.view.state,s);if(a===null)return;const l=le(o)?f.nodes.image.create({src:o.url,alt:""}):f.text(o.name,[f.marks.link.create({href:o.url})]);this.dispatch(this.view.state.tr.replaceWith(a,a,l).setMeta(te,{remove:{id:s}})),this.emit("upload",o)}).catch(o=>{this.destroyed||(this.dispatch(this.view.state.tr.setMeta(te,{remove:{id:s}})),this.showNotice(Q(this.t.fmUploadFailed,{name:i.name,error:o.message})))})}}showNotice(e){this.notice||(this.notice=document.createElement("div"),this.notice.className="wds-notice",this.notice.setAttribute("role","alert"),this.root.append(this.notice)),this.notice.textContent=e,this.notice.hidden=!1,window.clearTimeout(this.noticeTimer),this.noticeTimer=window.setTimeout(()=>this.notice&&(this.notice.hidden=!0),6e3)}on(e,n){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(n),this}off(e,n){return this.listeners.get(e)?.delete(n),this}destroy(){if(this.destroyed)return;this.emit("destroy");const e=this.getHTML();this.destroyed=!0,window.clearTimeout(this.noticeTimer),kt(),this.view.destroy(),document.removeEventListener("keydown",this.onKeydown),this.fullscreen&&document.documentElement.classList.remove("wds-noscroll"),this.textarea?(this.textarea.form?.removeEventListener("submit",this.onFormSubmit),this.textarea.value=e,this.textarea.style.display="",this.root.remove()):this.target.innerHTML=e||this.originalContent,ce.delete(this.target),this.listeners.clear()}dispatch(e){if(this.destroyed)return;const n=this.view.state.apply(e);if(this.view.updateState(n),e.docChanged){const r=xe(n.doc);r!==this.lastHtml&&(this.lastHtml=r,this.syncTarget(r),this.options.onChange?.(r,this),this.emit("change"))}this.refresh()}applySource(){const e=this.sourceArea.value,n=Le(e);if(n.eq(this.view.state.doc))return;const r=this.view.state.tr.replaceWith(0,this.view.state.doc.content.size,n.content),i=this.view.state.apply(r);this.view.updateState(i),this.lastHtml=xe(i.doc),this.syncTarget(this.lastHtml),this.options.onChange?.(this.lastHtml,this),this.emit("change")}syncTarget(e){this.textarea&&(this.textarea.value=e??this.getHTML())}refresh(){const e=this.view.state;if(this.toolbar.update(e),this.counter){const n=this.getText(),r=(n.match(/[\p{L}\p{N}][\p{L}\p{N}'’-]*/gu)??[]).length,i=n.replace(/\n/g,"").length;this.counter.textContent=`${r} ${this.t.words} · ${i} ${this.t.characters}`}}emit(e,n){this.listeners.get(e)?.forEach(r=>{try{r(this,n)}catch(i){console.error(i)}})}};de.version="1.1.0",de.addLanguage=_e;let Ye=de;function Kn(t){const e=t.replace(/\r\n?/g,`
9
6
  `).split(/\n{2,}/).map(n=>{const i=n.split(`
10
- `).flatMap((a,l)=>[...l?[f.nodes.hard_break.create()]:[],...a?[f.text(a)]:[]]);return f.nodes.paragraph.create(null,i)});return new J.Slice(J.Fragment.from(e),1,1)}function zn(t){const e=document.createElement("span");return e.textContent=t,e.innerHTML}T.DEFAULT_TOOLBAR=mt,T.WDSEditor=We,T.addLanguage=vt,T.en=ge,T.isImage=le,T.matchesAccept=Ue,T.normalizeList=Lt,T.schema=f,T.toolbarItems=pt,T.tr=yt,Object.defineProperty(T,Symbol.toStringTag,{value:"Module"})}));
7
+ `).flatMap((s,c)=>[...c?[f.nodes.hard_break.create()]:[],...s?[f.text(s)]:[]]);return f.nodes.paragraph.create(null,i)});return new J.Slice(J.Fragment.from(e),1,1)}function Yn(t){const e=document.createElement("span");return e.textContent=t,e.innerHTML}D.DEFAULT_TOOLBAR=Lt,D.WDSEditor=Ye,D.addLanguage=_e,D.en=ge,D.isImage=le,D.matchesAccept=Ge,D.normalizeList=It,D.schema=f,D.toolbarItems=Mt,D.tr=At,Object.defineProperty(D,Symbol.toStringTag,{value:"Module"})}));
11
8
  //# sourceMappingURL=wds-editor.umd.cjs.map