wds-editor 1.1.0 → 1.2.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,8 +1,9 @@
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,`
1
+ (function(D,N){typeof exports=="object"&&typeof module<"u"?N(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"],N):(D=typeof globalThis<"u"?globalThis:D||self,N(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,N,ne,X,Q,ae,R,Z,Re,_,an,ln){"use strict";const cn=/^(https?:|mailto:|tel:)/i,ut=/^[a-z][a-z0-9+.-]*:/i;function K(t){if(t==null)return null;const e=t.trim();if(!e)return null;const n=e.replace(/[\u0000- \u007f-\u009f]/g,"");return ut.test(n)&&!cn.test(n)?null:e}function ht(t){const e=t.trim();return e?/^[^\s@/]+@[^\s@/]+\.[^\s@/]+$/.test(e)?`mailto:${e}`:!ut.test(e)&&!/^[/#?.]/.test(e)&&/^[\w-]+(\.[\w-]+)+/.test(e)?`https://${e}`:K(e):null}function dn(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 un=/^[\w-]{11}$/,ft=560;function hn(t){if(!t)return 0;if(/^\d+$/.test(t))return+t;const e=t.match(/^(?:(\d+)h)?(?:(\d+)m)?(?:(\d+)s)?$/);return e?+(e[1]??0)*3600+ +(e[2]??0)*60+ +(e[3]??0):0}function Ee(t){if(!t)return null;let e=t.trim();const n=e.match(/<iframe[^>]*\ssrc=["']([^"']+)["']/i);n&&(e=n[1]),e.startsWith("//")&&(e=`https:${e}`),/^https?:\/\//i.test(e)||(e=`https://${e}`);let i;try{i=new URL(e.replace(/&amp;/g,"&"))}catch{return null}const r=i.hostname.replace(/^(www|m|music)\./,""),s=i.pathname.split("/").filter(Boolean);if(r==="youtube.com"||r==="youtube-nocookie.com"||r==="youtu.be"){let o=null;if(r==="youtu.be"?o=s[0]??null:s[0]==="watch"?o=i.searchParams.get("v"):["embed","shorts","live","v"].includes(s[0])&&(o=s[1]??null),!o||!un.test(o))return null;const c=hn(i.searchParams.get("start")??i.searchParams.get("t"));return`https://www.youtube-nocookie.com/embed/${o}${c?`?start=${c}`:""}`}if(r==="vimeo.com"||r==="player.vimeo.com"){const o=s.findIndex(l=>/^\d+$/.test(l));if(o<0)return null;const c=s[o],a=i.searchParams.get("h")??(r==="vimeo.com"&&/^[\da-f]+$/i.test(s[o+1]??"")?s[o+1]:null);return`https://player.vimeo.com/video/${c}${a?`?h=${a}`:""}`}return null}const fn=t=>{const e=parseInt(t.style.maxWidth,10),n=parseInt(t.getAttribute("width")??"",10),i=e>0?e:n;return i>0&&i<=4e3?i:null};function pt(t){const e=t.width??ft;return{src:t.src,title:t.title||"Video",width:String(e),height:String(Math.round(e*9/16)),style:`width: 100%; max-width: ${e}px; height: auto; aspect-ratio: 16 / 9; border: 0`,allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share",referrerpolicy:"strict-origin-when-cross-origin",loading:"lazy",allowfullscreen:"true"}}const pn={group:"block",atom:!0,draggable:!0,attrs:{src:{},title:{default:""},width:{default:null}},parseDOM:[{tag:"iframe[src]",getAttrs:t=>{const e=t,n=Ee(e.getAttribute("src"));if(!n)return!1;const i=e.getAttribute("title")??"";return{src:n,title:i==="Video"?"":i,width:fn(e)}}}],toDOM:t=>["iframe",pt(t.attrs)]};class mn{constructor(e,n,i){this.onEdit=n,this.dom=document.createElement("div"),this.dom.className="wds-video",this.dom.contentEditable="false",this.iframe=document.createElement("iframe"),this.dom.append(this.iframe),this.dom.addEventListener("dblclick",()=>this.onEdit()),this.render(e)}render(e){const n=pt(e.attrs);for(const[i,r]of Object.entries(n))this.iframe.getAttribute(i)!==r&&this.iframe.setAttribute(i,r);this.iframe.tabIndex=-1,this.dom.style.maxWidth=`${e.attrs.width??ft}px`}update(e){return e.type.name!=="video"?!1:(this.render(e),!0)}stopEvent(){return!1}ignoreMutation(){return!0}}const mt={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"},Oe=t=>Math.max(0,Math.min(255,Math.round(t))).toString(16).padStart(2,"0");function le(t){if(!t)return null;const e=t.trim().toLowerCase().replace(/\s*!important$/,"");if(mt[e])return mt[e];let n=/^#([0-9a-f]{3})$/.exec(e);return n?"#"+[...n[1]].map(i=>i+i).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:"#"+Oe(+n[1])+Oe(+n[2])+Oe(+n[3]):null))}function gt(t){const e=le(t);return e&&e!=="#000000"?e:null}function $e(t){const e=le(t)??le((t??"").split(/\s+(?![^(]*\))/).find(n=>le(n)));return e&&e!=="#ffffff"?e:null}const gn=[{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"}],bn=[{color:"#fef08a",name:"colorYellow"},{color:"#bbf7d0",name:"colorGreen"},{color:"#bae6fd",name:"colorBlue"},{color:"#fbcfe8",name:"colorPink"},{color:"#fed7aa",name:"colorOrange"},{color:"#e9d5ff",name:"colorPurple"}],wn=["left","center","right","justify"];function bt(t){const e=(t.style.textAlign||t.getAttribute("align")||"").toLowerCase();return wn.includes(e)&&e!=="left"?e:null}function wt(t){return t?{style:`text-align: ${t}`}:{}}const yn={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"},vn={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 kn(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 yt={src:{},alt:{default:""},title:{default:null},width:{default:null},height:{default:null},align:{default:null}};function vt(t,e){const n=K(t.getAttribute("src"));return n?{src:n,alt:t.getAttribute("alt")??"",title:t.getAttribute("title"),width:kt(t.getAttribute("width")??t.style.width),height:kt(t.getAttribute("height")??t.style.height),align:kn(e)}:!1}function Pe(t,e){const{src:n,alt:i,title:r,width:s,height:o,align:c}=t,a={src:n,alt:i??""};r&&(a.title=r),s&&(a.width=String(s)),s&&o&&(a.height=String(o));const l=e?yn[c]:void 0;return l&&(a.style=l),a}function kt(t){const e=/^\s*(\d{1,5})(px)?\s*$/.exec(t??"");return e?Number(e[1]):null}const Mn={doc:{content:"block+"},paragraph:{content:"inline*",group:"block",attrs:{align:{default:null}},parseDOM:[{tag:"p",getAttrs:t=>({align:bt(t)})}],toDOM:t=>["p",wt(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:bt(e)})})),toDOM:t=>[`h${t.attrs.level}`,wt(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]]},...R.tableNodes({tableGroup:"block",cellContent:"block+",cellAttributes:{}}),text:{group:"inline"},image:{inline:!0,group:"inline",draggable:!0,attrs:yt,parseDOM:[{tag:"img[src]",getAttrs:t=>vt(t,t)}],toDOM:t=>["img",Pe(t.attrs,!0)]},figure:{group:"block",content:"inline*",marks:"_",draggable:!0,isolating:!0,attrs:yt,parseDOM:[{tag:"figure",getAttrs:t=>{const e=t.querySelector("img");return e?vt(e,t):!1},contentElement:t=>t.querySelector("figcaption")??document.createElement("figcaption")}],toDOM:t=>{const e=vn[t.attrs.align];return["figure",e?{style:e}:{},["img",Pe(t.attrs,!1)],["figcaption",0]]}},video:pn,hard_break:{inline:!0,group:"inline",selectable:!1,parseDOM:[{tag:"br"}],toDOM:()=>["br"]}},xn={link:{attrs:{href:{},title:{default:null},target:{default:null}},inclusive:!1,parseDOM:[{tag:"a[href]",getAttrs:t=>{const e=t,n=K(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=gt(t.style.color);return e?{color:e}:!1}},{tag:"font[color]",getAttrs:t=>{const e=gt(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:$e(t.style.backgroundColor)??"#fef08a"})},{style:"background-color",getAttrs:t=>{const e=$e(t);return e?{color:e}:!1}},{style:"background",getAttrs:t=>{const e=$e(t);return e?{color:e}:!1}}],toDOM:t=>["mark",{style:`background-color: ${le(t.attrs.color)??"#fef08a"}`},0]},code:{parseDOM:[{tag:"code"}],toDOM:()=>["code",0]}},Mt=new Q.Schema({nodes:Mn,marks:xn}),f=new Q.Schema({nodes:ae.addListNodes(Mt.spec.nodes,"paragraph block*","block"),marks:Mt.spec.marks}),Ln=Q.DOMSerializer.fromSchema(f),Sn=Q.DOMParser.fromSchema(f);function Ae(t){const e=new window.DOMParser().parseFromString(`<!doctype html><body>${t}`,"text/html");return Sn.parse(e.body)}function Te(t){if(xt(t))return"";const e=document.createElement("div");return e.append(Ln.serializeFragment(t.content)),e.querySelectorAll("[style]").forEach(n=>n.setAttribute("style",An(n.getAttribute("style")??""))),e.innerHTML}const En=(t,e,n,i)=>"#"+[e,n,i].map(r=>(+r).toString(16).padStart(2,"0")).join("");function An(t){return t.split(";").map(e=>e.trim()).filter(Boolean).map(e=>e.replace(/rgb\(\s*(\d+),\s*(\d+),\s*(\d+)\s*\)/g,En).replace(/(^|[\s:])0px(?![\w.])/g,(n,i)=>`${i}0`).replace(/\s*:\s*/,": ")).join("; ")}function xt(t){const e=t.firstChild;return t.childCount===1&&!!e&&e.type===f.nodes.paragraph&&e.content.size===0&&!e.attrs.align}const He=new Set(["UL","OL","BLOCKQUOTE","TABLE","THEAD","TBODY","TFOOT","TR","FIGURE"]),Be=new Set(["LI","TH","TD"]),Lt=t=>t.nodeType===1&&(He.has(t.tagName)||Be.has(t.tagName)||/^(P|H[1-6]|PRE|HR|FIGCAPTION|IMG|DIV|IFRAME)$/.test(t.tagName)),Tn=t=>{const n=t.cloneNode(!1).outerHTML;return n.slice(0,n.length-`</${t.localName}>`.length)};function St(t){const e=document.createElement("div");e.innerHTML=t;const n=[],i=(r,s)=>{const o=" ".repeat(s);let c="";const a=()=>{c.trim()&&n.push(o+c.trim()),c=""};r.childNodes.forEach(l=>{if(!Lt(l)){c+=l.nodeType===1?l.outerHTML:l.nodeType===3?Cn(l.textContent??""):"";return}a();const d=l,u=Array.from(d.childNodes).filter(Lt);(Be.has(d.tagName)?u.length<=1&&u.every(m=>!He.has(m.tagName)&&!Be.has(m.tagName)):!He.has(d.tagName))?n.push(o+d.outerHTML):(n.push(o+Tn(d)),i(d,s+1),n.push(`${o}</${d.localName}>`))}),a()};return i(e,0),n.join(`
2
+ `)}const Cn=t=>t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/ /g,"&nbsp;");function be(t,e){const{from:n,$from:i,to:r,empty:s}=t.selection;return s?!!e.isInSet(t.storedMarks||i.marks()):t.doc.rangeHasMark(n,r,e)}function In(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 Dn(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 q=t=>_.toggleMark(f.marks[t]);function Et(t,e){const{$from:n}=t.selection;for(let i=n.depth;i>0;i--)if(n.node(i).type===e)return!0;return!1}function At(t){const{$from:e}=t.selection;for(let n=e.depth;n>0;n--){const i=e.node(n).type;if(i===f.nodes.bullet_list||i===f.nodes.ordered_list)return i}return null}function Tt(t){return(e,n,i)=>{const{$from:r}=e.selection;for(let s=r.depth;s>0;s--){const o=r.node(s);if(o.type===f.nodes.bullet_list||o.type===f.nodes.ordered_list)return o.type===t?ae.liftListItem(f.nodes.list_item)(e,n,i):(n&&n(e.tr.setNodeMarkup(r.before(s),t)),!0)}return ae.wrapInList(t)(e,n,i)}}const ze=ae.sinkListItem(f.nodes.list_item),Fe=(t,e,n)=>ae.liftListItem(f.nodes.list_item)(t,e,n)||_.lift(t,e);function Nn(){return(t,e)=>Et(t,f.nodes.blockquote)?_.lift(t,e):_.wrapIn(f.nodes.blockquote)(t,e)}function Ct(t,e="left"){return(n,i)=>{const r=t===e?null:t,{from:s,to:o}=n.selection,c=n.tr;let a=!1;return n.doc.nodesBetween(s,o,(l,d)=>l.type===f.nodes.paragraph||l.type===f.nodes.heading?(a=!0,l.attrs.align!==r&&c.setNodeMarkup(d,void 0,{...l.attrs,align:r}),!1):!0),a?(i&&i(c),!0):!1}}function Rn(t,e="left"){return t.selection.$from.parent.attrs.align??e}const On=(t,e)=>{const n=f.nodes.horizontal_rule;if(!e)return!0;const i=t.tr.replaceSelectionWith(n.create()),r=i.selection.$from;return!r.nodeAfter&&r.parent.type===f.nodes.doc&&i.insert(r.pos,f.nodes.paragraph.create()),e(i.scrollIntoView()),!0},$n=(t,e)=>{const{from:n,to:i,empty:r}=t.selection,s=t.tr;if(r)s.setStoredMarks([]);else for(const o of Object.values(f.marks))o!==f.marks.link&&s.removeMark(n,i,o);return t.doc.nodesBetween(n,i,(o,c)=>o.isTextblock&&o.type!==f.nodes.paragraph?(s.setBlockType(c,c+o.nodeSize,f.nodes.paragraph),!1):(o.type===f.nodes.paragraph&&o.attrs.align&&s.setNodeMarkup(c,void 0,{align:null}),!0)),e&&e(s),!0};function Ue(t){const e=f.marks.link,{$from:n,from:i,to:r,empty:s}=t.selection;if(!s){let u=null;return t.doc.nodesBetween(i,r,(p,m)=>{const b=e.isInSet(p.marks);b&&!u&&(u={from:Math.max(m,i),to:Math.min(m+p.nodeSize,r),...b.attrs})}),u}const o=e.isInSet(n.marks())??e.isInSet(n.nodeBefore?.marks??[]);if(!o)return null;const c=n.start(),a=[];let l=0;n.parent.forEach(u=>{const p=c+l,m=p+u.nodeSize;if(o.isInSet(u.marks)){const b=a[a.length-1];b&&b[1]===p?b[1]=m:a.push([p,m])}l+=u.nodeSize});const d=a.find(([u,p])=>u<=n.pos&&n.pos<=p);return d?{from:d[0],to:d[1],...o.attrs}:null}function It(t){const e=t.selection;return e instanceof N.NodeSelection&&e.node.type===f.nodes.video?{pos:e.from,node:e.node}:null}function We(t){const e=t.selection;return e instanceof N.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 Dt(t,e,n){const i=f.nodes.figure.create(n),r=t.doc.resolve(e),s=r.parent;s.type===f.nodes.paragraph&&s.childCount===1?t.replaceWith(r.before(),r.after(),i):t.replaceRangeWith(e,e+1,i);let o=-1;return t.doc.descendants((c,a)=>o>=0?!1:(c.type===f.nodes.figure&&c.attrs.src===n.src&&c.content.size===0&&(o=a),!0)),o>=0&&t.setSelection(N.TextSelection.create(t.doc,o+1)),t}function Pn(t,e,n,i){const r=f.nodes.image.create(i),s=[f.nodes.paragraph.create(null,r)];return n.content.size&&s.push(f.nodes.paragraph.create(null,n.content)),t.replaceWith(e,e+n.nodeSize,Q.Fragment.from(s)),t.setSelection(N.NodeSelection.create(t.doc,e+1))}function Hn(t,e,n=!0){const i=f.nodes,r=s=>i.table_row.create(null,Array.from({length:e},()=>s.createAndFill()));return i.table.create(null,Array.from({length:t},(s,o)=>r(n&&o===0?i.table_header:i.table_cell)))}function Bn(t,e){return(n,i)=>{if(R.isInTable(n))return!1;if(!i)return!0;const r=Hn(t,e),s=n.tr,o=n.selection.$from;o.parent.type===f.nodes.paragraph&&o.parent.content.size===0&&o.depth===1?s.replaceWith(o.before(),o.after(),r):s.replaceSelectionWith(r);let a=-1;if(s.doc.descendants((l,d)=>a>=0?!1:(l===r&&(a=d),a<0&&l.type!==f.nodes.table)),a>=0){const l=a+s.doc.nodeAt(a).nodeSize;l>=s.doc.content.size&&s.insert(l,f.nodes.paragraph.create()),s.setSelection(N.TextSelection.create(s.doc,a+4))}return i(s.scrollIntoView()),!0}}const zn=(t,e,n)=>R.isInTable(t)?R.goToNextCell(1)(t,e)||!e||!n?!0:(R.addRowAfter(t,e),R.goToNextCell(1)(n.state,e)):!1,Fn=(t,e)=>R.isInTable(t)&&R.goToNextCell(-1)(t,e);function _e(t,e){const n=f.marks[e],{from:i,to:r,empty:s,$from:o}=t.selection;if(s)return n.isInSet(t.storedMarks||o.marks())?.attrs.color??null;let c;return t.doc.nodesBetween(i,r,a=>{if(!a.isText||c===null)return;const l=n.isInSet(a.marks)?.attrs.color??null;c=c===void 0||c===l?l:null}),c??null}function Un(t,e){return(n,i)=>{const r=f.marks[t],{from:s,to:o,empty:c}=n.selection;if(!i)return!0;const a=n.tr;return c?(a.removeStoredMark(r),e&&a.addStoredMark(r.create({color:e}))):(a.removeMark(s,o,r),e&&a.addMark(s,o,r.create({color:e}))),i(a.scrollIntoView()),!0}}function Wn(){const t=f.nodes;return Z.inputRules({rules:[Z.textblockTypeInputRule(/^(#{1,4})\s$/,t.heading,e=>({level:e[1].length})),Z.wrappingInputRule(/^\s*>\s$/,t.blockquote),Z.wrappingInputRule(/^\s*([-+*])\s$/,t.bullet_list),Z.wrappingInputRule(/^(\d+)\.\s$/,t.ordered_list,e=>({order:+e[1]}),(e,n)=>n.childCount+n.attrs.order===+e[1]),Z.textblockTypeInputRule(/^```$/,t.code_block),new Z.InputRule(/^(?:---|\*\*\*|___)$/,(e,n,i,r)=>{const s=e.doc.resolve(i);if(s.parent.type!==t.paragraph)return null;const o=s.before();return e.tr.replaceWith(o,r+1,[t.horizontal_rule.create(),t.paragraph.create()])})]})}function _n(t){const e=_.chainCommands(_.exitCode,(n,i)=>(i&&i(n.tr.replaceSelectionWith(f.nodes.hard_break.create()).scrollIntoView()),!0));return Re.keymap({"Mod-z":X.undo,"Mod-y":X.redo,"Shift-Mod-z":X.redo,Backspace:Z.undoInputRule,"Mod-b":q("strong"),"Mod-i":q("em"),"Mod-u":q("underline"),"Mod-Shift-x":q("strike"),"Mod-e":q("code"),"Mod-k":t.link,"Shift-Enter":e,"Mod-Enter":e,Enter:ae.splitListItem(f.nodes.list_item),Tab:ze,"Shift-Tab":Fe})}const qn=()=>Re.keymap(_.baseKeymap);function Vn(t){return new N.Plugin({props:{decorations(e){const n=e.doc,i=n.firstChild;return!t||n.childCount!==1||!i||!i.isTextblock||i.content.size>0?null:ne.DecorationSet.create(n,[ne.Decoration.node(0,i.nodeSize,{class:"wds-placeholder","data-placeholder":t})])}}})}const ie=new N.PluginKey("wds-upload");function Gn(){return new N.Plugin({key:ie,state:{init:()=>ne.DecorationSet.empty,apply(t,e){e=e.map(t.mapping,t.doc);const n=t.getMeta(ie);if(n&&"add"in n){const i=document.createElement("span");i.className="wds-upload-placeholder",i.setAttribute("aria-hidden","true"),e=e.add(t.doc,[ne.Decoration.widget(n.add.pos,i,{id:n.add.id})])}else n&&"remove"in n&&(e=e.remove(e.find(void 0,void 0,i=>i.id===n.remove.id)));return e}},props:{decorations:t=>ie.getState(t)}})}function jn(t,e){const n=ie.getState(t)?.find(void 0,void 0,i=>i.id===e);return n&&n.length?n[0].from:null}const S=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>`,x={undo:S('<path d="M9 14 4 9l5-5"/><path d="M4 9h11a5 5 0 0 1 0 10h-3"/>'),redo:S('<path d="m15 14 5-5-5-5"/><path d="M20 9H9a5 5 0 0 0 0 10h3"/>'),bold:S('<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:S('<path d="M14 5h-4"/><path d="M14 19h-4"/><path d="m14 5-4 14"/><path d="M18 5h-4M10 19H6"/>'),underline:S('<path d="M7 4v7a5 5 0 0 0 10 0V4"/><path d="M5 20h14"/>'),strike:S('<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:S('<path d="m9 8-4 4 4 4"/><path d="m15 8 4 4-4 4"/>'),link:S('<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:S('<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:S('<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:S('<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:S('<path d="M4 6h16M10 10h10M10 14h10M4 18h16"/><path d="m4 9.5 3 2.5-3 2.5"/>'),outdent:S('<path d="M4 6h16M10 10h10M10 14h10M4 18h16"/><path d="m7 9.5-3 2.5 3 2.5"/>'),alignLeft:S('<path d="M4 6h16M4 10h10M4 14h16M4 18h10"/>'),alignCenter:S('<path d="M4 6h16M7 10h10M4 14h16M7 18h10"/>'),alignRight:S('<path d="M4 6h16M10 10h10M4 14h16M10 18h10"/>'),alignJustify:S('<path d="M4 6h16M4 10h16M4 14h16M4 18h16"/>'),hr:S('<path d="M3 12h18"/><path d="M8 7h8M8 17h8" opacity=".45"/>'),clear:S('<path d="M6 5h12"/><path d="M12 5 9 19"/><path d="m15 14 5 5M20 14l-5 5"/>'),source:S('<path d="m8 7-5 5 5 5"/><path d="m16 7 5 5-5 5"/><path d="m14 4-4 16"/>'),fullscreen:S('<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:S('<path d="M6 6l12 12M18 6 6 18"/>'),image:S('<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:S('<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:S('<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:S('<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:S('<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:S('<path d="M9 6h11M9 12h11M9 18h11"/><path d="M4 6h1M4 12h1M4 18h1"/>'),trash:S('<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"/>'),video:S('<rect x="3" y="5" width="18" height="14" rx="3"/><path d="m10 9 5 3-5 3z"/>'),search:S('<circle cx="11" cy="11" r="6.5"/><path d="m20 20-4.2-4.2"/>'),arrowUp:S('<path d="m6 15 6-6 6 6"/>'),arrowDown:S('<path d="m6 9 6 6 6-6"/>'),table:S('<rect x="3" y="4" width="18" height="16" rx="2"/><path d="M3 10h18M3 15h18M9 4v16M15 4v16"/>'),pasteText:S('<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:S('<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:S('<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:S('<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"/>')},ce=t=>getComputedStyle(t).direction==="rtl";let Ce=null;function Nt(){Ce?.close()}function qe(t,e,n,i){Nt();const r=document.createElement("div");r.className=`wds-menu ${n}`,e.append(r);const s=()=>{const u=t.getBoundingClientRect();r.style.maxHeight="";const p=r.offsetWidth,m=r.offsetHeight,b=ce(e)?u.right-p:u.left;r.style.left=`${Math.max(4,Math.min(b,window.innerWidth-p-4))}px`;const L=window.innerHeight-u.bottom-8,T=u.top-8;m<=L||L>=T?(r.style.top=`${u.bottom+4}px`,m>L&&(r.style.maxHeight=`${L}px`)):(r.style.top=`${Math.max(4,u.top-Math.min(m,T)-4)}px`,m>T&&(r.style.maxHeight=`${T}px`))},o=u=>{if(u.target instanceof Node&&r.contains(u.target))return;const p=t.getBoundingClientRect();p.bottom<0||p.top>window.innerHeight||!t.isConnected?d():s()};t.setAttribute("aria-expanded","true");const c=u=>{!r.contains(u.target)&&u.target!==t&&!t.contains(u.target)&&d()},a=u=>{u.key==="Escape"&&(u.preventDefault(),u.stopPropagation(),d(!0))};let l=!1;function d(u=!1){l||(l=!0,r.remove(),t.setAttribute("aria-expanded","false"),document.removeEventListener("mousedown",c,!0),window.removeEventListener("scroll",o,!0),window.removeEventListener("resize",o),r.removeEventListener("keydown",a),Ce?.close===d&&(Ce=null),u&&t.focus())}return document.addEventListener("mousedown",c,!0),window.addEventListener("scroll",o,!0),window.addEventListener("resize",o),r.addEventListener("keydown",a),Ce={close:d},{popup:r,place:s,close:d}}function Kn(t,e,n,i){const{popup:r,place:s,close:o}=qe(t,e,"wds-menu-list");r.setAttribute("role","menu"),r.setAttribute("aria-label",i);for(const a of n){if(a==="|"){const d=document.createElement("div");d.className="wds-menu-sep",d.setAttribute("role","separator"),r.append(d);continue}const l=document.createElement("button");l.type="button",l.className=`wds-menu-item${a.danger?" is-danger":""}`,l.setAttribute("role","menuitem"),l.tabIndex=-1,l.innerHTML=a.icon??"",l.append(document.createTextNode(a.label)),a.enabled===!1&&(l.disabled=!0),l.addEventListener("mousedown",d=>d.preventDefault()),l.addEventListener("click",()=>{o(),a.run()}),r.append(l)}const c=()=>[...r.querySelectorAll(".wds-menu-item:not(:disabled)")];r.addEventListener("keydown",a=>{const l=c(),d=l.indexOf(document.activeElement);let u=-1;a.key==="ArrowDown"?u=(d+1)%l.length:a.key==="ArrowUp"?u=(d-1+l.length)%l.length:a.key==="Home"?u=0:a.key==="End"?u=l.length-1:a.key==="Tab"&&o(),u>=0&&(a.preventDefault(),l[u]?.focus())}),s(),c()[0]?.focus()}function Yn(t,e,n,i,r){const{popup:c,place:a,close:l}=qe(t,e,"wds-table-picker");c.setAttribute("role","dialog"),c.setAttribute("aria-label",n);const d=document.createElement("div");d.className="wds-picker-grid",d.style.gridTemplateColumns="repeat(10, 1fr)",d.tabIndex=0,d.setAttribute("role","grid"),d.setAttribute("aria-label",n);const u=document.createElement("div");u.className="wds-picker-label",u.setAttribute("aria-live","polite");const p=[];let m=3,b=3;const L=()=>{p.forEach((T,A)=>T.classList.toggle("is-on",Math.floor(A/10)<m&&A%10<b)),u.textContent=i(m,b),d.setAttribute("aria-valuetext",u.textContent)};for(let T=0;T<8;T++)for(let A=0;A<10;A++){const $=document.createElement("span");$.className="wds-picker-cell",$.addEventListener("mouseenter",()=>{m=T+1,b=A+1,L()}),$.addEventListener("mousedown",v=>v.preventDefault()),$.addEventListener("click",()=>{l(),r(T+1,A+1)}),p.push($),d.append($)}d.addEventListener("keydown",T=>{const A=ce(d)?-1:1,$={ArrowRight:[0,A],ArrowLeft:[0,-A],ArrowDown:[1,0],ArrowUp:[-1,0]};$[T.key]?(T.preventDefault(),m=Math.min(8,Math.max(1,m+$[T.key][0])),b=Math.min(10,Math.max(1,b+$[T.key][1])),L()):T.key==="Enter"||T.key===" "?(T.preventDefault(),l(),r(m,b)):T.key==="Tab"&&l()}),c.append(d,u),L(),a(),d.focus()}function Jn(t,e,n){const{popup:i,place:r,close:s}=qe(t,e,"wds-color-picker");i.setAttribute("role","dialog"),i.setAttribute("aria-label",n.label);const o=l=>{s(),n.onPick(l)},c=document.createElement("button");c.type="button",c.className="wds-menu-item wds-color-remove",c.innerHTML='<span class="wds-swatch is-none" aria-hidden="true"></span>',c.append(document.createTextNode(n.removeLabel)),c.addEventListener("mousedown",l=>l.preventDefault()),c.addEventListener("click",()=>o(null));const a=document.createElement("div");a.className="wds-swatches",a.style.gridTemplateColumns=`repeat(${n.columns}, 1fr)`;for(const l of n.swatches){const d=document.createElement("button");d.type="button",d.className="wds-swatch",d.style.background=l.color,d.title=l.label,d.setAttribute("aria-label",l.label);const u=l.color===n.current;d.setAttribute("aria-pressed",String(u)),u&&d.classList.add("is-current"),d.addEventListener("mousedown",p=>p.preventDefault()),d.addEventListener("click",()=>o(l.color)),a.append(d)}i.append(c,a),i.addEventListener("keydown",l=>{const d=[c,...a.querySelectorAll(".wds-swatch")],u=d.indexOf(document.activeElement);if(u<0)return;const p=n.columns;let m=-1;const b=ce(i)?"ArrowLeft":"ArrowRight",L=ce(i)?"ArrowRight":"ArrowLeft";l.key===b?m=Math.min(d.length-1,u+1):l.key===L?m=Math.max(0,u-1):l.key==="ArrowDown"?m=u===0?1:Math.min(d.length-1,u+p):l.key==="ArrowUp"?m=u<=p?0:u-p:l.key==="Tab"&&s(),m>=0&&(l.preventDefault(),d[m].focus())}),r(),(a.querySelector(".is-current")??a.querySelector(".wds-swatch"))?.focus()}const B=t=>e=>e.exec(t),Ve=t=>ce(t.root)?"right":"left",Ie=t=>{const e=`align${t[0].toUpperCase()}${t.slice(1)}`;return{type:"button",label:e,icon:x[e],run:n=>n.exec(Ct(t,Ve(n))),active:(n,i)=>Rn(n,Ve(i))===t,enabled:(n,i)=>Ct(t,Ve(i))(n)}},Rt={undo:{type:"button",label:"undo",icon:x.undo,shortcut:"Mod+Z",run:t=>t.undo(),enabled:t=>X.undoDepth(t)>0},redo:{type:"button",label:"redo",icon:x.redo,shortcut:"Mod+Y",run:t=>t.redo(),enabled:t=>X.redoDepth(t)>0},blocks:{type:"blocks"},bold:{type:"button",label:"bold",icon:x.bold,shortcut:"Mod+B",run:B(q("strong")),active:t=>be(t,f.marks.strong)},italic:{type:"button",label:"italic",icon:x.italic,shortcut:"Mod+I",run:B(q("em")),active:t=>be(t,f.marks.em)},underline:{type:"button",label:"underline",icon:x.underline,shortcut:"Mod+U",run:B(q("underline")),active:t=>be(t,f.marks.underline)},strike:{type:"button",label:"strike",icon:x.strike,run:B(q("strike")),active:t=>be(t,f.marks.strike)},textColor:{type:"button",label:"textColor",icon:x.textColor,popup:!0,run:(t,e)=>t.openColorPicker("textColor",e),swatch:t=>_e(t,"textColor")},highlight:{type:"button",label:"highlight",icon:x.highlight,popup:!0,run:(t,e)=>t.openColorPicker("highlight",e),swatch:t=>_e(t,"highlight")},code:{type:"button",label:"code",icon:x.code,run:B(q("code")),active:t=>be(t,f.marks.code)},link:{type:"button",label:"link",icon:x.link,shortcut:"Mod+K",run:t=>t.openLinkDialog(),active:t=>!!Ue(t)},image:{type:"button",label:"image",icon:x.image,run:t=>t.openImageDialog(),active:t=>!!We(t)},file:{type:"button",label:"file",icon:x.file,run:t=>t.openFileManager("file"),available:t=>t.hasFileManager()},video:{type:"button",label:"video",icon:x.video,run:t=>t.openVideoDialog(),active:t=>!!It(t)},find:{type:"button",label:"findReplace",icon:x.search,shortcut:"Mod+F",run:t=>t.openFind(),active:(t,e)=>e.isFindOpen()},table:{type:"button",label:"table",icon:x.table,popup:!0,run:(t,e)=>t.openTableMenu(e),active:t=>R.isInTable(t)},blockquote:{type:"button",label:"blockquote",icon:x.blockquote,run:B(Nn()),active:t=>Et(t,f.nodes.blockquote)},bulletList:{type:"button",label:"bulletList",icon:x.bulletList,run:B(Tt(f.nodes.bullet_list)),active:t=>At(t)===f.nodes.bullet_list},orderedList:{type:"button",label:"orderedList",icon:x.orderedList,run:B(Tt(f.nodes.ordered_list)),active:t=>At(t)===f.nodes.ordered_list},outdent:{type:"button",label:"outdent",icon:x.outdent,run:B(Fe),enabled:t=>Fe(t)},indent:{type:"button",label:"indent",icon:x.indent,run:B(ze),enabled:t=>ze(t)},alignLeft:Ie("left"),alignCenter:Ie("center"),alignRight:Ie("right"),alignJustify:Ie("justify"),hr:{type:"button",label:"hr",icon:x.hr,run:B(On)},clear:{type:"button",label:"clear",icon:x.clear,run:B($n)},pasteText:{type:"button",label:"pasteText",icon:x.pasteText,run:t=>t.togglePlainPaste(),active:(t,e)=>e.isPlainPaste()},source:{type:"button",label:"source",icon:x.source,run:t=>t.toggleSource(),active:(t,e)=>e.isSourceMode(),inSource:!0},fullscreen:{type:"button",label:"fullscreen",icon:x.fullscreen,run:t=>t.toggleFullscreen(),active:(t,e)=>e.isFullscreen(),inSource:!0}},Ot=["undo","redo","|","blocks","|","bold","italic","underline","strike","code","textColor","highlight","|","link","image","file","video","table","blockquote","bulletList","orderedList","outdent","indent","|","alignLeft","alignCenter","alignRight","alignJustify","|","hr","clear","pasteText","|","source","fullscreen"],Xn=[["paragraph","paragraph"],["heading1","heading1"],["heading2","heading2"],["heading3","heading3"],["heading4","heading4"],["codeBlock","codeBlock"]],Qn=typeof navigator<"u"&&/Mac|iP(hone|ad|od)/.test(navigator.platform||navigator.userAgent),Zn=t=>t.replace("Mod",Qn?"⌘":"Ctrl");function ei(t,e,n){const i=document.createElement("div");i.className="wds-toolbar",i.setAttribute("role","toolbar"),i.setAttribute("aria-label",n.toolbarLabel);const r=[];let s=document.createElement("div");s.className="wds-group",i.append(s);for(const c of e){if(c==="|"){s.childElementCount&&(s=document.createElement("div"),s.className="wds-group",i.append(s));continue}const a=Rt[c];if(!a){console.warn(`[WDS Editor] Unknown toolbar item "${c}".`);continue}if(a.type==="blocks"){const u=document.createElement("select");u.className="wds-select",u.setAttribute("aria-label",n.blockType),u.title=n.blockType;for(const[m,b]of Xn){const L=document.createElement("option");L.value=m,L.textContent=n[b],u.append(L)}const p=document.createElement("option");p.value="",p.textContent="—",p.hidden=!0,u.append(p),u.addEventListener("change",()=>{u.value&&t.exec(Dn(u.value)),t.focus()}),s.append(u),r.push(m=>{u.value=In(m)??"",u.disabled=t.isSourceMode()||t.isReadOnly()});continue}if(a.available&&!a.available(t))continue;const l=document.createElement("button");l.type="button",l.className="wds-button-tool",l.innerHTML=a.icon;const d=n[a.label];l.setAttribute("aria-label",d),l.title=a.shortcut?`${d} (${Zn(a.shortcut)})`:d,l.dataset.item=c,a.popup&&(l.setAttribute("aria-haspopup","true"),l.setAttribute("aria-expanded","false")),l.addEventListener("mousedown",u=>u.preventDefault()),l.addEventListener("click",()=>{l.disabled||a.run(t,l)}),s.append(l),r.push(u=>{const p=t.isSourceMode()&&!a.inSource||t.isReadOnly()&&!a.inSource;if(l.disabled=p||(a.enabled?!a.enabled(u,t):!1),a.swatch){const m=p?null:a.swatch(u);m?l.style.setProperty("--wds-swatch",m):l.style.removeProperty("--wds-swatch")}if(a.active){const m=!p&&a.active(u,t);l.classList.toggle("is-active",m),l.setAttribute("aria-pressed",String(m))}})}return i.addEventListener("keydown",c=>{if(c.key!=="ArrowRight"&&c.key!=="ArrowLeft"&&c.key!=="Home"&&c.key!=="End"||c.target.tagName==="SELECT"&&(c.key==="Home"||c.key==="End"))return;const a=[...i.querySelectorAll("button:not([disabled]), select:not([disabled])")],l=a.indexOf(document.activeElement);if(l<0)return;c.preventDefault();const d=c.key==="Home"?0:c.key==="End"?a.length-1:(l+(c.key==="ArrowRight"!==ce(i)?1:-1)+a.length)%a.length;a.forEach(u=>u.tabIndex=-1),a[d].tabIndex=0,a[d].focus()}),{element:i,update:c=>{r.forEach(l=>l(c));const a=[...i.querySelectorAll("button, select")];if(!a.some(l=>l.tabIndex===0&&!l.disabled)){a.forEach(d=>d.tabIndex=-1);const l=a.find(d=>!d.disabled);l&&(l.tabIndex=0)}}}}function $t(t,e,n,i){const r=document.createElement("span");r.className="wds-image";const s=document.createElement("img");s.draggable=!1;const o=document.createElement("span");o.className="wds-resize-handle",o.title=i.resizeLabel,o.setAttribute("aria-hidden","true"),r.append(s,o);const c=()=>{const d=e();d!==void 0&&t.dispatch(t.state.tr.setSelection(N.NodeSelection.create(t.state.doc,d)))};let a=!1;return o.addEventListener("pointerdown",d=>{if(!t.editable)return;d.preventDefault(),d.stopPropagation(),c(),a=!0;try{o.setPointerCapture(d.pointerId)}catch{}const u=d.clientX,p=s.getBoundingClientRect().width,m=Math.max(40,t.dom.clientWidth-8);let b=p;const L=A=>{b=Math.round(Math.min(m,Math.max(40,p+A.clientX-u))),s.style.width=`${b}px`,s.style.height="auto",r.dataset.size=`${b}px`},T=()=>{a=!1,window.removeEventListener("pointermove",L),window.removeEventListener("pointerup",T),window.removeEventListener("pointercancel",T),delete r.dataset.size,s.style.width="",s.style.height="";const A=e();if(A===void 0||Math.abs(b-p)<2)return;const $=n(),v=t.state.tr.setNodeMarkup(A,void 0,{...$.attrs,width:b,height:null});t.dispatch(v.setSelection(N.NodeSelection.create(v.doc,A)))};window.addEventListener("pointermove",L),window.addEventListener("pointerup",T),window.addEventListener("pointercancel",T)}),r.addEventListener("dblclick",d=>{if(!t.editable)return;d.preventDefault(),c();const u=e();u!==void 0&&i.onEdit(u)}),{box:r,img:s,handle:o,select:c,render:d=>{const u=Pe(d.attrs,!1);for(const p of["src","alt","title","width","height"])u[p]!==void 0?s.setAttribute(p,u[p]):s.removeAttribute(p)},isResizing:()=>a}}const Pt=(t,e)=>{t.classList.remove("wds-align-left","wds-align-center","wds-align-right"),e&&t.classList.add(`wds-align-${e}`)};class ti{constructor(e,n,i,r){this.node=e,this.parts=$t(n,i,()=>this.node,r),this.dom=this.parts.box,this.render()}render(){this.parts.render(this.node),Pt(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 ni{constructor(e,n,i,r){this.node=e,this.dom=document.createElement("figure"),this.dom.className="wds-figure",this.parts=$t(n,i,()=>this.node,r),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=r.captionPlaceholder,this.dom.append(this.parts.box,this.contentDOM),this.render()}render(){this.parts.render(this.node),Pt(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 we={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",video:"Video",videoEdit:"Edit video",videoUrl:"YouTube or Vimeo address",videoHint:"Paste the link of the video page or its embed code.",videoTitle:"Title (read by screen readers)",videoInvalid:"Enter a YouTube or Vimeo video address.",findReplace:"Find and replace",find:"Find",replaceWith:"Replace with",findNext:"Next match",findPrevious:"Previous match",replace:"Replace",replaceAll:"Replace all",matchCase:"Match case",matchCount:"{current} of {total}",noMatches:"No results",replacedCount:"{count} replaced",draftFound:"An unsaved draft from {time} was found.",draftRestore:"Restore draft",draftDiscard:"Discard"},Ht={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",video:"Video",videoEdit:"Videoyu düzenle",videoUrl:"YouTube veya Vimeo adresi",videoHint:"Video sayfasının bağlantısını ya da yerleştirme kodunu yapıştırın.",videoTitle:"Başlık (ekran okuyucular okur)",videoInvalid:"Bir YouTube veya Vimeo video adresi girin.",findReplace:"Bul ve değiştir",find:"Bul",replaceWith:"Şununla değiştir",findNext:"Sonraki eşleşme",findPrevious:"Önceki eşleşme",replace:"Değiştir",replaceAll:"Tümünü değiştir",matchCase:"Büyük/küçük harf duyarlı",matchCount:"{current} / {total}",noMatches:"Sonuç yok",replacedCount:"{count} yer değiştirildi",draftFound:"{time} tarihli kaydedilmemiş bir taslak bulundu.",draftRestore:"Taslağı geri yükle",draftDiscard:"Sil"},ye={en:we,tr:Ht};function Ge(t,e){ye[t.toLowerCase()]={...we,...ye[t.toLowerCase()],...e}}function Bt(t){return globalThis.WDSEditorLang?.[t]}function zt(t){return!ye[t]&&Bt(t)&&Ge(t,Bt(t)),ye[t]}function Ft(t){const e=(t||(typeof navigator<"u"?navigator.language:"en")||"en").toLowerCase();if(zt(e))return e;const n=e.split("-")[0];return zt(n)?n:"en"}function ii(t){return t&&typeof t=="object"?{...we,...t}:ye[Ft(t)]??we}const ri=new Set(["ar","he","fa","ur","ps","yi","dv","ckb"]);function si(t){return ri.has(t.toLowerCase().split("-")[0])}function F(t,e){return t.replace(/\{(\w+)\}/g,(n,i)=>i in e?String(e[i]):n)}let oi=0;function je(t,e){const n=`wds-dlg-${++oi}`,i=document.createElement("dialog");i.className="wds-dialog",i.setAttribute("aria-labelledby",`${n}-title`);const r=document.createElement("form");r.method="dialog",r.noValidate=!0;const s=document.createElement("div");s.className="wds-dialog-header";const o=document.createElement("h2");o.id=`${n}-title`,o.textContent=e.title;const c=document.createElement("button");c.type="button",c.className="wds-icon-button",c.setAttribute("aria-label",e.closeLabel),c.innerHTML=x.close,s.append(o,c);const a=document.createElement("div");a.className="wds-dialog-body";const l=new Map;for(const v of e.fields){if(v.type==="select"){const I=document.createElement("select");I.id=`${n}-${v.name}`,I.name=v.name,I.className="wds-input";for(const H of v.options??[]){const te=document.createElement("option");te.value=H.value,te.textContent=H.label,I.append(te)}I.value=typeof v.value=="string"?v.value:"";const P=document.createElement("label");P.className="wds-label",P.htmlFor=I.id,P.textContent=v.label,a.append(P,I),l.set(v.name,I);continue}const E=document.createElement("input");if(E.id=`${n}-${v.name}`,E.name=v.name,v.type==="checkbox"){E.type="checkbox",E.checked=!!v.value;const I=document.createElement("label");I.className="wds-check",I.htmlFor=E.id,I.append(E,document.createTextNode(v.label)),a.append(I)}else{E.type="text",v.type==="url"&&(E.inputMode="url"),v.type==="number"&&(E.inputMode="numeric"),E.className="wds-input",E.value=typeof v.value=="string"?v.value:"",E.autocomplete="off",E.spellcheck=!1,v.placeholder&&(E.placeholder=v.placeholder);const I=document.createElement("label");if(I.className="wds-label",I.htmlFor=E.id,I.textContent=v.label,a.append(I,E),v.hint){const P=document.createElement("p");P.className="wds-hint",P.id=`${E.id}-hint`,P.textContent=v.hint,E.setAttribute("aria-describedby",P.id),a.append(P)}}l.set(v.name,E)}const d=document.createElement("p");d.className="wds-dialog-error",d.setAttribute("role","alert"),d.hidden=!0,a.append(d);const u=document.createElement("div");if(u.className="wds-dialog-footer",e.extraAction){const v=document.createElement("button");v.type="button",v.className="wds-button wds-button-danger",v.textContent=e.extraAction.label,v.addEventListener("click",()=>{e.extraAction.onClick(),A()}),u.append(v)}const p=document.createElement("span");p.className="wds-spacer";const m=document.createElement("button");m.type="button",m.className="wds-button",m.textContent=e.cancelLabel;const b=document.createElement("button");b.type="submit",b.className="wds-button wds-button-primary",b.textContent=e.submitLabel,u.append(p,m,b),r.append(s,a,u),i.append(r),t.append(i);const L=()=>{const v={};return l.forEach((E,I)=>v[I]=E instanceof HTMLInputElement&&E.type==="checkbox"?E.checked:E.value),v};let T=!1;function A(){T||(T=!0,i.open&&i.close(),i.remove(),e.onClose?.())}r.addEventListener("submit",v=>{v.preventDefault();const E=L(),I=e.validate?.(E)??null;if(I){d.textContent=I,d.hidden=!1,[...l.values()][0]?.focus();return}e.onSubmit(E),A()}),m.addEventListener("click",A),c.addEventListener("click",A),i.addEventListener("close",A),i.addEventListener("click",v=>{v.target===i&&A()}),i.showModal();const $=[...l.values()].find(v=>v instanceof HTMLInputElement&&v.type!=="checkbox");return $?.focus(),$?.select(),A}const ee=t=>typeof t=="string"&&t.trim()?t:void 0,Ke=t=>typeof t=="number"&&Number.isFinite(t)&&t>=0?t:void 0;function Ut(t){if(!t||typeof t!="object")return null;const e=t,n=K(ee(e.url)),i=ee(e.name);if(!n||!i)return null;const r={url:n,name:i},s=Ke(e.size),o=Ke(e.width),c=Ke(e.height);s!==void 0&&(r.size=s),o!==void 0&&(r.width=o),c!==void 0&&(r.height=c),ee(e.type)&&(r.type=e.type.toLowerCase());const a=K(ee(e.thumb));return a&&(r.thumb=a),ee(e.modified)&&!Number.isNaN(Date.parse(e.modified))&&(r.modified=e.modified),r}function Wt(t,e="/"){const n=Array.isArray(t)?{files:t}:t&&typeof t=="object"?t:{},i=(Array.isArray(n.files)?n.files:[]).map(Ut).filter(s=>!!s),r=(Array.isArray(n.folders)?n.folders:[]).map(s=>s&&typeof s=="object"?s:{}).filter(s=>ee(s.name)&&ee(s.path)).map(s=>({name:s.name,path:Ye(s.path)}));return{path:Ye(ee(n.path)??e),folders:r,files:i,hasMore:n.hasMore===!0,serverSearch:typeof n.q=="string"}}function Ye(t){return"/"+t.split("/").filter(n=>n&&n!=="."&&n!=="..").join("/")}const ai=/\.(jpe?g|png|gif|webp|avif|svg|bmp|ico)$/i,li={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"},_t=t=>(/\.([a-z0-9]+)$/i.exec(t)?.[1]??"").toLowerCase();function qt(t){return t.type||li[_t(t.name)]||""}function de(t){const e=qt(t);return e?e.startsWith("image/"):ai.test(t.url??t.name)}function Je(t,e){if(!e||!e.trim())return!0;const n=qt(t),i="."+_t(t.name);return e.split(",").some(r=>{const s=r.trim().toLowerCase();return s?s.startsWith(".")?i===s:s.endsWith("/*")?n.startsWith(s.slice(0,-1)):n===s:!1})}function Vt(t){if(t===void 0)return"";if(t<1024)return`${t} B`;const e=["KB","MB","GB"];let n=t/1024,i=0;for(;n>=1024&&i<e.length-1;)n/=1024,i++;return`${n<10?n.toFixed(1):Math.round(n)} ${e[i]}`}class z extends Error{constructor(e,n){super(e),this.code=n}}async function Gt(t){try{const e=await t.clone().json();if(e&&typeof e.error=="string")return e.error}catch{}return`HTTP ${t.status}`}function ci(t,e){const n=new URL(t,document.baseURI);for(const[i,r]of Object.entries(e))r&&n.searchParams.set(i,r);return n.href}class di{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,i,r){const s=ci(this.options.listUrl,{path:e,q:n,page:i>1?String(i):""});let o;try{o=await fetch(s,{...this.init(),signal:r})}catch(a){throw a.name==="AbortError"?a:new z(a.message||"Network error","network")}if(!o.ok)throw new z(await Gt(o));let c;try{c=await o.json()}catch{throw new z("Invalid JSON","response")}return Wt(c,e)}upload(e,n,i){const{uploadUrl:r,headers:s={},withCredentials:o}=this.options;return r?new Promise((c,a)=>{const l=new XMLHttpRequest;l.open("POST",new URL(r,document.baseURI).href),l.withCredentials=!!o,l.setRequestHeader("Accept","application/json");for(const[u,p]of Object.entries(s))l.setRequestHeader(u,p);l.upload.onprogress=u=>u.lengthComputable&&i?.(u.loaded/u.total),l.onerror=()=>a(new z("Network error","network")),l.onload=()=>{let u=null;try{u=JSON.parse(l.responseText)}catch{}if(l.status<200||l.status>=300){a(new z(typeof u?.error=="string"?u.error:`HTTP ${l.status}`));return}const p=Ut(u?.file);p?c(p):a(new z("Invalid upload response","response"))};const d=new FormData;d.append("file",e,e.name),d.append("path",n),l.send(d)}):Promise.reject(new z("Upload is not configured"))}async remove(e){const{deleteUrl:n}=this.options;if(!n)throw new z("Delete is not configured");let i;try{i=await fetch(new URL(n,document.baseURI).href,this.init({method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({url:e})}))}catch(r){throw new z(r.message||"Network error","network")}if(!i.ok)throw new z(await Gt(i))}}function Xe(t,e){return t instanceof z&&t.code==="network"?e.fmNetworkError:t instanceof z&&t.code==="response"?e.fmInvalidResponse:t?.message??""}const w=(t,e,n)=>{const i=document.createElement(t);return e&&(i.className=e),n!==void 0&&(i.textContent=n),i},Qe=(t,e,n="wds-icon-button")=>{const i=w("button",n);return i.type="button",i.innerHTML=t,i.setAttribute("aria-label",e),i.title=e,i},ui=[["","alignNone"],["left","alignLeftShort"],["center","alignCenterShort"],["right","alignRightShort"]];class hi{constructor(e,n,i){this.host=e,this.api=n,this.t=i,this.path="/",this.view="grid",this.sort="newest"}open(e){const n=this.t,i=e.accept??"";let r=[],s=[],o=1,c=!1,a=!1,l="",d=null,u=null,p=0,m=!1;const b=w("dialog","wds-dialog wds-fm");b.setAttribute("aria-labelledby","wds-fm-title");const L=w("div","wds-dialog-header"),T=w("h2",void 0,n.fmTitle);T.id="wds-fm-title";const A=Qe(x.close,n.close);L.append(T,A);const $=w("div","wds-fm-bar"),v=w("nav","wds-fm-crumbs");v.setAttribute("aria-label",n.fmBreadcrumb);const E=w("input","wds-input wds-fm-search");E.type="search",E.placeholder=n.fmSearch,E.setAttribute("aria-label",n.fmSearch);const I=w("select","wds-input wds-fm-sort");I.setAttribute("aria-label",n.fmSort),I.title=n.fmSort;for(const[h,g]of[["newest","fmSortNewest"],["name","fmSortName"],["largest","fmSortLargest"]]){const M=w("option",void 0,n[g]);M.value=h,I.append(M)}I.value=this.sort;const P=Qe(this.view==="grid"?x.list:x.grid,this.view==="grid"?n.fmList:n.fmGrid),H=w("input");H.type="file",H.multiple=!0,H.hidden=!0,i&&(H.accept=i);const te=w("button","wds-button wds-button-primary wds-fm-upload");te.type="button",te.innerHTML=`${x.upload}<span>${Ze(n.fmUpload)}</span>`;const rt=w("div","wds-fm-tools");rt.append(E,I,P),this.api.canUpload&&rt.append(te,H),$.append(v,rt);const Zt=w("div","wds-fm-main"),J=w("div","wds-fm-browser"),st=w("div","wds-fm-uploads"),V=w("ul",`wds-fm-items is-${this.view}`);V.setAttribute("aria-label",n.fmTitle);const O=w("p","wds-fm-status");O.setAttribute("role","status");const pe=w("button","wds-button",n.fmRetry);pe.type="button",pe.hidden=!0;const me=w("button","wds-button wds-fm-more",n.fmLoadMore);me.type="button",me.hidden=!0;const en=w("div","wds-fm-drop",n.fmDrop);en.setAttribute("aria-hidden","true"),J.append(st,V,O,pe,me,en);const G=w("aside","wds-fm-details");G.setAttribute("aria-label",n.imageEdit),Zt.append(J,G);const ot=w("div","wds-dialog-footer");if(e.onFromUrl){const h=w("button","wds-button wds-fm-fromurl");h.type="button",h.innerHTML=`${x.globe}<span>${Ze(n.fmFromUrl)}</span>`,h.addEventListener("click",()=>{oe(),e.onFromUrl()}),ot.append(h)}const at=w("button","wds-button",n.cancel);at.type="button";const ke=w("button","wds-button wds-button-primary",n.insert);ke.type="button",ke.disabled=!0,ot.append(w("span","wds-spacer"),at,ke),b.append(L,$,Zt,ot),this.host.append(b);let Me=null,j=null,xe=null,re=null,Le=null;const De=(h,g,M,y)=>{g.id=M;const C=w("label","wds-label",h);if(C.htmlFor=M,G.append(C,g),y){const k=w("p","wds-hint",y);k.id=`${M}-hint`,g.setAttribute("aria-describedby",k.id),G.append(k)}},Ne=()=>{if(G.replaceChildren(),Me=j=Le=re=null,xe=null,ke.disabled=!d,!d){G.append(w("p","wds-fm-placeholder",n.fmNoSelection));return}const h=d,g=w("div","wds-fm-preview"),M=w("p","wds-fm-filename",h.name),y=w("p","wds-fm-facts"),C=()=>[h.width&&h.height?`${h.width} × ${h.height}`:"",Vt(h.size),h.modified?new Date(h.modified).toLocaleDateString():""].filter(Boolean).join(" · ");if(y.textContent=C(),de(h)){const k=w("img");k.alt="",!h.thumb&&!(h.width&&h.height)&&k.addEventListener("load",()=>{!k.naturalWidth||d!==h||(h.width=k.naturalWidth,h.height=k.naturalHeight,y.textContent=C(),j&&!j.placeholder&&(j.placeholder=String(h.width)))},{once:!0}),k.src=h.thumb??h.url,g.append(k)}else g.innerHTML=x.file;if(G.append(g,M,y),e.mode==="image"&&de(h)){Me=w("input","wds-input"),Me.value=h.name.replace(/\.[a-z0-9]+$/i,"").replace(/[-_]+/g," "),De(n.imageAlt,Me,"wds-fm-alt",n.imageAltHint),j=w("input","wds-input"),j.inputMode="numeric",j.placeholder=h.width?String(h.width):"",De(n.imageWidth,j,"wds-fm-width"),xe=w("select","wds-input");for(const[U,W]of ui){const ge=w("option",void 0,n[W]);ge.value=U,xe.append(ge)}De(n.imageAlign,xe,"wds-fm-align"),re=w("input"),re.type="checkbox",re.id="wds-fm-caption";const k=w("label","wds-check");k.htmlFor=re.id,k.append(re,document.createTextNode(n.caption)),G.append(k)}else Le=w("input","wds-input"),Le.value=h.name,De(n.fmLinkText,Le,"wds-fm-text");if(this.api.canDelete){const k=w("button","wds-button wds-button-danger wds-fm-delete");k.type="button",k.innerHTML=`${x.trash}<span>${Ze(n.fmDelete)}</span>`,k.addEventListener("click",()=>Ii(h)),G.append(k)}},Ci=()=>{const h=l.trim().toLocaleLowerCase(),g=r.filter(y=>Je(y,i)&&(a||!h||y.name.toLocaleLowerCase().includes(h))),M=y=>y.modified?Date.parse(y.modified):-1/0;return this.sort==="name"?g.sort((y,C)=>y.name.localeCompare(C.name,void 0,{numeric:!0,sensitivity:"base"})):this.sort==="largest"?g.sort((y,C)=>(C.size??-1)-(y.size??-1)):g.sort((y,C)=>M(C)-M(y)),g},lt=()=>{v.replaceChildren();const h=this.path.split("/").filter(Boolean),g=[[n.fmRoot,"/"],...h.map((M,y)=>[M,"/"+h.slice(0,y+1).join("/")])];g.forEach(([M,y],C)=>{if(C&&v.append(w("span","wds-fm-sep","/")),C===g.length-1){const k=w("span","wds-fm-crumb is-current",M);k.setAttribute("aria-current","location"),v.append(k)}else{const k=w("button","wds-fm-crumb",M);k.type="button",k.addEventListener("click",()=>rn(y)),v.append(k)}})},se=()=>{V.className=`wds-fm-items is-${this.view}`,V.replaceChildren();const h=!l.trim();if(h)for(const y of s){const C=nn(x.folder,y.name,n.fmFolder,!0);C.addEventListener("click",()=>rn(y.path)),V.append(tn(C))}const g=Ci();for(const y of g){const C=de(y)?y.thumb??y.url:null,k=nn(C?"":x.file,y.name,[Vt(y.size),y.width&&y.height?`${y.width}×${y.height}`:""].filter(Boolean).join(" · "),!1);if(C){const W=w("img");W.loading="lazy",W.decoding="async",W.alt="",W.src=C,k.querySelector(".wds-fm-thumb").append(W)}k.dataset.url=y.url;const U=d?.url===y.url;k.classList.toggle("is-selected",U),k.setAttribute("aria-pressed",String(U)),k.addEventListener("click",()=>ct(y)),k.addEventListener("dblclick",()=>{ct(y),dt()}),V.append(tn(k))}const M=!g.length&&!(h&&s.length);!O.dataset.busy&&!O.dataset.error&&(O.textContent=M?l.trim()?n.fmNoResults:n.fmEmpty:""),me.hidden=!c||!!O.dataset.busy},tn=h=>{const g=w("li");return g.append(h),g},nn=(h,g,M,y)=>{const C=w("button",`wds-fm-item${y?" is-folder":""}`);C.type="button";const k=w("span","wds-fm-thumb");k.innerHTML=h;const U=w("span","wds-fm-name",g);U.title=g;const W=w("span","wds-fm-meta",M);return C.append(k,U,W),C},ct=h=>{d=h,V.querySelectorAll(".wds-fm-item[data-url]").forEach(g=>{const M=g.dataset.url===h.url;g.classList.toggle("is-selected",M),g.setAttribute("aria-pressed",String(M))}),Ne()},Se=async h=>{u?.abort(),u=new AbortController,h&&(o=1,r=[],s=[]),O.dataset.busy="1",delete O.dataset.error,O.textContent=n.fmLoading,pe.hidden=!0,me.hidden=!0,h&&se();try{const g=await this.api.list(this.path,l.trim(),o,u.signal);if(m)return;this.path=g.path,a=g.serverSearch,c=g.hasMore,s=h?g.folders:s;const M=new Set(r.map(y=>y.url));r=[...r,...g.files.filter(y=>!M.has(y.url))],delete O.dataset.busy,O.textContent="",lt(),se()}catch(g){if(g.name==="AbortError"||m)return;delete O.dataset.busy,O.dataset.error="1",O.textContent=F(n.fmListFailed,{error:Xe(g,n)}),O.setAttribute("role","alert"),pe.hidden=!1}},rn=h=>{this.path=Ye(h),l="",E.value="",d=null,Ne(),lt(),Se(!0).then(()=>V.querySelector(".wds-fm-item")?.focus())},sn=h=>{for(const g of Array.from(h)){const M=w("div","wds-fm-upload-row"),y=w("span","wds-fm-upload-name",F(n.fmUploading,{name:g.name}));if(!Je(g,i)){on(M,F(n.fmNotAllowed,{name:g.name})),st.append(M);continue}const C=w("progress");C.max=1,C.value=0,M.append(y,C),st.append(M),this.api.upload(g,this.path,k=>C.value=k).then(k=>{m||(M.remove(),r=[k,...r.filter(U=>U.url!==k.url)],se(),ct(k),e.onUpload?.(k))}).catch(k=>{m||(M.replaceChildren(),on(M,F(n.fmUploadFailed,{name:g.name,error:Xe(k,n)})))})}},on=(h,g)=>{h.classList.add("is-error");const M=w("span","wds-fm-upload-name",g);M.setAttribute("role","alert");const y=Qe(x.close,n.close);y.addEventListener("click",()=>h.remove()),h.append(M,y)},Ii=async h=>{if(window.confirm(F(n.fmDeleteConfirm,{name:h.name})))try{await this.api.remove(h.url),r=r.filter(g=>g.url!==h.url),d=null,Ne(),se()}catch(g){O.dataset.error="1",O.setAttribute("role","alert"),O.textContent=F(n.fmDeleteFailed,{error:Xe(g,n)})}},dt=()=>{if(!d)return;const h=j?parseInt(j.value,10):NaN;e.onPick({file:d,alt:Me?.value.trim()??"",width:Number.isFinite(h)&&h>0?h:null,align:xe?.value||null,text:Le?.value.trim()||d.name,caption:!!re?.checked}),oe()};function oe(){m||(m=!0,u?.abort(),window.clearTimeout(p),b.open&&b.close(),b.remove(),e.onClose?.())}if(A.addEventListener("click",oe),at.addEventListener("click",oe),ke.addEventListener("click",dt),b.addEventListener("close",oe),b.addEventListener("click",h=>h.target===b&&oe()),pe.addEventListener("click",()=>{O.setAttribute("role","status"),Se(!0)}),me.addEventListener("click",()=>{o++,Se(!1)}),I.addEventListener("change",()=>{this.sort=I.value,se()}),P.addEventListener("click",()=>{this.view=this.view==="grid"?"list":"grid",P.innerHTML=this.view==="grid"?x.list:x.grid;const h=this.view==="grid"?n.fmList:n.fmGrid;P.setAttribute("aria-label",h),P.title=h,se()}),E.addEventListener("input",()=>{window.clearTimeout(p),p=window.setTimeout(()=>{l=E.value,!a&&!c?se():Se(!0)},250)}),te.addEventListener("click",()=>H.click()),H.addEventListener("change",()=>{H.files?.length&&sn(H.files),H.value=""}),this.api.canUpload){let h=0;J.addEventListener("dragenter",g=>{g.dataTransfer?.types.includes("Files")&&(h++,J.classList.add("is-dragging"))}),J.addEventListener("dragleave",()=>{h=Math.max(0,h-1),h||J.classList.remove("is-dragging")}),J.addEventListener("dragover",g=>{g.dataTransfer?.types.includes("Files")&&g.preventDefault()}),J.addEventListener("drop",g=>{g.preventDefault(),h=0,J.classList.remove("is-dragging"),g.dataTransfer?.files.length&&sn(g.dataTransfer.files)})}return V.addEventListener("keydown",h=>{if(!["ArrowRight","ArrowLeft","ArrowDown","ArrowUp","Home","End"].includes(h.key))return;const M=[...V.querySelectorAll(".wds-fm-item")],y=M.indexOf(document.activeElement);if(y<0)return;h.preventDefault();const C=M[0].offsetTop,k=this.view==="list"?1:Math.max(1,M.findIndex(ge=>ge.offsetTop!==C)===-1?M.length:M.findIndex(ge=>ge.offsetTop!==C)),U={ArrowRight:1,ArrowLeft:-1,ArrowDown:k,ArrowUp:-k},W=h.key==="Home"?0:h.key==="End"?M.length-1:Math.min(M.length-1,Math.max(0,y+U[h.key]));M[W].focus()}),G.addEventListener("keydown",h=>{h.key==="Enter"&&h.target.tagName==="INPUT"&&(h.preventDefault(),dt())}),lt(),Ne(),b.showModal(),E.focus(),Se(!0),oe}}function Ze(t){const e=document.createElement("span");return e.textContent=t,e.innerHTML}const jt=new Map;let fi=0;function pi(t){const e=[];let n=0,i="",r="";for(let s=0;s<t.length;s++){const o=t[s];if(i){if(o==="\\"){r+=o+(t[++s]??"");continue}o===i&&(i="")}else if(o==='"'||o==="'")i=o;else if(o==="("||o==="[")n++;else if(o===")"||o==="]")n--;else if(o===","&&n===0){e.push(r.trim()),r="";continue}r+=o}return r.trim()&&e.push(r.trim()),e}const et=/^(?::root|:host|html|body)(?![\w-])((?:\[[^\]]*\]|[.:#][\w-]+(?:\([^)]*\))?)*)/i;function mi(t,e){return pi(t).map(n=>{let i=n,r=!1,s="";for(let c=i.match(et);c;c=i.match(et)){r=!0,s=c[1]??"",i=i.slice(c[0].length).trimStart();const a=i.replace(/^>\s*/,"");a!==i&&et.test(a)&&(i=a)}if(!r)return`${e} ${n}`;const o=e+s;return i?`${o} ${i}`:o}).join(", ")}function Kt(t,e){for(const n of Array.from(t))if("selectorText"in n&&typeof n.selectorText=="string"){const i=n;i.selectorText=mi(i.selectorText,e)}else"cssRules"in n&&!("name"in n&&"appendRule"in n)&&Kt(n.cssRules,e)}function Yt(t){const e=typeof CSSLayerBlockRule<"u";for(let n=0;n<t.cssRules.length;n++){const i=t.cssRules[n];if(e&&i instanceof CSSLayerStatementRule)t.deleteRule(n--);else if(e&&i instanceof CSSLayerBlockRule){const r=Array.from(i.cssRules,s=>s.cssText);t.deleteRule(n),r.forEach((s,o)=>{try{t.insertRule(s,n+o)}catch{}}),n--}else typeof CSSGroupingRule<"u"&&i instanceof CSSGroupingRule&&Yt(i)}}const gi=()=>typeof CSSStyleSheet<"u"&&"replaceSync"in CSSStyleSheet.prototype&&"adoptedStyleSheets"in document;async function bi(t,e){const n=`:where(.${e})`,i=t.css===void 0?[]:Array.isArray(t.css)?t.css:[t.css],r=await Promise.all(i.map(async o=>{const c=new URL(o,document.baseURI).href;try{const a=await fetch(c,{credentials:"same-origin"});if(!a.ok)throw new Error(`HTTP ${a.status}`);return{text:await a.text(),baseURL:c}}catch(a){return console.warn(`[WDS Editor] contentCss could not be loaded: ${c}`,a),null}}));t.style&&r.push({text:t.style,baseURL:document.baseURI});const s=[];for(const o of r){if(!o)continue;const c=new CSSStyleSheet({baseURL:o.baseURL});c.replaceSync(o.text.replace(/@import[^;]*;/g,"")),Yt(c),Kt(c.cssRules,n),s.push(c)}document.adoptedStyleSheets=[...document.adoptedStyleSheets,...s]}function wi(t){if(!t.css?.length&&!t.style)return null;if(!gi())return console.warn("[WDS Editor] contentCss needs constructable stylesheets (all current browsers)."),null;const e=JSON.stringify([t.css,t.style??""]);let n=jt.get(e);if(!n){const i=`wds-site-${++fi}`;n={className:i,ready:bi(t,i)},jt.set(e,n)}return n}const Y=new N.PluginKey("wds-find");function yi(t,e,n){const i=[];if(!e)return i;const r=n?e:e.toLowerCase();return t.descendants((s,o)=>{if(!s.isTextblock)return!0;let c="";s.forEach(l=>{c+=l.isText?l.text:"".repeat(l.nodeSize)});const a=n?c:c.toLowerCase();for(let l=a.indexOf(r);l>=0;l=a.indexOf(r,l+r.length))i.push({from:o+1+l,to:o+1+l+r.length});return!1}),i}function vi(t,e){if(!t.length)return-1;const n=t.findIndex(i=>i.to>e);return n<0?0:n}function ki(){return new N.Plugin({key:Y,state:{init:()=>({query:"",caseSensitive:!1,matches:[],current:-1}),apply(t,e,n,i){const r=t.getMeta(Y);if(!r&&!t.docChanged)return e;const s=r?.query??e.query,o=r?.caseSensitive??e.caseSensitive,c=yi(i.doc,s,o);let a=r?.current??(r?.query!==void 0||r?.caseSensitive!==void 0?vi(c,i.selection.from):e.current);return a>=c.length&&(a=c.length?0:-1),a<0&&c.length&&(a=0),{query:s,caseSensitive:o,matches:c,current:a}}},props:{decorations(t){const e=Y.getState(t);return e?.matches.length?ne.DecorationSet.create(t.doc,e.matches.map((n,i)=>ne.Decoration.inline(n.from,n.to,{class:i===e.current?"wds-find-match wds-find-current":"wds-find-match"}))):null}}})}const ue=t=>Y.getState(t);function tt(t,e){const n=ue(t.state);if(!n.matches.length)return;const i=(n.current+e+n.matches.length)%n.matches.length,r=n.matches[i];t.dispatch(t.state.tr.setMeta(Y,{current:i}).setSelection(N.TextSelection.create(t.state.doc,r.from,r.to)).scrollIntoView())}function Jt(t,e,n){n?t.insertText(n,e.from,e.to):t.delete(e.from,e.to)}function Xt(t,e){const n=ue(t.state),i=n.matches[n.current];if(!i)return;const r=t.state.tr;Jt(r,i,e),r.setMeta(Y,{current:n.current}),t.dispatch(r.scrollIntoView());const s=ue(t.state).matches[ue(t.state).current];s&&t.dispatch(t.state.tr.setSelection(N.TextSelection.create(t.state.doc,s.from,s.to)).scrollIntoView())}function Mi(t,e){const{matches:n}=ue(t.state);if(!n.length)return 0;const i=t.state.tr;for(let r=n.length-1;r>=0;r--)Jt(i,n[r],e);return t.dispatch(i.scrollIntoView()),n.length}function nt(t,e){const n=document.createElement("button");return n.type="button",n.className="wds-icon-button",n.innerHTML=t,n.setAttribute("aria-label",e),n.title=e,n}class xi{constructor(e,n,i){this.view=e,this.t=n,this.onClose=i;const r=this.element=document.createElement("div");r.className="wds-find",r.setAttribute("role","search"),r.hidden=!0;const s=(L,T)=>{const A=document.createElement("input");return A.type="text",A.className="wds-input wds-find-input",A.placeholder=T,A.setAttribute("aria-label",L),A.spellcheck=!1,A};this.findInput=s(n.find,n.find),this.replaceInput=s(n.replaceWith,n.replaceWith),this.count=document.createElement("span"),this.count.className="wds-find-count",this.count.setAttribute("aria-live","polite");const o=nt(x.arrowUp,n.findPrevious),c=nt(x.arrowDown,n.findNext),a=document.createElement("button");a.type="button",a.className="wds-button",a.textContent=n.replace;const l=document.createElement("button");l.type="button",l.className="wds-button",l.textContent=n.replaceAll,this.buttons=[o,c,a,l];const d=document.createElement("label");d.className="wds-find-case",this.caseInput=document.createElement("input"),this.caseInput.type="checkbox",d.append(this.caseInput,` ${n.matchCase}`);const u=nt(x.close,n.close),p=document.createElement("div");p.className="wds-find-row",p.append(this.findInput,this.count,o,c);const m=document.createElement("div");m.className="wds-find-row",m.append(this.replaceInput,a,l),r.append(p,m,d,u);const b=()=>e.dispatch(e.state.tr.setMeta(Y,{query:this.findInput.value,caseSensitive:this.caseInput.checked}));this.findInput.addEventListener("input",b),this.caseInput.addEventListener("change",b),o.addEventListener("click",()=>tt(e,-1)),c.addEventListener("click",()=>tt(e,1)),a.addEventListener("click",()=>Xt(e,this.replaceInput.value)),l.addEventListener("click",()=>{const L=Mi(e,this.replaceInput.value);L&&(this.count.textContent=F(n.replacedCount,{count:L}))}),u.addEventListener("click",()=>this.close()),r.addEventListener("keydown",L=>{L.key==="Escape"?(L.preventDefault(),L.stopPropagation(),this.close()):L.key==="Enter"&&L.target===this.findInput?(L.preventDefault(),tt(e,L.shiftKey?-1:1)):L.key==="Enter"&&L.target===this.replaceInput&&(L.preventDefault(),Xt(e,this.replaceInput.value))})}get isOpen(){return!this.element.hidden}open(){const{from:e,to:n,empty:i}=this.view.state.selection,r=i?"":this.view.state.doc.textBetween(e,n," ");r&&r.length<100&&!r.includes(`
3
+ `)&&(this.findInput.value=r),this.element.hidden=!1,this.findInput.focus(),this.findInput.select(),this.view.dispatch(this.view.state.tr.setMeta(Y,{query:this.findInput.value,caseSensitive:this.caseInput.checked}))}close(){this.element.hidden||(this.element.hidden=!0,this.view.dispatch(this.view.state.tr.setMeta(Y,{query:""})),this.onClose())}update(e,n){if(this.element.hidden)return;const i=ue(e),r=i.matches.length;this.count.textContent=i.query?r?F(this.t.matchCount,{current:i.current+1,total:r}):this.t.noMatches:"";const s=this.buttons.find(o=>o===document.activeElement);this.buttons.forEach((o,c)=>o.disabled=!r||c>1&&!n),s?.disabled&&this.findInput.focus(),this.replaceInput.disabled=!n}}const Li="wds-editor:draft:";function ve(){try{return window.localStorage}catch{return null}}class Si{constructor(e,n,i,r,s,o){this.host=i,this.before=r,this.t=s,this.restore=o,this.timer=0,this.pending=null,this.bar=null,this.onPageHide=()=>this.flush(),this.key=Li+(e.key??n),this.delay=e.delay??1e3,this.expires=e.expires??7,window.addEventListener("pagehide",this.onPageHide)}check(e){const n=this.read();if(!n||n.html===e)return;const i=this.bar=document.createElement("div");i.className="wds-draft",i.setAttribute("role","status");const r=document.createElement("span"),s=new Date(n.time).toLocaleString(this.host.lang||void 0,{dateStyle:"short",timeStyle:"short"});r.textContent=F(this.t.draftFound,{time:s});const o=document.createElement("button");o.type="button",o.className="wds-button wds-button-primary",o.textContent=this.t.draftRestore;const c=document.createElement("button");c.type="button",c.className="wds-button",c.textContent=this.t.draftDiscard,o.addEventListener("click",()=>{this.hideBar(),this.restore(n.html)}),c.addEventListener("click",()=>{this.hideBar(),this.clear()}),i.append(r,o,c),this.host.insertBefore(i,this.before)}schedule(e){this.bar||(this.pending=e,window.clearTimeout(this.timer),this.timer=window.setTimeout(()=>this.flush(),this.delay))}flush(){if(window.clearTimeout(this.timer),this.pending===null)return;const e=this.pending;this.pending=null;try{e?ve()?.setItem(this.key,JSON.stringify({html:e,time:Date.now()})):ve()?.removeItem(this.key)}catch{}}clear(){window.clearTimeout(this.timer),this.pending=null;try{ve()?.removeItem(this.key)}catch{}}destroy(){this.flush(),this.hideBar(),window.removeEventListener("pagehide",this.onPageHide)}hideBar(){this.bar?.remove(),this.bar=null}read(){try{const e=ve()?.getItem(this.key);if(!e)return null;const n=JSON.parse(e);return typeof n?.html!="string"||typeof n.time!="number"?null:Date.now()-n.time>this.expires*864e5?(ve()?.removeItem(this.key),null):n}catch{return null}}}const he=new WeakMap,Qt=t=>t===void 0?void 0:typeof t=="number"?`${t}px`:t;function Ei(t){return t===!1?[]:t===void 0||t==="default"?Ot:Array.isArray(t)?t:t.split(/\s+/).filter(Boolean)}const fe=class fe{constructor(e,n={}){if(this.listeners=new Map,this.notice=null,this.noticeTimer=0,this.onFormSubmit=()=>{this.syncTarget(),this.autosave?.clear()},this.onKeydown=d=>{d.key==="Escape"&&this.fullscreen&&this.toggleFullscreen()},this.sourceMode=!1,this.plainPaste=!1,this.fullscreen=!1,this.destroyed=!1,he.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=ii(n.language),this.readOnly=!!n.readOnly,this.textarea=e instanceof HTMLTextAreaElement?e:null,this.originalContent=this.textarea?this.textarea.value:e.innerHTML;const i=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 d=Ft(n.language);this.root.lang=d;const u=n.dir??"auto";u==="rtl"||u==="auto"&&si(d)?this.root.dir="rtl":u==="ltr"&&(this.root.dir="ltr")}else n.dir&&n.dir!=="auto"&&(this.root.dir=n.dir);this.fileManager=n.fileManager?.listUrl?new hi(this.root,new di(n.fileManager),this.t):null,this.contentWrap=document.createElement("div"),this.contentWrap.className="wds-content-wrap";const r=Qt(n.height);r?(this.contentWrap.style.height=r,this.root.classList.add("wds-fixed-height")):this.contentWrap.style.minHeight=Qt(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=N.EditorState.create({schema:f,doc:Ae(i),plugins:[R.tableEditing(),Re.keymap({Tab:zn,"Shift-Tab":Fn,"Mod-f":()=>(this.openFind(),!0)}),ki(),Wn(),_n({link:()=>(this.openLinkDialog(),!0)}),qn(),X.history(),Vn(n.placeholder??""),Gn(),an.gapCursor(),ln.dropCursor({class:"wds-dropcursor",color:!1})]}),o=wi({css:n.contentCss,style:n.contentStyle});(o||n.contentClass!==void 0)&&this.root.classList.add("wds-site-styles"),o&&this.contentWrap.classList.add(o.className);const c=["wds-content",n.contentClass?.trim()].filter(Boolean).join(" "),a={onEdit:()=>this.openImageUrlDialog(),resizeLabel:this.t.resizeImage,captionPlaceholder:this.t.captionPlaceholder};this.view=new ne.EditorView(this.contentWrap,{state:s,editable:()=>!this.readOnly,attributes:{class:c,role:"textbox","aria-multiline":"true","aria-label":this.t.editorLabel},dispatchTransaction:d=>this.dispatch(d),transformPastedHTML:dn,handlePaste:(d,u)=>{const p=u.clipboardData;if(this.plainPaste&&p){const b=p.getData("text/plain");if(b)return d.dispatch(d.state.tr.replaceSelection(Ai(b)).scrollIntoView()),!0}if(!p?.files.length||!this.canUploadInline()||p.getData("text/plain"))return!1;const m=[...p.files].filter(b=>b.type.startsWith("image/"));return m.length?(this.uploadFiles(m),!0):!1},handleDrop:(d,u,p,m)=>{const b=u.dataTransfer?.files;if(m||!b?.length||!this.canUploadInline())return!1;const L=d.posAtCoords({left:u.clientX,top:u.clientY})?.pos;return u.preventDefault(),this.uploadFiles([...b],L),!0},nodeViews:{image:(d,u,p)=>new ti(d,u,p,a),figure:(d,u,p)=>new ni(d,u,p,a),video:d=>new mn(d,()=>this.openVideoDialog())},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=ei(this,Ei(n.toolbar),this.t),this.toolbar.element.childElementCount&&this.toolbar.element.firstElementChild.childElementCount&&this.root.append(this.toolbar.element),this.findPanel=new xi(this.view,this.t,()=>this.view.focus()),this.root.append(this.findPanel.element,this.contentWrap),this.autosave=n.autosave?new Si(n.autosave===!0?{}:n.autosave,`${location.pathname}#${e.id||e.getAttribute("name")||"editor"}`,this.root,this.contentWrap,this.t,d=>this.setHTML(d)):null;const l=document.createElement("div");if(l.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"),l.append(this.counter)),n.branding!==!1){const d=document.createElement("a");d.className="wds-branding",d.href="https://webdevsnippets.com/wds-editor",d.target="_blank",d.rel="noopener",d.innerHTML=`${Ti(this.t.poweredBy)} <strong>WDS Editor</strong>`,l.append(d)}l.childElementCount&&this.root.append(l),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),he.set(e,this),this.lastHtml=this.getHTML(),this.autosave?.check(this.lastHtml),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 he.get(n)??new fe(n,e)}static initAll(e){return[...document.querySelectorAll(e.selector)].map(n=>he.get(n)??new fe(n,e))}static get(e){const n=typeof e=="string"?document.querySelector(e):e;return n?he.get(n):void 0}getHTML(){return this.sourceMode&&this.applySource(),Te(this.view.state.doc)}setHTML(e){this.sourceMode&&(this.sourceArea.value=St(e));const n=Ae(e),i=this.view.state.tr.replaceWith(0,this.view.state.doc.content.size,n.content);this.dispatch(i.setSelection(N.TextSelection.atStart(i.doc)))}insertHTML(e){const n=Ae(e),i=Q.Slice.maxOpen(n.content);this.dispatch(this.view.state.tr.replaceSelection(i).scrollIntoView())}getText(){const e=this.view.state.doc;return e.textBetween(0,e.content.size,`
3
4
 
4
5
  `,`
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,`
6
- `).split(/\n{2,}/).map(n=>{const i=n.split(`
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"})}));
6
+ `)}isEmpty(){return xt(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,i=>this.dispatch(i),this.view);return this.view.focus(),n}undo(){this.exec(X.undo)}redo(){this.exec(X.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.findPanel.close(),this.sourceArea.value=St(Te(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()}clearDraft(){this.autosave?.clear()}openFind(){this.sourceMode||(this.findPanel.open(),this.refresh())}closeFind(){this.findPanel.close()}isFindOpen(){return this.findPanel.isOpen}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=Ue(e),{from:i,to:r,empty:s}=e.selection,o=s?"":e.doc.textBetween(i,r," "),c=s&&!n,a=this.t;je(this.root,{title:a.link,closeLabel:a.close,submitLabel:a.save,cancelLabel:a.cancel,fields:[{name:"href",label:a.linkUrl,type:"url",value:n?.href??"",placeholder:"https://"},...c?[{name:"text",label:a.linkText,type:"text",value:o}]:[],{name:"title",label:a.linkTitle,type:"text",value:n?.title??""},{name:"newTab",label:a.linkNewTab,type:"checkbox",value:n?.target==="_blank"}],extraAction:n?{label:a.remove,onClick:()=>this.removeLink()}:void 0,validate:l=>ht(String(l.href))?null:a.linkInvalid,onSubmit:l=>{const d=ht(String(l.href)),u={href:d,title:String(l.title).trim()||null,target:l.newTab?"_blank":null},p=f.marks.link.create(u),m=this.view.state;let b=m.tr;if(n)b=b.removeMark(n.from,n.to,f.marks.link).addMark(n.from,n.to,p);else if(c){const L=String(l.text??"").trim()||d.replace(/^mailto:/,"");b=b.replaceSelectionWith(f.text(L,[p]),!1)}else b=b.addMark(m.selection.from,m.selection.to,p);this.dispatch(b.scrollIntoView())},onClose:()=>this.view.focus()})}removeLink(){const e=Ue(this.view.state);e&&this.dispatch(this.view.state.tr.removeMark(e.from,e.to,f.marks.link))}insertVideo(e,n={}){const i=Ee(e);if(!i||this.readOnly||this.sourceMode)return!1;const r=f.nodes.video.create({src:i,title:n.title?.trim()??"",width:n.width??null}),s=this.view.state.tr.replaceSelectionWith(r);return this.dispatch(s.scrollIntoView()),!0}openVideoDialog(){if(this.readOnly||this.sourceMode)return;const e=this.t,n=It(this.view.state),i=n?.node.attrs??{};je(this.root,{title:n?e.videoEdit:e.video,closeLabel:e.close,submitLabel:n?e.save:e.insert,cancelLabel:e.cancel,fields:[{name:"url",label:e.videoUrl,type:"url",value:i.src??"",placeholder:"https://www.youtube.com/watch?v=…",hint:e.videoHint},{name:"title",label:e.videoTitle,type:"text",value:i.title??""},{name:"width",label:e.imageWidth,type:"number",value:i.width?String(i.width):"",placeholder:"560"}],validate:r=>Ee(String(r.url))?null:e.videoInvalid,onSubmit:r=>{const s=parseInt(String(r.width),10),o={src:Ee(String(r.url)),title:String(r.title).trim(),width:s>0?Math.min(s,4e3):null};if(n){const c=this.view.state.tr.setNodeMarkup(n.pos,void 0,o);this.dispatch(c.setSelection(N.NodeSelection.create(c.doc,n.pos)).scrollIntoView())}else this.insertVideo(o.src,o)},onClose:()=>this.view.focus()})}hasFileManager(){return!!this.fileManager}insertImage(e){const n=K(e.src);if(!n||this.readOnly||this.sourceMode)return!1;const i=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}),r=this.view.state.tr.replaceSelectionWith(i);return e.caption&&Dt(r,r.selection.from-1,i.attrs),this.dispatch(r.scrollIntoView()),!0}openImageDialog(){if(this.readOnly||this.sourceMode)return;We(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:i,width:r,align:s,text:o,caption:c})=>{e==="image"&&de(n)?this.insertImage({src:n.url,alt:i,width:r,align:s,caption:c}):this.insertFileLink(n,o),this.emit("fileSelect",n)},onClose:()=>this.view.focus()})}openImageUrlDialog(){const e=this.t,n=We(this.view.state),i=n?.attrs??{};je(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:i.src??"",placeholder:"https://"},{name:"alt",label:e.imageAlt,type:"text",value:i.alt??"",hint:e.imageAltHint},{name:"width",label:e.imageWidth,type:"number",value:i.width?String(i.width):""},{name:"align",label:e.imageAlign,type:"select",value:i.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:r=>K(String(r.src))&&!/^(mailto|tel):/i.test(String(r.src).trim())?null:e.imageInvalid,onSubmit:r=>{const s=parseInt(String(r.width),10),o={src:K(String(r.src)),alt:String(r.alt).trim(),width:s>0?s:null,align:String(r.align)||null},c=!!r.caption;if(n){const a=o.width&&o.width===i.width?i.height??null:null,l={...i,...o,height:a},d=this.view.state.tr;c&&!n.figure?Dt(d,n.pos,l):!c&&n.figure?Pn(d,n.pos,n.node,l):d.setNodeMarkup(n.pos,void 0,l).setSelection(N.NodeSelection.create(d.doc,n.pos)),this.dispatch(d.scrollIntoView())}else this.insertImage({...o,caption:c})},onClose:()=>this.view.focus()})}openTableMenu(e){if(this.readOnly||this.sourceMode)return;const n=this.t,i=this.view.state;if(!R.isInTable(i)){Yn(e,this.root,n.tableInsert,(o,c)=>F(n.tableSize,{rows:String(o),cols:String(c)}),(o,c)=>this.exec(Bn(o,c)));return}const r=(o,c,a=!1)=>({label:o,danger:a,enabled:c(i),run:()=>this.exec(c)}),s=[r(n.rowAbove,R.addRowBefore),r(n.rowBelow,R.addRowAfter),r(n.colLeft,R.addColumnBefore),r(n.colRight,R.addColumnAfter),"|",r(n.deleteRow,R.deleteRow),r(n.deleteCol,R.deleteColumn),"|",r(n.headerRow,R.toggleHeaderRow),r(n.headerCol,R.toggleHeaderColumn),r(n.mergeCells,R.mergeCells),r(n.splitCell,R.splitCell),"|",r(n.deleteTable,R.deleteTable,!0)];Kn(e,this.root,s,n.table)}openColorPicker(e,n){if(this.readOnly||this.sourceMode)return;const i=this.t,s=((e==="textColor"?this.options.colors?.text:this.options.colors?.highlight)??(e==="textColor"?gn:bn)).map(o=>typeof o=="string"?{color:o,name:o}:o).map(o=>({color:le(o.color),label:i[o.name]??o.name})).filter(o=>!!o.color);Jn(n,this.root,{label:e==="textColor"?i.textColor:i.highlight,removeLabel:e==="textColor"?i.removeColor:i.removeHighlight,swatches:s,columns:e==="textColor"?5:6,current:_e(this.view.state,e),onPick:o=>this.exec(Un(e,o))})}togglePlainPaste(e=!this.plainPaste){this.plainPaste=e,this.refresh(),this.view.focus()}isPlainPaste(){return this.plainPaste}insertFileLink(e,n){const i=K(e.url);if(!i||this.readOnly||this.sourceMode)return;const r=f.marks.link.create({href:i}),s=this.view.state,o=s.selection.empty?s.tr.replaceSelectionWith(f.text(n||e.name,[r]),!1):s.tr.addMark(s.selection.from,s.selection.to,r);this.dispatch(o.scrollIntoView())}canUploadInline(){return!!this.fileManager?.api.canUpload&&!this.readOnly&&!this.sourceMode}uploadFiles(e,n){if(!this.canUploadInline())return;const i=this.fileManager.api;for(const r of e){const s={};let o=this.view.state.tr;n===void 0&&!o.selection.empty&&(o=o.deleteSelection());const c=n??o.selection.from;this.dispatch(o.setMeta(ie,{add:{id:s,pos:c}})),i.upload(r,this.fileManager.path).then(a=>{if(this.destroyed)return;const l=jn(this.view.state,s);if(l===null)return;const d=de(a)?f.nodes.image.create({src:a.url,alt:""}):f.text(a.name,[f.marks.link.create({href:a.url})]);this.dispatch(this.view.state.tr.replaceWith(l,l,d).setMeta(ie,{remove:{id:s}})),this.emit("upload",a)}).catch(a=>{this.destroyed||(this.dispatch(this.view.state.tr.setMeta(ie,{remove:{id:s}})),this.showNotice(F(this.t.fmUploadFailed,{name:r.name,error:a.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),this.autosave?.destroy(),Nt(),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,he.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 i=Te(n.doc);i!==this.lastHtml&&(this.lastHtml=i,this.syncTarget(i),this.autosave?.schedule(i),this.options.onChange?.(i,this),this.emit("change"))}this.refresh()}applySource(){const e=this.sourceArea.value,n=Ae(e);if(n.eq(this.view.state.doc))return;const i=this.view.state.tr.replaceWith(0,this.view.state.doc.content.size,n.content),r=this.view.state.apply(i);this.view.updateState(r),this.lastHtml=Te(r.doc),this.syncTarget(this.lastHtml),this.autosave?.schedule(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.findPanel?.update(e,!this.readOnly),this.counter){const n=this.getText(),i=(n.match(/[\p{L}\p{N}][\p{L}\p{N}'’-]*/gu)??[]).length,r=n.replace(/\n/g,"").length;this.counter.textContent=`${i} ${this.t.words} · ${r} ${this.t.characters}`}}emit(e,n){this.listeners.get(e)?.forEach(i=>{try{i(this,n)}catch(r){console.error(r)}})}};fe.version="1.2.0",fe.addLanguage=Ge;let it=fe;function Ai(t){const e=t.replace(/\r\n?/g,`
7
+ `).split(/\n{2,}/).map(n=>{const r=n.split(`
8
+ `).flatMap((s,o)=>[...o?[f.nodes.hard_break.create()]:[],...s?[f.text(s)]:[]]);return f.nodes.paragraph.create(null,r)});return new Q.Slice(Q.Fragment.from(e),1,1)}function Ti(t){const e=document.createElement("span");return e.textContent=t,e.innerHTML}D.DEFAULT_TOOLBAR=Ot,D.WDSEditor=it,D.addLanguage=Ge,D.en=we,D.isImage=de,D.matchesAccept=Je,D.normalizeList=Wt,D.schema=f,D.toolbarItems=Rt,D.tr=Ht,Object.defineProperty(D,Symbol.toStringTag,{value:"Module"})}));
8
9
  //# sourceMappingURL=wds-editor.umd.cjs.map