@morfira-dev/wysiwyg-core 1.5.0 → 1.5.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/editor/html-snapshots.d.ts +5 -0
- package/dist/editor/types.d.ts +1 -1
- package/dist/formatting/inline-document.d.ts +2 -0
- package/dist/formatting/local-inline.d.ts +3 -0
- package/dist/formatting/types.d.ts +4 -0
- package/dist/index.js +1 -1
- package/dist/index.js.map +4 -4
- package/dist/input/block-boundaries.d.ts +3 -0
- package/dist/input/index.d.ts +1 -0
- package/package.json +1 -1
package/dist/editor/types.d.ts
CHANGED
|
@@ -40,7 +40,7 @@ export interface Editor {
|
|
|
40
40
|
redo(): void;
|
|
41
41
|
canUndo(): boolean;
|
|
42
42
|
canRedo(): boolean;
|
|
43
|
-
/** Execute
|
|
43
|
+
/** Execute one undoable plugin edit. Read-only and active composition block it. */
|
|
44
44
|
transact(mutate: (surface: HTMLElement) => void): void;
|
|
45
45
|
providePlugin<T>(name: string, api: T): () => void;
|
|
46
46
|
getPlugin<T>(name: string): T | undefined;
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var ot=["p","h1","h2","h3","h4","h5","h6","blockquote","pre","code","strong","em","u","s","sub","sup","a","span","br","hr","ul","ol","li","img","figure","figcaption","table","caption","colgroup","col","thead","tbody","tfoot","tr","td","th"],Ce=new Set(ot),st=new Set(["script","style","iframe","object","embed","svg","math","template","form","input","button","textarea","select","noscript","link","meta","base"]),it={b:"strong",i:"em",strike:"s",div:"p"},Ae=1e5,De=100,lt=(e,r)=>{let t=e.trim();if(!t||/[\u0000-\u0020\u007f]/.test(t))return;let n=/^([a-z][a-z\d+.-]*):/i.exec(t)?.[1].toLowerCase();if(!(n&&!(r?["http","https"]:["http","https","mailto","tel"]).includes(n))&&!(t.startsWith("\\")||t.startsWith("//")))return t},ct=e=>{let r=[];for(let t of e.split(";")){let n=t.indexOf(":");if(n<0)continue;let o=t.slice(0,n).trim().toLowerCase(),s=t.slice(n+1).trim().toLowerCase(),i=/^(#[a-f\d]{3,8}|[a-z]{1,24}|(?:rgb|rgba|hsl|hsla)\([\d\s.,%+-]+\))$/,c=/^(?:\d{1,4}(?:\.\d{1,3})?)(?:px|%|em|rem)$/;(["color","background-color","border-color"].includes(o)?i.test(s):["width","height","font-size"].includes(o)?c.test(s):o==="text-align"?["left","center","right","justify"].includes(s):o==="font-weight"?/^(bold|normal|[1-9]00)$/.test(s):o==="font-style"?["italic","normal"].includes(s):o==="text-decoration"?/^(underline|line-through|none)$/.test(s):!1)&&r.push(`${o}: ${s}`)}return r.join("; ")},Oe=(e,r)=>{let t={};for(let[n,o]of Object.entries(r))if(!(typeof o!="string"||o.length>2e4))if(n==="style"){let s=ct(o);s&&(t.style=s)}else if(n==="title"||e==="img"&&n==="alt")t[n]=o;else if(e==="a"&&n==="href"||e==="img"&&n==="src"){let s=lt(o,e==="img");s&&(t[n]=s)}else if(["td","th"].includes(e)&&["rowspan","colspan"].includes(n)||["img","col","table"].includes(e)&&["width","height","span"].includes(n))/^\d{1,4}$/.test(o)&&Number(o)>0&&Number(o)<=1e3&&(t[n]=o);else if(e==="a"&&n==="target"&&["_self","_blank"].includes(o))t.target=o;else if(e==="a"&&n==="rel"){let s=[...new Set(o.toLowerCase().split(/\s+/).filter(i=>["noopener","noreferrer"].includes(i)))];s.length&&(t.rel=s.join(" "))}else e==="th"&&n==="scope"&&["row","col","rowgroup","colgroup"].includes(o)&&(t[n]=o);if(e==="img"&&(t.width||t.height)){let n=["width","height"].filter(s=>t[s]),o=(t.style??"").split(";").map(s=>s.trim()).filter(s=>s&&!n.includes(s.slice(0,s.indexOf(":")).trim()));t.style=[...o,...n.map(s=>`${s}: ${t[s]}px`)].join("; ")}return e==="a"&&t.target==="_blank"&&(t.rel="noopener noreferrer"),t},Re=(e,r,t)=>{if(++t.count>Ae||r>De)throw new RangeError("Document exceeds structural limits.");if(e.nodeType===3)return[{type:"text",text:e.textContent??""}];if(e.nodeType!==1)return[];let n=e,o=n.localName.toLowerCase();if(n.namespaceURI!=="http://www.w3.org/1999/xhtml"||st.has(o))return[];let s=[...n.childNodes].flatMap(a=>Re(a,r+1,t)),i=it[o]??o;if(!Ce.has(i))return s;let c=Oe(i,Object.fromEntries([...n.attributes].map(a=>[a.name,a.value])));return i==="img"&&!c.src?[]:[{type:"element",tag:i,attributes:c,children:s}]},C=e=>{if(e.length>5e6)throw new RangeError("HTML exceeds the document size limit.");let r=document.createElement("template");r.innerHTML=e;let t={count:0};return{version:1,children:[...r.content.childNodes].flatMap(n=>Re(n,0,t))}},de=e=>{if(!e||typeof e!="object"||!("version"in e)||e.version!==1||!("children"in e)||!Array.isArray(e.children))throw new TypeError("Expected a version 1 document.");let r=0,t=0,n=(o,s)=>{if(++r>Ae||s>De)throw new RangeError("Document exceeds structural limits.");if(!o||typeof o!="object"||!("type"in o))throw new TypeError("Invalid document node.");if(o.type==="text"&&"text"in o&&typeof o.text=="string"){if(t+=o.text.length,t>5e6)throw new RangeError("Document text exceeds size limit.");return{type:"text",text:o.text}}if(o.type!=="element"||!("tag"in o)||typeof o.tag!="string"||!Ce.has(o.tag)||!("children"in o)||!Array.isArray(o.children))throw new TypeError("Invalid document element.");let i="attributes"in o&&o.attributes&&typeof o.attributes=="object"&&!Array.isArray(o.attributes)?o.attributes:{};return{type:"element",tag:o.tag,attributes:Oe(o.tag,i),children:o.children.map(c=>n(c,s+1))}};return{version:1,children:e.children.map(o=>n(o,0))}},ue=e=>{let r=document.createDocumentFragment(),t=(n,o)=>{if(o.type==="text"){n.appendChild(document.createTextNode(o.text));return}let s=document.createElement(o.tag);for(let[i,c]of Object.entries(o.attributes))s.setAttribute(i,c);for(let i of o.children)t(s,i);n.appendChild(s)};for(let n of e.children)t(r,n);return r},B=e=>{let r=document.createElement("div");return r.append(ue(e)),r.innerHTML},fe=e=>B(C(e));var N=e=>{let r=e.ownerDocument.getSelection();if(!r?.rangeCount)return;let t=r.getRangeAt(0);if(!(!e.contains(t.startContainer)||!e.contains(t.endContainer)))return t.cloneRange()},je=(e,r)=>{let t=[],n=r;for(;n!==e&&n.parentNode;)t.unshift([...n.parentNode.childNodes].indexOf(n)),n=n.parentNode;return t},Z=e=>{let r=N(e);if(!r)return;let t=e.ownerDocument.getSelection();return{start:je(e,r.startContainer),startOffset:r.startOffset,end:je(e,r.endContainer),endOffset:r.endOffset,backward:!r.collapsed&&t.anchorNode===r.endContainer&&t.anchorOffset===r.endOffset}},W=(e,r)=>{if(!r)return;let t=d=>d.reduce((m,u)=>m.childNodes[u]??m,e),n=t(r.start),o=t(r.end),s=(d,m)=>Math.min(m,d.nodeType===3?d.textContent?.length??0:d.childNodes.length),i=e.ownerDocument.getSelection();if(!i)return;let c=s(n,r.startOffset),a=s(o,r.endOffset);r.backward?i.setBaseAndExtent(o,a,n,c):i.setBaseAndExtent(n,c,o,a)},S=e=>{let r=N(e);if(!r)return;let t=e.ownerDocument.createRange();return t.selectNodeContents(e),t.setEnd(r.startContainer,r.startOffset),{index:t.toString().length,length:r.toString().length}},O=(e,r,t=0)=>{if(![r,t].every(b=>Number.isInteger(b)&&b>=0))throw new RangeError("Selection offsets must be non-negative integers.");let n=e.ownerDocument.createTreeWalker(e,4),o=[],s;for(;s=n.nextNode();)o.push(s);let i=b=>{for(let g of o){if(b<=g.length)return[g,b];b-=g.length}let f=o.at(-1);return f?[f,f.length]:[e.querySelector("p,h1,h2,h3,h4,h5,h6,li,blockquote,pre")??e,0]},[c,a]=i(r),[d,m]=i(r+t),u=e.ownerDocument.createRange();u.setStart(c,a),u.setEnd(d,m),e.focus({preventScroll:!0});let h=e.ownerDocument.getSelection();h?.removeAllRanges(),h?.addRange(u)},me=(e,r=!1)=>{let t=e.ownerDocument.createRange();t.selectNodeContents(e),t.collapse(!r);let n=e.ownerDocument.getSelection();n?.removeAllRanges(),n?.addRange(t)},P=(e,r)=>{let t=N(e);if(!t)return;let n=e.ownerDocument.getSelection(),o=!t.collapsed&&n.anchorNode===t.endContainer&&n.anchorOffset===t.endOffset,s=e.ownerDocument.createComment("mw-start"),i=t.collapsed?void 0:e.ownerDocument.createComment("mw-end");if(i){let a=t.cloneRange();a.collapse(!1),a.insertNode(i)}let c=t.cloneRange();c.collapse(!0),c.insertNode(s);try{if(r(),e.contains(s)&&(!i||e.contains(i))){let a=e.ownerDocument.createRange();a.setStartBefore(s),i?a.setEndBefore(i):a.collapse(!0),s.remove(),i?.remove(),e.normalize(),o?n.setBaseAndExtent(a.endContainer,a.endOffset,a.startContainer,a.startOffset):(n.removeAllRanges(),n.addRange(a))}}finally{s.remove(),i?.remove()}};var Pe="p,h1,h2,h3,h4,h5,h6,blockquote,pre,li",A=e=>!!e&&/^(ul|ol)$/.test(e.localName),at=e=>e instanceof Element?e:e.parentElement,ne=(e,r,t=!0)=>{let n=at(r),o=n?.closest("li"),s=(t&&o&&e.contains(o)?o:void 0)??n?.closest(Pe);return s&&e.contains(s)?s:void 0},dt=(e,r)=>{let t=r.ownerDocument.createRange();r.nodeType===3?t.selectNodeContents(r):t.selectNode(r);let n=e.cloneRange();n.collapse(!0);let o=e.cloneRange();o.collapse(!1);let s=t.cloneRange();s.collapse(!0);let i=t.cloneRange();return i.collapse(!1),n.compareBoundaryPoints(Range.START_TO_START,i)<0&&o.compareBoundaryPoints(Range.START_TO_START,s)>0},J=(e,r=N(e),t=!0)=>{if(!r)return[];if(r.collapsed){let i=ne(e,r.startContainer,t);return i?[i]:[]}let n=new Set,o=e.ownerDocument.createTreeWalker(e,NodeFilter.SHOW_TEXT|NodeFilter.SHOW_ELEMENT),s;for(;s=o.nextNode();)if(!(!(s.nodeType===3&&s.textContent)&&!(s instanceof Element&&/^(br|img|hr)$/.test(s.localName)))&&dt(r,s)){let i=ne(e,s,t);i&&n.add(i)}return[...e.querySelectorAll(Pe)].filter(i=>n.has(i))},qe=e=>e.filter(r=>!e.some(t=>t!==r&&t.contains(r))),Fe=e=>{let r=qe(J(e));if(!r.length||r.some(o=>o.localName!=="li"||!A(o.parentElement)))return[];let t=r[0].parentElement;if(r.some(o=>o.parentElement!==t))return[];let n=[...t.children];return n.indexOf(r.at(-1))-n.indexOf(r[0])+1!==r.length?[]:r},Be=(e,r)=>{let t=0,n=r.parentElement;for(;n&&n!==e;)A(n)&&t++,n=n.parentElement;return t},$e=(e,r)=>!!e&&e.localName===r.localName&&A(e)&&e.getAttribute("style")===r.getAttribute("style"),ee=e=>{for(let r of[...e.querySelectorAll("ul,ol")]){if(!e.contains(r))continue;let t=r.previousSibling;t instanceof Element&&$e(t,r)&&(t.append(...r.childNodes),r.remove())}},ze=(e,r)=>{let t=e.parentElement,n=t.cloneNode(!1);for(;e.nextSibling;)n.append(e.nextSibling);e.remove(),t.after(...r,...n.childNodes.length?[n]:[]),t.childNodes.length||t.remove()},te=e=>[...e.childNodes].filter(r=>!(r instanceof Element&&A(r))),Ke=(e,r=!1)=>{let t=()=>{let c=document.createElement("p");return e.hasAttribute("style")&&c.setAttribute("style",e.getAttribute("style")),c},n=t(),o=[...e.children].filter(A),s=te(e),i=[];for(let c of s)r&&c instanceof HTMLElement&&/^(p|h[1-6]|blockquote|pre)$/.test(c.localName)?n.append(...c.childNodes):c instanceof HTMLElement&&/^(p|h[1-6]|blockquote|pre)$/.test(c.localName)?(n.childNodes.length&&i.push(n),n=t(),i.push(c)):n.append(c);(n.childNodes.length||!i.length)&&(n.childNodes.length||n.append(document.createElement("br")),i.push(n)),ze(e,[...i,...o])},pe=e=>{let r=e[0].parentElement,t=r.parentElement;if(t?.localName!=="li"||!A(t.parentElement)){for(let o of e)Ke(o);return}let n=r.cloneNode(!1);for(;e.at(-1).nextSibling;)n.append(e.at(-1).nextSibling);n.childNodes.length&&e.at(-1).append(n),t.after(...e),r.childNodes.length||r.remove()},re=e=>{let r=Fe(e),t=!!r.length&&r[0].previousElementSibling?.localName==="li"&&r.every(n=>[n,...n.querySelectorAll("li")].every(o=>Be(e,o)<8));return{listDepth:r.length?Be(e,r[0]):0,canIndent:t,canOutdent:!!r.length}},he=(e,r)=>{if(r!==1&&r!==-1)throw new TypeError("List indentation requires 1 or -1.");let t=Fe(e);if(!t.length)throw new RangeError("Select consecutive items in the same list.");r===1&&!re(e).canIndent||P(e,()=>{if(r===-1)pe(t);else{let n=t[0].parentElement,o=t[0].previousElementSibling,s=o.lastElementChild;$e(s,n)||(s=n.cloneNode(!1),o.append(s)),s.append(...t)}ee(e)})},_e=(e,r)=>{if(r!==!1&&r!=="bullet"&&r!=="ordered")throw new TypeError("Expected bullet, ordered or false.");let t=qe(J(e));if(t.some(n=>n.localName==="li"&&!A(n.parentElement)))throw new RangeError("A list item must belong to a list.");P(e,()=>{for(let n of t){if(!r){n.localName==="li"&&pe([n]);continue}let o=r==="bullet"?"ul":"ol";if(n.localName==="li"){if(n.parentElement.localName===o)continue;let s=document.createElement(o);n.parentElement.hasAttribute("style")&&s.setAttribute("style",n.parentElement.getAttribute("style")),ze(n,[s]),s.append(n)}else{let s=document.createElement(o),i=document.createElement("li");n.hasAttribute("style")&&i.setAttribute("style",n.getAttribute("style")),i.append(...n.childNodes),s.append(i),n.replaceWith(s)}}ee(e)})},ut=e=>!e.textContent?.trim()&&!e.querySelector("img,hr,ul,ol"),Ie=e=>{te(e).some(n=>n.textContent||n instanceof Element&&(n.matches("br,img,hr")||n.querySelector("br,img,hr")))||([...e.children].some(A)?e.prepend(Object.assign(document.createElement("p"),{innerHTML:"<br>"})):e.append(document.createElement("br")))},ft=(e,r)=>{let t=r.cloneRange();return t.selectNodeContents(e),t.setEnd(r.startContainer,r.startOffset),!t.toString()&&!t.cloneContents().querySelector("img,hr,br")},Ee=(e,r)=>{let t=N(e);if(!t)return!1;let n=ne(e,t.startContainer);return n?.localName!=="li"||!A(n.parentElement)||ne(e,t.endContainer)!==n?!1:["insertParagraph","insertLineBreak"].includes(r)||r==="deleteContentBackward"&&t.collapsed&&ft(n,t)},xe=(e,r)=>{let t=N(e),n=ne(e,t.startContainer);if(r==="insertParagraph"){if(ut(n)){P(e,()=>{let a=n.parentElement.parentElement;a?.localName==="li"&&A(a.parentElement)?pe([n]):Ke(n,!0)}),ee(e);return}t.deleteContents();let o=t.cloneRange();o.selectNodeContents(n),o.setStart(t.startContainer,t.startOffset);let s=n.cloneNode(!1);s.append(o.extractContents()),n.after(s),Ie(n),Ie(s);let i=document.createTreeWalker(s,NodeFilter.SHOW_TEXT),c;do c=i.nextNode();while(c&&(!c.textContent||c.parentElement?.closest("li")!==s));if(c){let a=document.createRange();a.setStart(c,0),a.collapse(!0);let d=document.getSelection();d?.removeAllRanges(),d?.addRange(a)}else me(s.querySelector("p,h1,h2,h3,h4,h5,h6,pre")??s)}else if(r==="insertLineBreak"){t.deleteContents();let o=document.createElement("br");t.insertNode(o),o.nextSibling||o.after(document.createElement("br")),t.setStartAfter(o),t.collapse(!0);let s=document.getSelection();s?.removeAllRanges(),s?.addRange(t)}else{let o=n.previousElementSibling;if(o&&o.localName!=="li")return;if(!o){P(e,()=>pe([n])),ee(e);return}if(!te(o).some(h=>h.textContent||h instanceof Element&&(h.localName==="img"||h.querySelector("img"))))for(let h of[...o.querySelectorAll("br")])h.closest("li")===o&&h.remove();let s=document.createComment("mw-join"),c=te(o).at(-1),a=c instanceof HTMLElement&&/^(p|h[1-6]|blockquote|pre)$/.test(c.localName)?c:o;a===o?o.insertBefore(s,[...o.children].find(A)??null):a.append(s);let d=te(n);d[0]instanceof HTMLElement&&/^(p|h[1-6])$/.test(d[0].localName)&&d.splice(0,1,...d[0].childNodes),s.after(...d);for(let h of[...n.children].filter(A))o.append(h);n.remove(),ee(e);let m=document.createRange();m.setStartBefore(s),m.collapse(!0),s.remove();let u=document.getSelection();u?.removeAllRanges(),u?.addRange(m)}};var R={color:"color",background:"background-color"},Ue=new Set(["p","h1","h2","h3","h4","h5","h6","blockquote","pre","ul","ol","li","table","thead","tbody","tfoot","tr","td","th","caption","colgroup","figure","figcaption"]),ke=(e,r)=>de({version:1,children:[{type:"element",tag:e,attributes:r,children:[]}]}).children[0].attributes,X=(e,r)=>{if(r===!1)return!1;if(typeof r!="string"||!r.trim()||r.length>128||/[;{}]/.test(r))throw new TypeError("Expected a CSS color or false.");let t=R[e],n=ke("span",{style:`${t}: ${r}`}),o=document.createElement("span");o.setAttribute("style",n.style??"");let s=o.style.getPropertyValue(t);if(!s)throw new TypeError("Unsupported or invalid CSS color.");return s},Je=e=>{if(e===!1)return!1;let r=typeof e=="string"?{href:e}:e;if(!r||typeof r!="object"||Array.isArray(r)||!("href"in r)||typeof r.href!="string")throw new TypeError("Expected a link URL, LinkFormat or false.");let t=r,n={href:r.href};if(t.title!==void 0){if(typeof t.title!="string"||t.title.length>1024)throw new TypeError("Link title must be a string up to 1024 characters.");n.title=t.title}if(t.target!==void 0){if(t.target!=="_self"&&t.target!=="_blank")throw new TypeError("Link target must be _self or _blank.");n.target=t.target}if(t.text!==void 0&&(typeof t.text!="string"||!t.text.length||t.text.length>2e4))throw new TypeError("New link text must contain 1\u201320000 characters.");let o=ke("a",n);if(!o.href)throw new TypeError("Unsupported or unsafe link URL.");return{attributes:o,...typeof t.text=="string"?{text:t.text}:{}}},we=(e,r)=>{let t={...e,...r};return t.title||delete t.title,r.target==="_self"&&delete t.rel,ke("a",t)},Xe=(e,r)=>JSON.stringify(Object.entries(e??{}).sort())===JSON.stringify(Object.entries(r??{}).sort()),mt=(e,r)=>{let t={...e},n=(t.style??"").split(";").map(o=>o.trim()).filter(o=>o&&o.slice(0,o.indexOf(":")).trim()!==r).join("; ");return n?t.style=n:delete t.style,t},We=e=>{let r=[];for(let t of e){let n=r.at(-1);n&&n.selected===t.selected&&Xe(n.link,t.link)?n.pieces.push(t):r.push({pieces:[t],selected:t.selected,link:t.link})}return r},Te=e=>{let r=[];for(let t of e){let n=t.type==="element"?{...t,children:Te(t.children)}:t,o=r.at(-1);n.type==="text"&&o?.type==="text"?o.text+=n.text:n.type==="element"&&o?.type==="element"&&!Ue.has(n.tag)&&!["img","br","hr"].includes(n.tag)&&o.tag===n.tag&&Xe(o.attributes,n.attributes)?o.children=Te([...o.children,...n.children]):r.push(n)}return r},ge=(e,r,t,n)=>{let o=0,s=c=>We(c).flatMap(a=>{let d=a.pieces.map(u=>u.node);if(n.kind==="style")return a.selected&&n.value!==!1?[{type:"element",tag:"span",attributes:{style:`${n.property}: ${n.value}`},children:d}]:d;let m=a.selected?n.attributes===!1?void 0:we(a.link??{},n.attributes):a.link;return m?[{type:"element",tag:"a",attributes:m,children:d}]:d}),i=(c,a)=>{if(c.type==="text"){let u=o;o+=c.text.length;let h=Math.max(0,Math.min(c.text.length,r-u)),b=Math.max(h,Math.min(c.text.length,t-u));return[[0,h,!1],[h,b,!0],[b,c.text.length,!1]].flatMap(([f,g,x])=>{let T=c.text.slice(f,g);return T?[{node:{type:"text",text:T},selected:!!x,link:a}]:[]})}let d=n.kind==="link"&&c.tag==="a"?c.attributes:a;if(!c.children.length)return[{node:c,selected:o>=r&&o<t,link:d}];let m=c.children.flatMap(u=>i(u,d));return n.kind==="link"&&c.tag==="a"?m:Ue.has(c.tag)?[{node:{...c,children:s(m)},selected:!1}]:We(m).flatMap(u=>{let h=n.kind==="style"&&u.selected?mt(c.attributes,n.property):c.attributes,b=u.pieces.map(f=>f.node);return c.tag==="span"&&!Object.keys(h).length?u.pieces:[{node:{...c,attributes:h,children:b},selected:u.selected,link:u.link}]})};return{version:1,children:Te(s(e.children.flatMap(c=>i(c))))}};var Qe=(e,r)=>{let t=Je(r),n=N(e);if(!n)return;let o=S(e),s=n.startContainer.nodeType===1?n.startContainer:n.startContainer.parentElement,i=s?.closest("a"),c=i&&e.contains(i)?i:void 0;if(t&&t.text!==void 0&&(!n.collapsed||c))throw new TypeError("Link text is only supported for insertion at a caret outside links.");if(!n.collapsed){e.innerHTML=B(ge(C(e.innerHTML),o.index,o.index+o.length,{kind:"link",attributes:t&&t.attributes})),O(e,o.index,o.length);return}if(c){let h=t&&we(Object.fromEntries([...c.attributes].map(b=>[b.name,b.value])),t.attributes);P(e,()=>{if(!h)c.replaceWith(...c.childNodes);else{for(let b of[...c.attributes])c.removeAttribute(b.name);for(let[b,f]of Object.entries(h))c.setAttribute(b,f)}});return}if(!t||t.text===void 0)return;let a=e.ownerDocument.createElement("a");for(let[h,b]of Object.entries(t.attributes))a.setAttribute(h,b);a.textContent=t.text;let d=s?.closest("p,li,h1,h2,h3,h4,h5,h6,blockquote,pre,td,th");d?.childNodes.length===1&&d.firstChild instanceof HTMLBRElement&&(d.firstChild.remove(),n.setStart(d,0)),n.insertNode(a);let m=e.ownerDocument.createTextNode("");a.after(m),n.setStart(m,0),n.collapse(!0);let u=e.ownerDocument.getSelection();u?.removeAllRanges(),u?.addRange(n)};var Q={bold:"strong",italic:"em",underline:"u",strike:"s",code:"code",subscript:"sub",superscript:"sup"},pt=new Set(["p","h1","h2","h3","h4","h5","h6","blockquote","pre","ul","ol","li","table","thead","tbody","tfoot","tr","td","th","caption","colgroup","figure","figcaption"]),Ve=(e,r,t,n,o)=>{let s=0,i=(c,a)=>{if(c.type==="text"){let u=s;s+=c.text.length;let h=Math.max(0,Math.min(c.text.length,r-u)),b=Math.max(h,Math.min(c.text.length,t-u));return[[0,h,!1],[h,b,!0],[b,c.text.length,!1]].flatMap(([f,g,x])=>{let T=c.text.slice(f,g);if(!T)return[];let k={type:"text",text:T};return[{node:x&&o&&!a?{type:"element",tag:n,attributes:{},children:[k]}:k,selected:!!x}]})}let d=c.children.flatMap(u=>i(u,a||o&&c.tag===n));if(pt.has(c.tag))return[{node:{...c,children:d.map(u=>u.node)},selected:!1}];if(!d.length)return[{node:c,selected:!1}];let m=[];for(let u of d){let h=m.at(-1);h?.selected===u.selected?h.children.push(u.node):m.push({selected:u.selected,children:[u.node]})}return m.flatMap(u=>c.tag===n&&!o&&u.selected?u.children.map(h=>({node:h,selected:!0})):[{node:{...c,children:u.children},selected:u.selected}])};return{version:1,children:e.children.flatMap(c=>i(c,!1)).map(c=>c.node)}},ht=e=>e.nodeType===1?e:e.parentElement,Ge=(e,r)=>{let t=ht(r),n={};for(;t&&t!==e;){for(let[o,s]of Object.entries(Q))t.localName===s&&(n[o]=!0);if(/^h[1-6]$/.test(t.localName)&&n.header===void 0&&(n.header=Number(t.localName[1])),t.localName==="blockquote"&&(n.blockquote=!0),t.localName==="pre"&&(n["code-block"]=!0),(t.localName==="ul"||t.localName==="ol")&&n.list===void 0&&(n.list=t.localName==="ul"?"bullet":"ordered"),t.localName==="a"&&n.link===void 0&&(n.link=t.getAttribute("href"),n.linkTitle=t.getAttribute("title")??"",n.linkTarget=t.getAttribute("target")??"_self"),t instanceof HTMLElement)for(let[o,s]of Object.entries(R))n[o]===void 0&&t.style.getPropertyValue(s)&&(n[o]=t.style.getPropertyValue(s));t instanceof HTMLElement&&t.style.textAlign&&n.align===void 0&&(n.align=t.style.textAlign),t=t.parentElement}return n},be=e=>{let r=N(e);if(!r)return{};let t=Ge(e,r.startContainer),n=new Set;if(!r.collapsed){let{index:o,length:s}=S(e),i=e.ownerDocument.createTreeWalker(e,NodeFilter.SHOW_TEXT),c=0,a,d=[];for(;a=i.nextNode();){let h=c+a.textContent.length;h>o&&c<o+s&&d.push(Ge(e,a)),c=h}d.length&&(t=d[0]);let m=[...Object.keys(Q),"header","list","blockquote","code-block","link","linkTitle","linkTarget","color","background","align"],u=(h,b)=>h[b]??(b==="align"?"left":b==="header"?0:!1);for(let h of m)d.some(b=>u(b,h)!==u(d[0],h))&&n.add(h)}return{...t,align:t.align??"left",mixed:[...n],...re(e)}},Le=(e,r,t)=>{let n=N(e);if(!n)return;let o=S(e);if(r==="list"){_e(e,t);return}if(r==="indent"){he(e,t);return}if(r==="clear"){if(t!==!0||!o.length)return;let c=C(e.innerHTML);for(let a of[...Object.values(Q),"a","span"])c=Ve(c,o.index,o.index+o.length,a,!1);e.innerHTML=B(c),O(e,o.index,o.length);return}let s=Q[r];if(s){if(n.collapsed)return;e.innerHTML=B(Ve(C(e.innerHTML),o.index,o.index+o.length,s,!!t)),O(e,o.index,o.length);return}if(r==="link"){Qe(e,t);return}if(Object.hasOwn(R,r)){let c=X(r,t);if(!o.length)return;e.innerHTML=B(ge(C(e.innerHTML),o.index,o.index+o.length,{kind:"style",property:R[r],value:c})),O(e,o.index,o.length);return}let i=J(e,n,!1);if(!i.length){let c=document.createElement("p");c.append(n.extractContents()),c.childNodes.length||c.append(document.createElement("br")),n.insertNode(c),i=[c]}P(e,()=>{for(let c of i){if(r==="align"&&["left","center","right","justify",!1].includes(t)){c.style.textAlign=t?String(t):"";continue}let a=r==="header"?Number.isInteger(t)&&Number(t)>=1&&Number(t)<=6?`h${t}`:"p":r==="blockquote"?t?"blockquote":"p":r==="code-block"?t?"pre":"p":void 0;if(a){let d=document.createElement(a);if(c.localName==="li"){let m=[...c.childNodes].filter(u=>!(u instanceof Element&&/^(ul|ol|p|h[1-6]|pre|blockquote)$/.test(u.localName)));d.append(...m),c.prepend(d)}else d.append(...c.childNodes),d.setAttribute("style",c.getAttribute("style")??""),c.replaceWith(d)}}})};var Ze=new WeakSet,gt=new Set(["change","selectionchange","readonlychange","destroy"]),bt=e=>{if(typeof e!="string"||!e.trim()||e.length>200)throw new TypeError("Expected an event name with 1\u2013200 characters.");let r=Object.freeze({name:e});return Ze.add(r),r},Ye=e=>{if(!e||typeof e!="object"||!Ze.has(e))throw new TypeError("Expected a plugin event token. Core events cannot be emitted publicly.");return e},et=()=>{let e=new Map,r=[],t=0,n=!1,o=!1,s=a=>{if(o&&a.key!=="destroy"||(r.push(a),n))return;n=!0;let d=[];try{for(;r.length;){let m=r.shift();if(o&&m.key!=="destroy")continue;let u=e.get(m.key);for(let[h,b]of[...u??[]])if(!(o&&m.key!=="destroy"||u?.get(h)!==b))try{let f=m.core&&m.payload&&typeof m.payload=="object"?{...m.payload}:m.payload;h(f)}catch(f){d.push(f)}m.key==="destroy"&&(e.clear(),r.length=0)}}finally{n=!1}if(d.length)throw new AggregateError(d,"Editor event listeners failed.")};return{events:{on:(a,d)=>{if(o)throw new Error("Editor events have been destroyed.");if(typeof d!="function")throw new TypeError("Expected an event listener.");let m=typeof a=="string"&>.has(a)?a:Ye(a),u=e.get(m);u||(u=new Map,e.set(m,u)),u.has(d)||u.set(d,++t);let h=u.get(d);return()=>{u.get(d)===h&&(u.delete(d),!u.size&&e.get(m)===u&&e.delete(m))}},emit:(a,d)=>{if(o)throw new Error("Editor events have been destroyed.");s({key:Ye(a),payload:d,core:!1})}},notify:(a,d)=>s({key:a,payload:d,core:!0}),destroy:()=>{o||(o=!0,r.length=0,s({key:"destroy",payload:void 0,core:!0}))}}};var oe=e=>{let r=!1;e.childNodes.length||(e.innerHTML="<p><br></p>",r=!0);let t;for(let n of[...e.childNodes])n.nodeType===3||n.nodeType===1&&/^(strong|em|u|s|a|span|code|img|br|sub|sup)$/.test(n.localName)?(t||(t=document.createElement("p"),e.insertBefore(t,n)),t.append(n),r=!0):t=void 0;return["table","figure"].includes(e.lastElementChild?.localName??"")&&e.append(Object.assign(document.createElement("p"),{innerHTML:"<br>"})),e.dataset.empty=String(!e.textContent&&!e.querySelector("table,img,hr")),r},yt=(e,r)=>{let t=N(e);if(!t)return;let n=ue(C(r));if(!n.childNodes.length)return;t.deleteContents();let s=(t.startContainer.nodeType===1?t.startContainer:t.startContainer.parentElement)?.closest("p,h1,h2,h3,h4,h5,h6,li,blockquote,pre");if(n.childNodes.length===1&&n.firstChild instanceof HTMLParagraphElement&&s){let m=n.firstChild;n.replaceChildren(...m.childNodes)}let i=[...n.childNodes].some(m=>m instanceof HTMLElement&&/^(p|h[1-6]|ul|ol|table|figure|blockquote|pre)$/.test(m.localName)),c=n.lastChild;if(i&&s&&e.contains(s)){let m=document.createRange();m.selectNodeContents(s),m.setStart(t.startContainer,t.startOffset);let u=s.cloneNode(!1);u.append(m.extractContents()),s.after(n),(u.textContent||u.querySelector("img,br"))&&c.after(u),!s.textContent&&!s.querySelector("img")&&s.remove()}else t.insertNode(n);let a=document.createRange();a.setStartAfter(c),a.collapse(!0);let d=document.getSelection();d?.removeAllRanges(),d?.addRange(a)},Et=(e,r={})=>{if(e.childNodes.length)throw new Error("Editor host must be empty. Pass initial HTML through value.");let t=r.plugins??[];if(new Set(t.map(l=>l.name)).size!==t.length)throw new Error("Duplicate editor plugin.");let n=r.historyLimit??100;if(!Number.isInteger(n)||n<1||n>1e4)throw new RangeError("historyLimit must be an integer from 1 to 10000.");let o=C(r.value??""),s=document.createElement("div");s.className="mw-editor";let i=document.createElement("div");i.className="mw-content",i.setAttribute("role","textbox"),i.setAttribute("aria-multiline","true"),i.setAttribute("aria-label",r.label??"\u0422\u0435\u043A\u0441\u0442\u043E\u0432\u044B\u0439 \u0440\u0435\u0434\u0430\u043A\u0442\u043E\u0440"),i.dataset.placeholder=r.placeholder??"\u041D\u0430\u0447\u043D\u0438\u0442\u0435 \u043F\u0438\u0441\u0430\u0442\u044C\u2026",s.append(i),e.append(s),i.append(ue(o)),oe(i);let c=!1,a=r.readOnly??!1,d=!1,m,u,h=0,b="",f={},g,x=()=>{f={},g=void 0},T=()=>{let l=S(i);return l?.length===0&&l.index===g},k=[],H=[],I=et(),q=0,se=!1,ie,V=!1,G=new Map,le=[];r.onChange&&I.events.on("change",r.onChange);let w=()=>{if(c)throw new Error("Editor has been destroyed.")},$=l=>{if(!q)return;let p=new Error(`${l} is unavailable inside a transaction.`);throw se=!0,ie=p,p},tt={on:I.events.on,emit:(l,p)=>{w(),$("events.emit"),I.events.emit(l,p)}},j=()=>({html:fe(i.innerHTML),selection:Z(i),...g!==void 0&&Object.keys(f).length&&T()?{typing:{offset:g,formats:{...f}}}:{}}),Ne=l=>{x();let p=S(i);l.typing&&p?.length===0&&p.index===l.typing.offset&&(g=l.typing.offset,f={...l.typing.formats})},v=j(),z=v.selection,K=()=>{if(c)return;if(q){V=!0;return}S(i)&&!T()&&x();let l=Z(i);l&&(z=l,v.selection=l),I.notify("selectionchange",S(i))},ce=l=>{let p={html:L.getHTML(),text:L.getText(),source:l},y=[];try{I.notify("change",p)}catch(E){y.push(E)}try{K()}catch(E){y.push(E)}if(y.length)throw new AggregateError(y,"Editor change notification failed.")},Me=(l,p="")=>{let y=S(i);oe(i)&&y&&O(i,y.index,y.length);let E=j();if(E.html===l.html)return v=E,!1;let M=Date.now();return p===b&&["insertText","deleteContentBackward","deleteContentForward"].includes(p)&&M-h<600&&l.selection&&v.selection&&JSON.stringify(l.selection)===JSON.stringify(v.selection)||(k.push(l),k.length>n&&k.shift()),H.length=0,v=E,h=p?M:0,b=p,!0},Se=(l,p="")=>{Me(l,p)&&ce("user")},He=l=>{x(),i.innerHTML=l.html,oe(i),i.focus({preventScroll:!0}),W(i,l.selection),Ne(l),v=j(),z=v.selection,h=0,ce("user")},Y=(l,p="")=>{if(w(),a)return;let y=()=>{if(typeof l!="function"||l.constructor.name==="AsyncFunction")throw new TypeError("Transactions require a synchronous callback.");let D=l(i);if(D&&(typeof D=="object"||typeof D=="function")&&typeof D.then=="function")throw D instanceof Promise&&D.catch(()=>{}),new TypeError("Transaction callbacks must not return a thenable.")};if(q){q++;try{y()}catch(D){throw se=!0,ie=D,D}finally{q--}return}L.focus();let E=j(),M=[...k],ye=[...H],F=h,U=b,ae=u,nt=z;q=1,se=!1,ie=void 0,V=!1;let ve=!1;try{if(y(),se)throw ie;ve=Me(E,p)}catch(D){throw i.innerHTML=E.html,oe(i),W(i,E.selection),Ne(E),v=j(),z=nt,u=ae,k.splice(0,k.length,...M),H.splice(0,H.length,...ye),h=F,b=U,q=0,V=!1,D}finally{q=0}let rt=V;V=!1,ve?ce("user"):rt&&K()},L={element:s,surface:i,events:tt,getHTML:()=>(w(),fe(i.innerHTML)),getText:()=>(w(),i.innerText),getJSON:()=>(w(),C(i.innerHTML)),setHTML:l=>{w(),$("setHTML");let p=B(C(l));p!==L.getHTML()&&(x(),i.innerHTML=p,oe(i),k.length=0,H.length=0,h=0,z=void 0,v=j(),ce("api"))},setJSON:l=>{w(),$("setJSON");let p=de(l);L.setHTML(B(p))},getSelection:()=>(w(),S(i)),setSelection:(l,p=0)=>{w(),O(i,l,p),K()},getFormats:()=>(w(),{...be(i),...T()?f:{}}),setReadOnly:l=>{w(),$("setReadOnly");let p=a!==l;a=l,i.contentEditable=String(!l),i.setAttribute("aria-readonly",String(l)),s.dataset.readonly=String(l);let y=[];if(p)try{I.notify("readonlychange",l)}catch(E){y.push(E)}try{K()}catch(E){y.push(E)}if(y.length)throw new AggregateError(y,"Editor state notification failed.")},isReadOnly:()=>(w(),a),format:(l,p)=>{if(w(),a)return;L.focus();let y=S(i);if(y?.length===0&&(Object.hasOwn(Q,l)||Object.hasOwn(R,l))){T()||x(),g=y.index,f[l]=Object.hasOwn(R,l)?X(l,p):!!p,K();return}x(),L.transact(()=>Le(i,l,p))},insertHTML:l=>L.transact(()=>yt(i,l)),focus:()=>{w(),i.focus({preventScroll:!0}),N(i)||(z?W(i,z):me(i.firstElementChild??i,!0))},undo:()=>{if(w(),$("undo"),a)return;let l=k.pop();l&&(H.push(j()),He(l))},redo:()=>{if(w(),$("redo"),a)return;let l=H.pop();l&&(k.push(j()),He(l))},canUndo:()=>(w(),k.length>0),canRedo:()=>(w(),H.length>0),transact:l=>Y(l),providePlugin:(l,p)=>{if(w(),G.has(l))throw new Error(`Plugin API already registered: ${l}`);return G.set(l,p),()=>{G.delete(l)}},getPlugin:l=>(w(),G.get(l)),subscribe:l=>(w(),I.events.on("change",l)),onSelectionChange:l=>(w(),I.events.on("selectionchange",l)),destroy:()=>{if(c)return;$("destroy"),c=!0;let l=[];try{I.destroy()}catch(p){l.push(p)}for(let p of le.reverse())try{p()}catch(y){l.push(y)}if(G.clear(),k.length=0,H.length=0,s.remove(),l.length)throw new AggregateError(l,"Editor cleanup failed.")}},_=(l,p)=>{i.addEventListener(l,p),le.push(()=>i.removeEventListener(l,p))};_("beforeinput",l=>{if(a){l.preventDefault();return}if(l.inputType==="historyUndo"||l.inputType==="historyRedo"){l.preventDefault(),l.inputType==="historyUndo"?L.undo():L.redo();return}if(!d&&!l.isComposing&&Ee(i,l.inputType)){l.preventDefault(),x(),u=void 0,Y(()=>xe(i,l.inputType));return}if(l.inputType==="insertText"&&l.data&&!d&&!l.isComposing&&T()&&Object.keys(f).length){l.preventDefault();let p=S(i).index,y=l.data,E={...f};Y(()=>{let M=N(i),F=(M.startContainer instanceof Element?M.startContainer:M.startContainer.parentElement)?.closest("p,h1,h2,h3,h4,h5,h6,li,blockquote,pre");F&&!F.textContent&&F.childNodes.length===1&&F.firstChild instanceof HTMLBRElement&&(F.replaceChildren(),M.selectNodeContents(F),M.collapse(!0)),M.insertNode(document.createTextNode(y)),O(i,p,y.length);for(let[U,ae]of Object.entries(E))(Object.hasOwn(R,U)?be(i)[U]??!1:!!be(i)[U])!==ae&&Le(i,U,ae);O(i,p+y.length),g=p+y.length},"insertText"),u=void 0;return}u=j()}),_("input",l=>{let p=l;if(a){i.innerHTML=v.html;return}if(d||p.isComposing)return;let y=u??v;u=void 0,Se(y,p.inputType)}),_("compositionstart",()=>{x(),d=!0,m=j()}),_("compositionend",()=>{d=!1;let l=m;m=void 0,u=void 0,l&&Se(l)}),_("paste",l=>{if(l.preventDefault(),a||!l.clipboardData)return;L.focus();let p=l.clipboardData.getData("text/html");if(p)L.insertHTML(p);else{let y=l.clipboardData.getData("text/plain"),E=document.createElement("div");E.textContent=y,L.insertHTML(E.innerHTML.replace(/\r?\n/g,"<br>"))}}),_("drop",l=>{l.preventDefault()}),_("keydown",l=>{if(!d&&!l.isComposing&&!a&&!l.ctrlKey&&!l.metaKey&&!l.altKey&&(l.key==="Enter"||l.key==="Backspace")){let E=l.key==="Backspace"?"deleteContentBackward":l.shiftKey?"insertLineBreak":"insertParagraph";if(Ee(i,E)){l.preventDefault(),x(),u=void 0,Y(()=>xe(i,E));return}}if(!d&&!l.isComposing&&!a&&l.key==="Tab"&&!l.ctrlKey&&!l.metaKey&&!l.altKey){let E=J(i);if(E.length&&E.every(M=>M.localName==="li"&&!M.closest("td,th"))&&re(i).canOutdent){l.preventDefault(),x(),Y(()=>he(i,l.shiftKey?-1:1));return}}if(d||l.isComposing||a||!(l.ctrlKey||l.metaKey)||l.altKey)return;let p=l.key.toLowerCase();(p==="z"||p==="y")&&(l.preventDefault(),p==="y"||l.shiftKey?L.redo():L.undo());let y={b:"bold",i:"italic",u:"underline"}[p];y&&(l.preventDefault(),L.format(y,L.getFormats().mixed?.includes(y)||!L.getFormats()[y]))}),document.addEventListener("selectionchange",K),le.push(()=>document.removeEventListener("selectionchange",K));try{L.setReadOnly(a);for(let l of t){let p=l.setup(L);p&&le.push(p)}return L}catch(l){throw L.destroy(),l}};var xt=[{label:"\u041E\u0442\u043C\u0435\u043D\u0438\u0442\u044C",text:"\u21B6",run:e=>e.undo(),enabled:e=>e.canUndo()},{label:"\u041F\u043E\u0432\u0442\u043E\u0440\u0438\u0442\u044C",text:"\u21B7",run:e=>e.redo(),enabled:e=>e.canRedo()},{label:"\u041F\u043E\u043B\u0443\u0436\u0438\u0440\u043D\u044B\u0439",text:"B",format:"bold"},{label:"\u041A\u0443\u0440\u0441\u0438\u0432",text:"I",format:"italic"},{label:"\u041F\u043E\u0434\u0447\u0451\u0440\u043A\u043D\u0443\u0442\u044B\u0439",text:"U",format:"underline"},{label:"\u0417\u0430\u0433\u043E\u043B\u043E\u0432\u043E\u043A",text:"H\u2082",format:"header",value:2},{label:"\u041C\u0430\u0440\u043A\u0438\u0440\u043E\u0432\u0430\u043D\u043D\u044B\u0439 \u0441\u043F\u0438\u0441\u043E\u043A",text:"\u2637",format:"list",value:"bullet"},{label:"\u041D\u0443\u043C\u0435\u0440\u043E\u0432\u0430\u043D\u043D\u044B\u0439 \u0441\u043F\u0438\u0441\u043E\u043A",text:"1.",format:"list",value:"ordered"},{label:"\u0423\u0432\u0435\u043B\u0438\u0447\u0438\u0442\u044C \u043E\u0442\u0441\u0442\u0443\u043F",text:"\u21E5",format:"indent",value:1,enabled:e=>!!e.getFormats().canIndent},{label:"\u0423\u043C\u0435\u043D\u044C\u0448\u0438\u0442\u044C \u043E\u0442\u0441\u0442\u0443\u043F",text:"\u21E4",format:"indent",value:-1,enabled:e=>!!e.getFormats().canOutdent},{label:"\u0426\u0438\u0442\u0430\u0442\u0430",text:"\u275D",format:"blockquote"},{label:"\u041E\u0447\u0438\u0441\u0442\u0438\u0442\u044C \u0444\u043E\u0440\u043C\u0430\u0442\u0438\u0440\u043E\u0432\u0430\u043D\u0438\u0435",text:"Tx",format:"clear",enabled:e=>!!e.getSelection()?.length}],Tt=(e,r,t=xt,n={})=>{t=t.map(f=>f.format&&Object.hasOwn(R,f.format)?{...f,value:X(f.format,f.value)}:f);let o=document.createElement("div");o.className="mw-toolbar",o.setAttribute("role","toolbar"),o.setAttribute("aria-label",n.label??"\u0424\u043E\u0440\u043C\u0430\u0442\u0438\u0440\u043E\u0432\u0430\u043D\u0438\u0435");let s,i=!1,c=0,a=[],d=t.map(f=>{let g=document.createElement("button");g.type="button",g.textContent=f.text,g.title=f.label,g.setAttribute("aria-label",f.label);let x=k=>k.preventDefault(),T=()=>{if(!(i||g.disabled||r.isReadOnly())&&(r.focus(),s&&W(r.surface,s),!(f.enabled&&!f.enabled(r)))){if(f.run)f.run(r);else if(f.format){let k=r.getFormats(),H=k.mixed?.includes(f.format);r.format(f.format,!H&&k[f.format]===(f.value??!0)?!1:f.value??!0)}m()}};return g.addEventListener("mousedown",x),g.addEventListener("click",T),a.push(()=>{g.removeEventListener("mousedown",x),g.removeEventListener("click",T)}),o.append(g),g}),m=()=>{if(i)return;s=Z(r.surface)??s;let f=r.getFormats();d.forEach((g,x)=>{let T=t[x];g.disabled=r.isReadOnly()||(T.enabled?!T.enabled(r):!1),T.format&&!["indent","clear"].includes(T.format)&&g.setAttribute("aria-pressed",f.mixed?.includes(T.format)?"mixed":String(f[T.format]===(T.value??!0)))}),(d[c]?.disabled||!d[c])&&(c=d.findIndex(g=>!g.disabled)),d.forEach((g,x)=>{g.tabIndex=x===c?0:-1})},u=f=>{let g=d.filter(H=>!H.disabled);if(!g.length)return;let x=g.indexOf(document.activeElement);if(x<0||f.ctrlKey||f.metaKey||f.altKey)return;if(f.key==="Escape"){f.preventDefault(),r.focus(),s&&W(r.surface,s);return}let T=getComputedStyle(o).direction==="rtl"?-1:1,k=f.key==="Home"?0:f.key==="End"?g.length-1:f.key==="ArrowRight"?(x+T+g.length)%g.length:f.key==="ArrowLeft"?(x-T+g.length)%g.length:-1;k>=0&&(f.preventDefault(),c=d.indexOf(g[k]),m(),g[k].focus())};o.addEventListener("keydown",u);let h=r.subscribe(f=>{f.source==="api"&&(s=void 0),m()}),b=r.onSelectionChange(m);return e.append(o),m(),()=>{if(!i){i=!0,h(),b(),o.removeEventListener("keydown",u);for(let f of a)f();o.remove()}}};export{Et as createEditor,bt as createPluginEvent,Tt as createToolbar,fe as sanitizeHTML};
|
|
1
|
+
var Nt=["p","h1","h2","h3","h4","h5","h6","blockquote","pre","code","strong","em","u","s","sub","sup","a","span","br","hr","ul","ol","li","img","figure","figcaption","table","caption","colgroup","col","thead","tbody","tfoot","tr","td","th"],ze=new Set(Nt),Mt=new Set(["script","style","iframe","object","embed","svg","math","template","form","input","button","textarea","select","noscript","link","meta","base"]),Ct={b:"strong",i:"em",strike:"s",div:"p"},Ke=1e5,_e=100,St=(e,r)=>{let t=e.trim();if(!t||/[\u0000-\u0020\u007f]/.test(t))return;let n=/^([a-z][a-z\d+.-]*):/i.exec(t)?.[1].toLowerCase();if(!(n&&!(r?["http","https"]:["http","https","mailto","tel"]).includes(n))&&!(t.startsWith("\\")||t.startsWith("//")))return t},Ht=e=>{let r=[];for(let t of e.split(";")){let n=t.indexOf(":");if(n<0)continue;let o=t.slice(0,n).trim().toLowerCase(),s=t.slice(n+1).trim().toLowerCase(),i=/^(#[a-f\d]{3,8}|[a-z]{1,24}|(?:rgb|rgba|hsl|hsla)\([\d\s.,%+-]+\))$/,a=/^(?:\d{1,4}(?:\.\d{1,3})?)(?:px|%|em|rem)$/;(["color","background-color","border-color"].includes(o)?i.test(s):["width","height","font-size"].includes(o)?a.test(s):o==="text-align"?["left","center","right","justify"].includes(s):o==="font-weight"?/^(bold|normal|[1-9]00)$/.test(s):o==="font-style"?["italic","normal"].includes(s):o==="text-decoration"?/^(underline|line-through|none)$/.test(s):!1)&&r.push(`${o}: ${s}`)}return r.join("; ")},Ue=(e,r)=>{let t={};for(let[n,o]of Object.entries(r))if(!(typeof o!="string"||o.length>2e4))if(n==="style"){let s=Ht(o);s&&(t.style=s)}else if(n==="title"||e==="img"&&n==="alt")t[n]=o;else if(e==="a"&&n==="href"||e==="img"&&n==="src"){let s=St(o,e==="img");s&&(t[n]=s)}else if(["td","th"].includes(e)&&["rowspan","colspan"].includes(n)||["img","col","table"].includes(e)&&["width","height","span"].includes(n))/^\d{1,4}$/.test(o)&&Number(o)>0&&Number(o)<=1e3&&(t[n]=o);else if(e==="a"&&n==="target"&&["_self","_blank"].includes(o))t.target=o;else if(e==="a"&&n==="rel"){let s=[...new Set(o.toLowerCase().split(/\s+/).filter(i=>["noopener","noreferrer"].includes(i)))];s.length&&(t.rel=s.join(" "))}else e==="th"&&n==="scope"&&["row","col","rowgroup","colgroup"].includes(o)&&(t[n]=o);if(e==="img"&&(t.width||t.height)){let n=["width","height"].filter(s=>t[s]),o=(t.style??"").split(";").map(s=>s.trim()).filter(s=>s&&!n.includes(s.slice(0,s.indexOf(":")).trim()));t.style=[...o,...n.map(s=>`${s}: ${t[s]}px`)].join("; ")}return e==="a"&&t.target==="_blank"&&(t.rel="noopener noreferrer"),t},We=(e,r,t)=>{if(++t.count>Ke||r>_e)throw new RangeError("Document exceeds structural limits.");if(e.nodeType===3)return[{type:"text",text:e.textContent??""}];if(e.nodeType!==1)return[];let n=e,o=n.localName.toLowerCase();if(n.namespaceURI!=="http://www.w3.org/1999/xhtml"||Mt.has(o))return[];let s=[...n.childNodes].flatMap(c=>We(c,r+1,t)),i=Ct[o]??o;if(!ze.has(i))return s;let a=Ue(i,Object.fromEntries([...n.attributes].map(c=>[c.name,c.value])));return i==="img"&&!a.src?[]:[{type:"element",tag:i,attributes:a,children:s}]},S=e=>{if(e.length>5e6)throw new RangeError("HTML exceeds the document size limit.");let r=document.createElement("template");r.innerHTML=e;let t={count:0};return{version:1,children:[...r.content.childNodes].flatMap(n=>We(n,0,t))}},xe=e=>{if(!e||typeof e!="object"||!("version"in e)||e.version!==1||!("children"in e)||!Array.isArray(e.children))throw new TypeError("Expected a version 1 document.");let r=0,t=0,n=(o,s)=>{if(++r>Ke||s>_e)throw new RangeError("Document exceeds structural limits.");if(!o||typeof o!="object"||!("type"in o))throw new TypeError("Invalid document node.");if(o.type==="text"&&"text"in o&&typeof o.text=="string"){if(t+=o.text.length,t>5e6)throw new RangeError("Document text exceeds size limit.");return{type:"text",text:o.text}}if(o.type!=="element"||!("tag"in o)||typeof o.tag!="string"||!ze.has(o.tag)||!("children"in o)||!Array.isArray(o.children))throw new TypeError("Invalid document element.");let i="attributes"in o&&o.attributes&&typeof o.attributes=="object"&&!Array.isArray(o.attributes)?o.attributes:{};return{type:"element",tag:o.tag,attributes:Ue(o.tag,i),children:o.children.map(a=>n(a,s+1))}};return{version:1,children:e.children.map(o=>n(o,0))}},te=e=>{let r=document.createDocumentFragment(),t=(n,o)=>{if(o.type==="text"){n.appendChild(document.createTextNode(o.text));return}let s=document.createElement(o.tag);for(let[i,a]of Object.entries(o.attributes))s.setAttribute(i,a);for(let i of o.children)t(s,i);n.appendChild(s)};for(let n of e.children)t(r,n);return r},q=e=>{let r=document.createElement("div");return r.append(te(e)),r.innerHTML},He=e=>q(S(e));var L=e=>{let r=e.ownerDocument.getSelection();if(!r?.rangeCount)return;let t=r.getRangeAt(0);if(!(!e.contains(t.startContainer)||!e.contains(t.endContainer)))return t.cloneRange()},Je=(e,r)=>{let t=[],n=r;for(;n!==e&&n.parentNode;)t.unshift([...n.parentNode.childNodes].indexOf(n)),n=n.parentNode;return t},ae=e=>{let r=L(e);if(!r)return;let t=e.ownerDocument.getSelection();return{start:Je(e,r.startContainer),startOffset:r.startOffset,end:Je(e,r.endContainer),endOffset:r.endOffset,backward:!r.collapsed&&t.anchorNode===r.endContainer&&t.anchorOffset===r.endOffset}},$=(e,r)=>{if(!r)return;let t=d=>d.reduce((f,u)=>f.childNodes[u]??f,e),n=t(r.start),o=t(r.end),s=(d,f)=>Math.min(f,d.nodeType===3?d.textContent?.length??0:d.childNodes.length),i=e.ownerDocument.getSelection();if(!i)return;let a=s(n,r.startOffset),c=s(o,r.endOffset);r.backward?i.setBaseAndExtent(o,c,n,a):i.setBaseAndExtent(n,a,o,c)},H=e=>{let r=L(e);if(!r)return;let t=e.ownerDocument.createRange();return t.selectNodeContents(e),t.setEnd(r.startContainer,r.startOffset),{index:t.toString().length,length:r.toString().length}},D=(e,r,t=0)=>{if(![r,t].every(g=>Number.isInteger(g)&&g>=0))throw new RangeError("Selection offsets must be non-negative integers.");let n=e.ownerDocument.createTreeWalker(e,4),o=[],s;for(;s=n.nextNode();)o.push(s);let i=g=>{for(let b of o){if(g<=b.length)return[b,g];g-=b.length}let m=o.at(-1);return m?[m,m.length]:[e.querySelector("p,h1,h2,h3,h4,h5,h6,li,blockquote,pre")??e,0]},[a,c]=i(r),[d,f]=i(r+t),u=e.ownerDocument.createRange();u.setStart(a,c),u.setEnd(d,f),e.focus({preventScroll:!0});let p=e.ownerDocument.getSelection();p?.removeAllRanges(),p?.addRange(u)},G=(e,r=!1)=>{let t=e.ownerDocument.createRange();t.selectNodeContents(e),t.collapse(!r);let n=e.ownerDocument.getSelection();n?.removeAllRanges(),n?.addRange(t)},z=(e,r)=>{let t=L(e);if(!t)return;let n=e.ownerDocument.getSelection(),o=!t.collapsed&&n.anchorNode===t.endContainer&&n.anchorOffset===t.endOffset,s=e.ownerDocument.createComment("mw-start"),i=t.collapsed?void 0:e.ownerDocument.createComment("mw-end");if(i){let c=t.cloneRange();c.collapse(!1),c.insertNode(i)}let a=t.cloneRange();a.collapse(!0),a.insertNode(s);try{if(r(),e.contains(s)&&(!i||e.contains(i))){let c=e.ownerDocument.createRange();c.setStartBefore(s),i?c.setEndBefore(i):c.collapse(!0),s.remove(),i?.remove(),e.normalize(),o?n.setBaseAndExtent(c.endContainer,c.endOffset,c.startContainer,c.startOffset):(n.removeAllRanges(),n.addRange(c))}}finally{s.remove(),i?.remove()}};var Ve="p,h1,h2,h3,h4,h5,h6,blockquote,pre,li",v=e=>!!e&&/^(ul|ol)$/.test(e.localName),At=e=>e instanceof Element?e:e.parentElement,ue=(e,r,t=!0)=>{let n=At(r),o=n?.closest("li"),s=(t&&o&&e.contains(o)?o:void 0)??n?.closest(Ve);return s&&e.contains(s)?s:void 0},Dt=(e,r)=>{let t=r.ownerDocument.createRange();r.nodeType===3?t.selectNodeContents(r):t.selectNode(r);let n=e.cloneRange();n.collapse(!0);let o=e.cloneRange();o.collapse(!1);let s=t.cloneRange();s.collapse(!0);let i=t.cloneRange();return i.collapse(!1),n.compareBoundaryPoints(Range.START_TO_START,i)<0&&o.compareBoundaryPoints(Range.START_TO_START,s)>0},ne=(e,r=L(e),t=!0)=>{if(!r)return[];if(r.collapsed){let i=ue(e,r.startContainer,t);return i?[i]:[]}let n=new Set,o=e.ownerDocument.createTreeWalker(e,NodeFilter.SHOW_TEXT|NodeFilter.SHOW_ELEMENT),s;for(;s=o.nextNode();)if(!(!(s.nodeType===3&&s.textContent)&&!(s instanceof Element&&/^(br|img|hr)$/.test(s.localName)))&&Dt(r,s)){let i=ue(e,s,t);i&&n.add(i)}return[...e.querySelectorAll(Ve)].filter(i=>n.has(i))},Ge=e=>e.filter(r=>!e.some(t=>t!==r&&t.contains(r))),Ye=e=>{let r=Ge(ne(e));if(!r.length||r.some(o=>o.localName!=="li"||!v(o.parentElement)))return[];let t=r[0].parentElement;if(r.some(o=>o.parentElement!==t))return[];let n=[...t.children];return n.indexOf(r.at(-1))-n.indexOf(r[0])+1!==r.length?[]:r},Xe=(e,r)=>{let t=0,n=r.parentElement;for(;n&&n!==e;)v(n)&&t++,n=n.parentElement;return t},Ze=(e,r)=>!!e&&e.localName===r.localName&&v(e)&&e.getAttribute("style")===r.getAttribute("style"),ce=e=>{for(let r of[...e.querySelectorAll("ul,ol")]){if(!e.contains(r))continue;let t=r.previousSibling;t instanceof Element&&Ze(t,r)&&(t.append(...r.childNodes),r.remove())}},et=(e,r)=>{let t=e.parentElement,n=t.cloneNode(!1);for(;e.nextSibling;)n.append(e.nextSibling);e.remove(),t.after(...r,...n.childNodes.length?[n]:[]),t.childNodes.length||t.remove()},de=e=>[...e.childNodes].filter(r=>!(r instanceof Element&&v(r))),tt=(e,r=!1)=>{let t=()=>{let a=document.createElement("p");return e.hasAttribute("style")&&a.setAttribute("style",e.getAttribute("style")),a},n=t(),o=[...e.children].filter(v),s=de(e),i=[];for(let a of s)r&&a instanceof HTMLElement&&/^(p|h[1-6]|blockquote|pre)$/.test(a.localName)?n.append(...a.childNodes):a instanceof HTMLElement&&/^(p|h[1-6]|blockquote|pre)$/.test(a.localName)?(n.childNodes.length&&i.push(n),n=t(),i.push(a)):n.append(a);(n.childNodes.length||!i.length)&&(n.childNodes.length||n.append(document.createElement("br")),i.push(n)),et(e,[...i,...o])},ke=e=>{let r=e[0].parentElement,t=r.parentElement;if(t?.localName!=="li"||!v(t.parentElement)){for(let o of e)tt(o);return}let n=r.cloneNode(!1);for(;e.at(-1).nextSibling;)n.append(e.at(-1).nextSibling);n.childNodes.length&&e.at(-1).append(n),t.after(...e),r.childNodes.length||r.remove()},fe=e=>{let r=Ye(e),t=!!r.length&&r[0].previousElementSibling?.localName==="li"&&r.every(n=>[n,...n.querySelectorAll("li")].every(o=>Xe(e,o)<8));return{listDepth:r.length?Xe(e,r[0]):0,canIndent:t,canOutdent:!!r.length}},we=(e,r)=>{if(r!==1&&r!==-1)throw new TypeError("List indentation requires 1 or -1.");let t=Ye(e);if(!t.length)throw new RangeError("Select consecutive items in the same list.");r===1&&!fe(e).canIndent||z(e,()=>{if(r===-1)ke(t);else{let n=t[0].parentElement,o=t[0].previousElementSibling,s=o.lastElementChild;Ze(s,n)||(s=n.cloneNode(!1),o.append(s)),s.append(...t)}ce(e)})},nt=(e,r)=>{if(r!==!1&&r!=="bullet"&&r!=="ordered")throw new TypeError("Expected bullet, ordered or false.");let t=Ge(ne(e));if(t.some(n=>n.localName==="li"&&!v(n.parentElement)))throw new RangeError("A list item must belong to a list.");z(e,()=>{for(let n of t){if(!r){n.localName==="li"&&ke([n]);continue}let o=r==="bullet"?"ul":"ol";if(n.localName==="li"){if(n.parentElement.localName===o)continue;let s=document.createElement(o);n.parentElement.hasAttribute("style")&&s.setAttribute("style",n.parentElement.getAttribute("style")),et(n,[s]),s.append(n)}else{let s=document.createElement(o),i=document.createElement("li");n.hasAttribute("style")&&i.setAttribute("style",n.getAttribute("style")),i.append(...n.childNodes),s.append(i),n.replaceWith(s)}}ce(e)})},Rt=e=>!e.textContent?.trim()&&!e.querySelector("img,hr,ul,ol"),Qe=e=>{de(e).some(n=>n.textContent||n instanceof Element&&(n.matches("br,img,hr")||n.querySelector("br,img,hr")))||([...e.children].some(v)?e.prepend(Object.assign(document.createElement("p"),{innerHTML:"<br>"})):e.append(document.createElement("br")))},vt=(e,r)=>{let t=r.cloneRange();return t.selectNodeContents(e),t.setEnd(r.startContainer,r.startOffset),!t.toString()&&!t.cloneContents().querySelector("img,hr,br")},Ae=(e,r)=>{let t=L(e);if(!t)return!1;let n=ue(e,t.startContainer);return n?.localName!=="li"||!v(n.parentElement)||ue(e,t.endContainer)!==n?!1:["insertParagraph","insertLineBreak"].includes(r)||r==="deleteContentBackward"&&t.collapsed&&vt(n,t)},De=(e,r)=>{let t=L(e),n=ue(e,t.startContainer);if(r==="insertParagraph"){if(Rt(n)){z(e,()=>{let c=n.parentElement.parentElement;c?.localName==="li"&&v(c.parentElement)?ke([n]):tt(n,!0)}),ce(e);return}t.deleteContents();let o=t.cloneRange();o.selectNodeContents(n),o.setStart(t.startContainer,t.startOffset);let s=n.cloneNode(!1);s.append(o.extractContents()),n.after(s),Qe(n),Qe(s);let i=document.createTreeWalker(s,NodeFilter.SHOW_TEXT),a;do a=i.nextNode();while(a&&(!a.textContent||a.parentElement?.closest("li")!==s));if(a){let c=document.createRange();c.setStart(a,0),c.collapse(!0);let d=document.getSelection();d?.removeAllRanges(),d?.addRange(c)}else G(s.querySelector("p,h1,h2,h3,h4,h5,h6,pre")??s)}else if(r==="insertLineBreak"){t.deleteContents();let o=document.createElement("br");t.insertNode(o),o.nextSibling||o.after(document.createElement("br")),t.setStartAfter(o),t.collapse(!0);let s=document.getSelection();s?.removeAllRanges(),s?.addRange(t)}else{let o=n.previousElementSibling;if(o&&o.localName!=="li")return;if(!o){z(e,()=>ke([n])),ce(e);return}if(!de(o).some(p=>p.textContent||p instanceof Element&&(p.localName==="img"||p.querySelector("img"))))for(let p of[...o.querySelectorAll("br")])p.closest("li")===o&&p.remove();let s=document.createComment("mw-join"),a=de(o).at(-1),c=a instanceof HTMLElement&&/^(p|h[1-6]|blockquote|pre)$/.test(a.localName)?a:o;c===o?o.insertBefore(s,[...o.children].find(v)??null):c.append(s);let d=de(n);d[0]instanceof HTMLElement&&/^(p|h[1-6])$/.test(d[0].localName)&&d.splice(0,1,...d[0].childNodes),s.after(...d);for(let p of[...n.children].filter(v))o.append(p);n.remove(),ce(e);let f=document.createRange();f.setStartBefore(s),f.collapse(!0),s.remove();let u=document.getSelection();u?.removeAllRanges(),u?.addRange(f)}};var Ot=new Set(["p","h1","h2","h3","h4","h5","h6"]),jt=new Set(["strong","em","u","s","sub","sup","a","span","code","br"]),rt=e=>[...e.childNodes].every(r=>r.nodeType===3||r instanceof HTMLElement&&jt.has(r.localName)&&rt(r)),Bt=e=>e.nodeType===1?e:e.parentElement,Re=(e,r)=>{let t=Bt(r)?.closest("p,h1,h2,h3,h4,h5,h6");if(!(t instanceof HTMLElement)||t.namespaceURI!=="http://www.w3.org/1999/xhtml"||!e.contains(t)||t.closest("li,figure,pre")||!rt(t))return;let n=t.parentElement;if(!(n!==e&&!["blockquote","td","th"].includes(n?.localName??"")))return t},ot=e=>!!(e.textContent||e.querySelector("br")),st=e=>{let r=L(e);if(!r)return;let t=Re(e,r.startContainer);return t&&Re(e,r.endContainer)===t?t:void 0},ve=(e,r,t)=>{if(!e.textContent&&e.querySelectorAll("br").length<=1)return!0;let n=e.ownerDocument.createRange();n.selectNodeContents(e),t?n.setStart(r.endContainer,r.endOffset):n.setEnd(r.startContainer,r.startOffset);let o=n.cloneContents();return!ot(o)},It=(e,r,t)=>{let n=t?r.nextSibling:r.previousSibling;return n instanceof HTMLElement&&Ot.has(n.localName)&&Re(e,n)===n?n:void 0},me=(e,r)=>{let t=st(e),n=L(e);return!t||!n?!1:r==="insertParagraph"||r==="insertLineBreak"?!0:n.collapsed?r==="deleteContentBackward"?ve(t,n,!1):r==="deleteContentForward"?ve(t,n,!0):!1:!1},Le=(e,r)=>{let t=st(e),n=L(e);if(!t||!n||!me(e,r))return;let o=e.ownerDocument;if(r==="insertParagraph"){n.deleteContents();let u=o.createRange();u.selectNodeContents(t),u.setStart(n.startContainer,n.startOffset);let p=u.extractContents(),g=t.localName!=="p"&&!t.textContent&&!p.textContent&&t.querySelectorAll("br").length+p.querySelectorAll("br").length<=1,m=t.localName!=="p"&&(!ot(p)||g);if(g){let x=o.createElement("p");for(let T of t.attributes)x.setAttribute(T.name,T.value);x.append(o.createElement("br")),t.replaceWith(x),G(x);return}let b=m?o.createElement("p"):t.cloneNode(!1);if(m)for(let x of t.attributes)b.setAttribute(x.name,x.value);b.append(p),!b.textContent&&!b.querySelector("br")&&b.replaceChildren(o.createElement("br")),!t.textContent&&!t.querySelector("br")&&t.replaceChildren(o.createElement("br")),t.after(b),G(b);return}if(r==="insertLineBreak"){n.deleteContents(),!t.textContent&&t.querySelectorAll("br").length<=1&&(t.replaceChildren(),n.selectNodeContents(t),n.collapse(!0));let u=ve(t,n,!0),p=o.createElement("br");n.insertNode(p),u&&p.after(o.createElement("br"));let g=o.createRange();g.setStartAfter(p),g.collapse(!0);let m=o.getSelection();m?.removeAllRanges(),m?.addRange(g);return}let s=r==="deleteContentForward",i=It(e,t,s);if(!i)return;let a=s?t:i,c=s?i:t;!a.textContent&&a.childNodes.length===1&&a.firstChild instanceof HTMLBRElement&&a.replaceChildren(),!c.textContent&&c.childNodes.length===1&&c.firstChild instanceof HTMLBRElement&&c.replaceChildren();let d=o.createRange();d.selectNodeContents(a),d.collapse(!1),a.append(...c.childNodes),c.remove(),a.childNodes.length||a.append(o.createElement("br")),a.normalize();let f=o.getSelection();f?.removeAllRanges(),f?.addRange(d)};var I={color:"color",background:"background-color"},lt=new Set(["p","h1","h2","h3","h4","h5","h6","blockquote","pre","ul","ol","li","table","thead","tbody","tfoot","tr","td","th","caption","colgroup","figure","figcaption"]),je=(e,r)=>xe({version:1,children:[{type:"element",tag:e,attributes:r,children:[]}]}).children[0].attributes,re=(e,r)=>{if(r===!1)return!1;if(typeof r!="string"||!r.trim()||r.length>128||/[;{}]/.test(r))throw new TypeError("Expected a CSS color or false.");let t=I[e],n=je("span",{style:`${t}: ${r}`}),o=document.createElement("span");o.setAttribute("style",n.style??"");let s=o.style.getPropertyValue(t);if(!s)throw new TypeError("Unsupported or invalid CSS color.");return s},at=e=>{if(e===!1)return!1;let r=typeof e=="string"?{href:e}:e;if(!r||typeof r!="object"||Array.isArray(r)||!("href"in r)||typeof r.href!="string")throw new TypeError("Expected a link URL, LinkFormat or false.");let t=r,n={href:r.href};if(t.title!==void 0){if(typeof t.title!="string"||t.title.length>1024)throw new TypeError("Link title must be a string up to 1024 characters.");n.title=t.title}if(t.target!==void 0){if(t.target!=="_self"&&t.target!=="_blank")throw new TypeError("Link target must be _self or _blank.");n.target=t.target}if(t.text!==void 0&&(typeof t.text!="string"||!t.text.length||t.text.length>2e4))throw new TypeError("New link text must contain 1\u201320000 characters.");let o=je("a",n);if(!o.href)throw new TypeError("Unsupported or unsafe link URL.");return{attributes:o,...typeof t.text=="string"?{text:t.text}:{}}},Be=(e,r)=>{let t={...e,...r};return t.title||delete t.title,r.target==="_self"&&delete t.rel,je("a",t)},ct=(e,r)=>JSON.stringify(Object.entries(e??{}).sort())===JSON.stringify(Object.entries(r??{}).sort()),qt=(e,r)=>{let t={...e},n=(t.style??"").split(";").map(o=>o.trim()).filter(o=>o&&o.slice(0,o.indexOf(":")).trim()!==r).join("; ");return n?t.style=n:delete t.style,t},it=e=>{let r=[];for(let t of e){let n=r.at(-1);n&&n.selected===t.selected&&ct(n.link,t.link)?n.pieces.push(t):r.push({pieces:[t],selected:t.selected,link:t.link})}return r},Oe=e=>{let r=[];for(let t of e){let n=t.type==="element"?{...t,children:Oe(t.children)}:t,o=r.at(-1);n.type==="text"&&o?.type==="text"?o.text+=n.text:n.type==="element"&&o?.type==="element"&&!lt.has(n.tag)&&!["img","br","hr"].includes(n.tag)&&o.tag===n.tag&&ct(o.attributes,n.attributes)?o.children=Oe([...o.children,...n.children]):r.push(n)}return r},Ne=(e,r,t,n)=>{let o=0,s=a=>it(a).flatMap(c=>{let d=c.pieces.map(u=>u.node);if(n.kind==="style")return c.selected&&n.value!==!1?[{type:"element",tag:"span",attributes:{style:`${n.property}: ${n.value}`},children:d}]:d;let f=c.selected?n.attributes===!1?void 0:Be(c.link??{},n.attributes):c.link;return f?[{type:"element",tag:"a",attributes:f,children:d}]:d}),i=(a,c)=>{if(a.type==="text"){let u=o;o+=a.text.length;let p=Math.max(0,Math.min(a.text.length,r-u)),g=Math.max(p,Math.min(a.text.length,t-u));return[[0,p,!1],[p,g,!0],[g,a.text.length,!1]].flatMap(([m,b,x])=>{let T=a.text.slice(m,b);return T?[{node:{type:"text",text:T},selected:!!x,link:c}]:[]})}let d=n.kind==="link"&&a.tag==="a"?a.attributes:c;if(!a.children.length)return[{node:a,selected:o>=r&&o<t,link:d}];let f=a.children.flatMap(u=>i(u,d));return n.kind==="link"&&a.tag==="a"?f:lt.has(a.tag)?[{node:{...a,children:s(f)},selected:!1}]:it(f).flatMap(u=>{let p=n.kind==="style"&&u.selected?qt(a.attributes,n.property):a.attributes,g=u.pieces.map(m=>m.node);return a.tag==="span"&&!Object.keys(p).length?u.pieces:[{node:{...a,attributes:p,children:g},selected:u.selected,link:u.link}]})};return{version:1,children:Oe(s(e.children.flatMap(a=>i(a))))}};var dt=(e,r)=>{let t=at(r),n=L(e);if(!n)return;let o=H(e),s=n.startContainer.nodeType===1?n.startContainer:n.startContainer.parentElement,i=s?.closest("a"),a=i&&e.contains(i)?i:void 0;if(t&&t.text!==void 0&&(!n.collapsed||a))throw new TypeError("Link text is only supported for insertion at a caret outside links.");if(!n.collapsed){e.innerHTML=q(Ne(S(e.innerHTML),o.index,o.index+o.length,{kind:"link",attributes:t&&t.attributes})),D(e,o.index,o.length);return}if(a){let p=t&&Be(Object.fromEntries([...a.attributes].map(g=>[g.name,g.value])),t.attributes);z(e,()=>{if(!p)a.replaceWith(...a.childNodes);else{for(let g of[...a.attributes])a.removeAttribute(g.name);for(let[g,m]of Object.entries(p))a.setAttribute(g,m)}});return}if(!t||t.text===void 0)return;let c=e.ownerDocument.createElement("a");for(let[p,g]of Object.entries(t.attributes))c.setAttribute(p,g);c.textContent=t.text;let d=s?.closest("p,li,h1,h2,h3,h4,h5,h6,blockquote,pre,td,th");d?.childNodes.length===1&&d.firstChild instanceof HTMLBRElement&&(d.firstChild.remove(),n.setStart(d,0)),n.insertNode(c);let f=e.ownerDocument.createTextNode("");c.after(f),n.setStart(f,0),n.collapse(!0);let u=e.ownerDocument.getSelection();u?.removeAllRanges(),u?.addRange(n)};var Pt=new Set(["p","h1","h2","h3","h4","h5","h6","blockquote","pre","ul","ol","li","table","thead","tbody","tfoot","tr","td","th","caption","colgroup","figure","figcaption"]),ut=e=>e.type==="text"?e.text.length:e.children.reduce((r,t)=>r+ut(t),0),pe=(e,r,t,n,o)=>{let s=0,i=a=>{if(a.type==="text"){let f=s;s+=a.text.length;let u=Math.max(0,Math.min(a.text.length,r-f)),p=Math.max(u,Math.min(a.text.length,t-f));return[[0,u,!1],[u,p,!0],[p,a.text.length,!1]].flatMap(([g,m,b])=>{let x=a.text.slice(g,m);if(!x)return[];let T={type:"text",text:x};return[{node:b&&o?{type:"element",tag:n,attributes:{},children:[T]}:T,selected:!!b}]})}if(o&&a.tag===n)return s+=ut(a),[{node:a,selected:!1}];let c=a.children.flatMap(i);if(Pt.has(a.tag))return[{node:{...a,children:c.map(f=>f.node)},selected:!1}];if(!c.length)return[{node:a,selected:!1}];let d=[];for(let f of c){let u=d.at(-1);u?.selected===f.selected?u.children.push(f.node):d.push({selected:f.selected,children:[f.node]})}return d.flatMap(f=>a.tag===n&&!o&&f.selected?f.children.map(u=>({node:u,selected:!0})):[{node:{...a,children:f.children},selected:f.selected}])};return{version:1,children:e.children.flatMap(i).map(a=>a.node)}};var ft="p,h1,h2,h3,h4,h5,h6",Ft=new Set(["strong","em","u","s","sub","sup","a","span","code"]),$t=new Set(["blockquote","ul","ol","li","table","thead","tbody","tfoot","tr","td","th"]),mt=e=>e.nodeType===1?e:e.parentElement,pt=e=>{for(let r of e.childNodes){if(r.nodeType===3)continue;if(r.nodeType!==1)return!1;let t=r;if(t.namespaceURI!=="http://www.w3.org/1999/xhtml"||!Ft.has(t.localName)||!pt(t))return!1}return!0},ht=(e,r,t,n)=>{let o=mt(r.startContainer)?.closest(ft);if(!o||!e.contains(o)||o.namespaceURI!=="http://www.w3.org/1999/xhtml"||mt(r.endContainer)?.closest(ft)!==o||!pt(o))return!1;for(let g=o.parentElement;g&&g!==e;g=g.parentElement)if(g.namespaceURI!=="http://www.w3.org/1999/xhtml"||!$t.has(g.localName))return!1;let s=e.ownerDocument.createRange();s.selectNodeContents(o),s.setEnd(r.startContainer,r.startOffset);let i=s.toString().length,a=r.toString().length;if(!a||i+a>(o.textContent?.length??0))return!1;let c=e.ownerDocument.getSelection(),d=c?.anchorNode===r.endContainer&&c.anchorOffset===r.endOffset,f=pe(S(o.outerHTML),i,i+a,t,n),u=te(f),p=u.firstElementChild;if(u.childNodes.length!==1||!(p instanceof HTMLElement)||p.localName!==o.localName)return!1;if(p.normalize(),p.outerHTML===o.outerHTML)return!0;if(o.replaceWith(u),D(p,i,a),e.focus({preventScroll:!0}),d&&c?.rangeCount){let g=c.getRangeAt(0);c.setBaseAndExtent(g.endContainer,g.endOffset,g.startContainer,g.startOffset)}return!0};var oe={bold:"strong",italic:"em",underline:"u",strike:"s",code:"code",subscript:"sub",superscript:"sup"},zt=e=>e.nodeType===1?e:e.parentElement,gt=(e,r)=>{let t=zt(r),n={};for(;t&&t!==e;){for(let[o,s]of Object.entries(oe))t.localName===s&&(n[o]=!0);if(/^h[1-6]$/.test(t.localName)&&n.header===void 0&&(n.header=Number(t.localName[1])),t.localName==="blockquote"&&(n.blockquote=!0),t.localName==="pre"&&(n["code-block"]=!0),(t.localName==="ul"||t.localName==="ol")&&n.list===void 0&&(n.list=t.localName==="ul"?"bullet":"ordered"),t.localName==="a"&&n.link===void 0&&(n.link=t.getAttribute("href"),n.linkTitle=t.getAttribute("title")??"",n.linkTarget=t.getAttribute("target")??"_self"),t instanceof HTMLElement)for(let[o,s]of Object.entries(I))n[o]===void 0&&t.style.getPropertyValue(s)&&(n[o]=t.style.getPropertyValue(s));t instanceof HTMLElement&&t.style.textAlign&&n.align===void 0&&(n.align=t.style.textAlign),t=t.parentElement}return n},Me=e=>{let r=L(e);if(!r)return{};let t=gt(e,r.startContainer),n=new Set;if(!r.collapsed){let{index:o,length:s}=H(e),i=e.ownerDocument.createTreeWalker(e,NodeFilter.SHOW_TEXT),a=0,c,d=[];for(;c=i.nextNode();){let p=a+c.textContent.length;p>o&&a<o+s&&d.push(gt(e,c)),a=p}d.length&&(t=d[0]);let f=[...Object.keys(oe),"header","list","blockquote","code-block","link","linkTitle","linkTarget","color","background","align"],u=(p,g)=>p[g]??(g==="align"?"left":g==="header"?0:!1);for(let p of f)d.some(g=>u(g,p)!==u(d[0],p))&&n.add(p)}return{...t,align:t.align??"left",mixed:[...n],...fe(e)}},Ie=(e,r,t)=>{let n=L(e);if(!n)return;let o=oe[r];if(o&&!n.collapsed&&ht(e,n,o,!!t))return;let s=H(e);if(r==="list"){nt(e,t);return}if(r==="indent"){we(e,t);return}if(r==="clear"){if(t!==!0||!s.length)return;let a=S(e.innerHTML);for(let c of[...Object.values(oe),"a","span"])a=pe(a,s.index,s.index+s.length,c,!1);e.innerHTML=q(a),D(e,s.index,s.length);return}if(o){if(n.collapsed)return;e.innerHTML=q(pe(S(e.innerHTML),s.index,s.index+s.length,o,!!t)),D(e,s.index,s.length);return}if(r==="link"){dt(e,t);return}if(Object.hasOwn(I,r)){let a=re(r,t);if(!s.length)return;e.innerHTML=q(Ne(S(e.innerHTML),s.index,s.index+s.length,{kind:"style",property:I[r],value:a})),D(e,s.index,s.length);return}let i=ne(e,n,!1);if(!i.length){let a=document.createElement("p");a.append(n.extractContents()),a.childNodes.length||a.append(document.createElement("br")),n.insertNode(a),i=[a]}z(e,()=>{for(let a of i){if(r==="align"&&["left","center","right","justify",!1].includes(t)){a.style.textAlign=t?String(t):"";continue}let c=r==="header"?Number.isInteger(t)&&Number(t)>=1&&Number(t)<=6?`h${t}`:"p":r==="blockquote"?t?"blockquote":"p":r==="code-block"?t?"pre":"p":void 0;if(c){let d=document.createElement(c);if(a.localName==="li"){let f=[...a.childNodes].filter(u=>!(u instanceof Element&&/^(ul|ol|p|h[1-6]|pre|blockquote)$/.test(u.localName)));d.append(...f),a.prepend(d)}else d.append(...a.childNodes),d.setAttribute("style",a.getAttribute("style")??""),a.replaceWith(d)}}})};var yt=new WeakSet,Kt=new Set(["change","selectionchange","readonlychange","destroy"]),_t=e=>{if(typeof e!="string"||!e.trim()||e.length>200)throw new TypeError("Expected an event name with 1\u2013200 characters.");let r=Object.freeze({name:e});return yt.add(r),r},bt=e=>{if(!e||typeof e!="object"||!yt.has(e))throw new TypeError("Expected a plugin event token. Core events cannot be emitted publicly.");return e},Et=()=>{let e=new Map,r=[],t=0,n=!1,o=!1,s=c=>{if(o&&c.key!=="destroy"||(r.push(c),n))return;n=!0;let d=[];try{for(;r.length;){let f=r.shift();if(o&&f.key!=="destroy")continue;let u=e.get(f.key);for(let[p,g]of[...u??[]])if(!(o&&f.key!=="destroy"||u?.get(p)!==g))try{let m=f.core&&f.payload&&typeof f.payload=="object"?{...f.payload}:f.payload;p(m)}catch(m){d.push(m)}f.key==="destroy"&&(e.clear(),r.length=0)}}finally{n=!1}if(d.length)throw new AggregateError(d,"Editor event listeners failed.")};return{events:{on:(c,d)=>{if(o)throw new Error("Editor events have been destroyed.");if(typeof d!="function")throw new TypeError("Expected an event listener.");let f=typeof c=="string"&&Kt.has(c)?c:bt(c),u=e.get(f);u||(u=new Map,e.set(f,u)),u.has(d)||u.set(d,++t);let p=u.get(d);return()=>{u.get(d)===p&&(u.delete(d),!u.size&&e.get(f)===u&&e.delete(f))}},emit:(c,d)=>{if(o)throw new Error("Editor events have been destroyed.");s({key:bt(c),payload:d,core:!1})}},notify:(c,d)=>s({key:c,payload:d,core:!0}),destroy:()=>{o||(o=!0,r.length=0,s({key:"destroy",payload:void 0,core:!0}))}}};var Tt=e=>{let r,t="";return{read:()=>{let s=e.innerHTML;if(s===r)return t;let i=He(s);return r=s,t=i,i},clear:()=>{r=void 0,t=""}}};var xt=e=>e.isComposing||e.inputType==="insertCompositionText"||e.inputType==="insertFromComposition"||e.inputType==="deleteCompositionText",Y=e=>{let r=!1;e.childNodes.length||(e.innerHTML="<p><br></p>",r=!0);let t;for(let n of[...e.childNodes])n.nodeType===3||n.nodeType===1&&/^(strong|em|u|s|a|span|code|img|br|sub|sup)$/.test(n.localName)?(t||(t=document.createElement("p"),e.insertBefore(t,n)),t.append(n),r=!0):t=void 0;return["table","figure"].includes(e.lastElementChild?.localName??"")&&e.append(Object.assign(document.createElement("p"),{innerHTML:"<br>"})),e.dataset.empty=String(!e.textContent&&!e.querySelector("table,img,hr")),r},Ut=(e,r)=>{let t=L(e);if(!t)return;let n=te(S(r));if(!n.childNodes.length)return;t.deleteContents();let s=(t.startContainer.nodeType===1?t.startContainer:t.startContainer.parentElement)?.closest("p,h1,h2,h3,h4,h5,h6,li,blockquote,pre");if(n.childNodes.length===1&&n.firstChild instanceof HTMLParagraphElement&&s){let f=n.firstChild;n.replaceChildren(...f.childNodes)}let i=[...n.childNodes].some(f=>f instanceof HTMLElement&&/^(p|h[1-6]|ul|ol|table|figure|blockquote|pre)$/.test(f.localName)),a=n.lastChild;if(i&&s&&e.contains(s)){let f=document.createRange();f.selectNodeContents(s),f.setStart(t.startContainer,t.startOffset);let u=s.cloneNode(!1);u.append(f.extractContents()),s.after(n),(u.textContent||u.querySelector("img,br"))&&a.after(u),!s.textContent&&!s.querySelector("img")&&s.remove()}else t.insertNode(n);let c=document.createRange();c.setStartAfter(a),c.collapse(!0);let d=document.getSelection();d?.removeAllRanges(),d?.addRange(c)},Wt=(e,r={})=>{if(e.childNodes.length)throw new Error("Editor host must be empty. Pass initial HTML through value.");let t=r.plugins??[];if(new Set(t.map(l=>l.name)).size!==t.length)throw new Error("Duplicate editor plugin.");let n=r.historyLimit??100;if(!Number.isInteger(n)||n<1||n>1e4)throw new RangeError("historyLimit must be an integer from 1 to 10000.");let o=S(r.value??""),s=document.createElement("div");s.className="mw-editor";let i=document.createElement("div");i.className="mw-content",i.setAttribute("role","textbox"),i.setAttribute("aria-multiline","true"),i.setAttribute("aria-label",r.label??"\u0422\u0435\u043A\u0441\u0442\u043E\u0432\u044B\u0439 \u0440\u0435\u0434\u0430\u043A\u0442\u043E\u0440"),i.dataset.placeholder=r.placeholder??"\u041D\u0430\u0447\u043D\u0438\u0442\u0435 \u043F\u0438\u0441\u0430\u0442\u044C\u2026",s.append(i),e.append(s),i.append(te(o)),Y(i);let a=!1,c=r.readOnly??!1,d=!1,f,u=!1,p,g=!1,m,b=0,x="",T={},N,M=()=>{T={},N=void 0},se=()=>{let l=H(i);return l?.length===0&&l.index===N},A=[],P=[],F=Et(),K=0,he=!1,ge,ie=!1,le=new Map,be=[];r.onChange&&F.events.on("change",r.onChange);let k=()=>{if(a)throw new Error("Editor has been destroyed.")},J=l=>{if(!K)return;let h=new Error(`${l} is unavailable inside a transaction.`);throw he=!0,ge=h,h},kt={on:F.events.on,emit:(l,h)=>{k(),J("events.emit"),F.events.emit(l,h)}},ye=Tt(i),O=()=>({html:ye.read(),selection:ae(i),...N!==void 0&&Object.keys(T).length&&se()?{typing:{offset:N,formats:{...T}}}:{}}),Ce=l=>{M();let h=H(i);l.typing&&h?.length===0&&h.index===l.typing.offset&&(N=l.typing.offset,T={...l.typing.formats})},C=O(),_=C.selection,U=()=>{p=void 0,g=!1},Se=l=>{let h=f;u=u||d||p!==void 0,d=!1,f=void 0,m=void 0,U(),l&&h&&(i.innerHTML=h.html,Y(i),$(i,h.selection),Ce(h),C=O(),_=C.selection)},qe=()=>{i.innerHTML=C.html,Y(i),$(i,C.selection)},X=()=>{if(a)return;if(K){ie=!0;return}H(i)&&!se()&&M();let l=ae(i);l&&(_=l,C.selection=l),F.notify("selectionchange",H(i))},Z=l=>{let h={html:w.getHTML(),text:w.getText(),source:l},y=[];try{F.notify("change",h)}catch(E){y.push(E)}try{X()}catch(E){y.push(E)}if(y.length)throw new AggregateError(y,"Editor change notification failed.")},Ee=(l,h="")=>{let y=H(i);Y(i)&&y&&D(i,y.index,y.length);let E=O();if(E.html===l.html)return C=E,!1;let R=Date.now();return h===x&&["insertText","deleteContentBackward","deleteContentForward"].includes(h)&&R-b<600&&l.selection&&C.selection&&JSON.stringify(l.selection)===JSON.stringify(C.selection)||(A.push(l),A.length>n&&A.shift()),P.length=0,C=E,b=h?R:0,x=h,!0},wt=(l,h="")=>{Ee(l,h)&&Z("user")},Pe=l=>{M(),i.innerHTML=l.html,Y(i),i.focus({preventScroll:!0}),$(i,l.selection),Ce(l),C=O(),_=C.selection,b=0,Z("user")},Q=(l,h="")=>{if(k(),c||d)return;U();let y=()=>{if(typeof l!="function"||l.constructor.name==="AsyncFunction")throw new TypeError("Transactions require a synchronous callback.");let B=l(i);if(B&&(typeof B=="object"||typeof B=="function")&&typeof B.then=="function")throw B instanceof Promise&&B.catch(()=>{}),new TypeError("Transaction callbacks must not return a thenable.")};if(K){K++;try{y()}catch(B){throw he=!0,ge=B,B}finally{K--}return}w.focus();let E=O(),R=[...A],j=[...P],Fe=b,W=x,ee=m,Te=_;K=1,he=!1,ge=void 0,ie=!1;let $e=!1;try{if(y(),he)throw ge;$e=Ee(E,h)}catch(B){throw i.innerHTML=E.html,Y(i),$(i,E.selection),Ce(E),C=O(),_=Te,m=ee,A.splice(0,A.length,...R),P.splice(0,P.length,...j),b=Fe,x=W,K=0,ie=!1,B}finally{K=0}let Lt=ie;ie=!1,$e?Z("user"):Lt&&X()},w={element:s,surface:i,events:kt,getHTML:()=>(k(),ye.read()),getText:()=>(k(),i.innerText),getJSON:()=>(k(),S(i.innerHTML)),setHTML:l=>{k(),J("setHTML");let h=q(S(l));h!==w.getHTML()&&(Se(!1),M(),i.innerHTML=h,Y(i),A.length=0,P.length=0,b=0,_=void 0,C=O(),Z("api"))},setJSON:l=>{k(),J("setJSON");let h=xe(l);w.setHTML(q(h))},getSelection:()=>(k(),H(i)),setSelection:(l,h=0)=>{k(),D(i,l,h),X()},getFormats:()=>(k(),{...Me(i),...se()?T:{}}),setReadOnly:l=>{k(),J("setReadOnly");let h=c!==l;h&&l&&Se(!0),c=l,i.contentEditable=String(!l),i.setAttribute("aria-readonly",String(l)),s.dataset.readonly=String(l);let y=[];if(h)try{F.notify("readonlychange",l)}catch(E){y.push(E)}try{X()}catch(E){y.push(E)}if(y.length)throw new AggregateError(y,"Editor state notification failed.")},isReadOnly:()=>(k(),c),format:(l,h)=>{if(k(),c||d)return;U(),w.focus();let y=H(i);if(y?.length===0&&(Object.hasOwn(oe,l)||Object.hasOwn(I,l))){se()||M(),N=y.index,T[l]=Object.hasOwn(I,l)?re(l,h):!!h,X();return}M(),w.transact(()=>Ie(i,l,h))},insertHTML:l=>w.transact(()=>Ut(i,l)),focus:()=>{k(),i.focus({preventScroll:!0}),L(i)||(_?$(i,_):G(i.firstElementChild??i,!0))},undo:()=>{if(k(),J("undo"),c||d)return;U();let l=A.pop();l&&(P.push(O()),Pe(l))},redo:()=>{if(k(),J("redo"),c||d)return;U();let l=P.pop();l&&(A.push(O()),Pe(l))},canUndo:()=>(k(),A.length>0),canRedo:()=>(k(),P.length>0),transact:l=>Q(l),providePlugin:(l,h)=>{if(k(),le.has(l))throw new Error(`Plugin API already registered: ${l}`);return le.set(l,h),()=>{le.delete(l)}},getPlugin:l=>(k(),le.get(l)),subscribe:l=>(k(),F.events.on("change",l)),onSelectionChange:l=>(k(),F.events.on("selectionchange",l)),destroy:()=>{if(a)return;J("destroy"),Se(!1),a=!0;let l=[];try{F.destroy()}catch(h){l.push(h)}for(let h of be.reverse())try{h()}catch(y){l.push(y)}if(le.clear(),A.length=0,P.length=0,ye.clear(),s.remove(),l.length)throw new AggregateError(l,"Editor cleanup failed.")}},V=(l,h)=>{i.addEventListener(l,h),be.push(()=>i.removeEventListener(l,h))};V("beforeinput",l=>{if(l.defaultPrevented)return;if(c){l.preventDefault();return}let h=xt(l);if(u&&h){l.preventDefault();return}if(!(d||l.isComposing)){if(h||(u=!1,U()),l.inputType==="historyUndo"||l.inputType==="historyRedo"){l.preventDefault(),l.inputType==="historyUndo"?w.undo():w.redo();return}if(!d&&!l.isComposing&&Ae(i,l.inputType)){l.preventDefault(),M(),m=void 0,Q(()=>De(i,l.inputType));return}if(me(i,l.inputType)){l.preventDefault(),M(),m=void 0,Q(()=>Le(i,l.inputType));return}if(l.inputType==="insertText"&&l.data&&!d&&!l.isComposing&&se()&&Object.keys(T).length){l.preventDefault();let y=H(i).index,E=l.data,R={...T};Q(()=>{let j=L(i),W=(j.startContainer instanceof Element?j.startContainer:j.startContainer.parentElement)?.closest("p,h1,h2,h3,h4,h5,h6,li,blockquote,pre");W&&!W.textContent&&W.childNodes.length===1&&W.firstChild instanceof HTMLBRElement&&(W.replaceChildren(),j.selectNodeContents(W),j.collapse(!0)),j.insertNode(document.createTextNode(E)),D(i,y,E.length);for(let[ee,Te]of Object.entries(R))(Object.hasOwn(I,ee)?Me(i)[ee]??!1:!!Me(i)[ee])!==Te&&Ie(i,ee,Te);D(i,y+E.length),N=y+E.length},"insertText"),m=void 0;return}m=O()}}),V("input",l=>{let h=l,y=xt(h);if(c||u&&y){qe();return}if(d||h.isComposing)return;if(p&&y){let R=p,j=ye.read()!==C.html;if(m=void 0,!j)return;g&&A.at(-1)===R&&A.pop(),g=Ee(R),Z("user");return}u=!1,U();let E=m??C;m=void 0,wt(E,h.inputType)}),V("compositionstart",()=>{if(c){u=!0;return}d||(M(),U(),m=void 0,u=!1,f=O(),d=!0)}),V("compositionend",()=>{if(u){m=void 0,qe();return}d=!1;let l=f;f=void 0,m=void 0,l&&(p=l,g=Ee(l),g&&Z("user"))}),V("paste",l=>{if(l.preventDefault(),c||d||!l.clipboardData)return;w.focus();let h=l.clipboardData.getData("text/html");if(h)w.insertHTML(h);else{let y=l.clipboardData.getData("text/plain"),E=document.createElement("div");E.textContent=y,w.insertHTML(E.innerHTML.replace(/\r?\n/g,"<br>"))}}),V("drop",l=>{l.preventDefault()}),V("keydown",l=>{if(l.keyCode===229)return;if(!d&&!l.isComposing&&!c&&!l.ctrlKey&&!l.metaKey&&!l.altKey&&(l.key==="Enter"||l.key==="Backspace"||l.key==="Delete")){let E=l.key==="Backspace"?"deleteContentBackward":l.key==="Delete"?"deleteContentForward":l.shiftKey?"insertLineBreak":"insertParagraph";if(Ae(i,E)){l.preventDefault(),M(),m=void 0,Q(()=>De(i,E));return}if((l.key!=="Enter"||l.shiftKey)&&me(i,E)){l.preventDefault(),M(),m=void 0,Q(()=>Le(i,E));return}}if(!d&&!l.isComposing&&!c&&l.key==="Tab"&&!l.ctrlKey&&!l.metaKey&&!l.altKey){let E=ne(i);if(E.length&&E.every(R=>R.localName==="li"&&!R.closest("td,th"))&&fe(i).canOutdent){l.preventDefault(),M(),Q(()=>we(i,l.shiftKey?-1:1));return}}if(d||l.isComposing||c||!(l.ctrlKey||l.metaKey)||l.altKey)return;let h=l.key.toLowerCase();(h==="z"||h==="y")&&(l.preventDefault(),h==="y"||l.shiftKey?w.redo():w.undo());let y={b:"bold",i:"italic",u:"underline"}[h];y&&(l.preventDefault(),w.format(y,w.getFormats().mixed?.includes(y)||!w.getFormats()[y]))}),document.addEventListener("selectionchange",X),be.push(()=>document.removeEventListener("selectionchange",X));try{w.setReadOnly(c);for(let l of t){let h=l.setup(w);h&&be.push(h)}return w}catch(l){throw w.destroy(),l}};var Jt=[{label:"\u041E\u0442\u043C\u0435\u043D\u0438\u0442\u044C",text:"\u21B6",run:e=>e.undo(),enabled:e=>e.canUndo()},{label:"\u041F\u043E\u0432\u0442\u043E\u0440\u0438\u0442\u044C",text:"\u21B7",run:e=>e.redo(),enabled:e=>e.canRedo()},{label:"\u041F\u043E\u043B\u0443\u0436\u0438\u0440\u043D\u044B\u0439",text:"B",format:"bold"},{label:"\u041A\u0443\u0440\u0441\u0438\u0432",text:"I",format:"italic"},{label:"\u041F\u043E\u0434\u0447\u0451\u0440\u043A\u043D\u0443\u0442\u044B\u0439",text:"U",format:"underline"},{label:"\u0417\u0430\u0433\u043E\u043B\u043E\u0432\u043E\u043A",text:"H\u2082",format:"header",value:2},{label:"\u041C\u0430\u0440\u043A\u0438\u0440\u043E\u0432\u0430\u043D\u043D\u044B\u0439 \u0441\u043F\u0438\u0441\u043E\u043A",text:"\u2637",format:"list",value:"bullet"},{label:"\u041D\u0443\u043C\u0435\u0440\u043E\u0432\u0430\u043D\u043D\u044B\u0439 \u0441\u043F\u0438\u0441\u043E\u043A",text:"1.",format:"list",value:"ordered"},{label:"\u0423\u0432\u0435\u043B\u0438\u0447\u0438\u0442\u044C \u043E\u0442\u0441\u0442\u0443\u043F",text:"\u21E5",format:"indent",value:1,enabled:e=>!!e.getFormats().canIndent},{label:"\u0423\u043C\u0435\u043D\u044C\u0448\u0438\u0442\u044C \u043E\u0442\u0441\u0442\u0443\u043F",text:"\u21E4",format:"indent",value:-1,enabled:e=>!!e.getFormats().canOutdent},{label:"\u0426\u0438\u0442\u0430\u0442\u0430",text:"\u275D",format:"blockquote"},{label:"\u041E\u0447\u0438\u0441\u0442\u0438\u0442\u044C \u0444\u043E\u0440\u043C\u0430\u0442\u0438\u0440\u043E\u0432\u0430\u043D\u0438\u0435",text:"Tx",format:"clear",enabled:e=>!!e.getSelection()?.length}],Xt=(e,r,t=Jt,n={})=>{t=t.map(m=>m.format&&Object.hasOwn(I,m.format)?{...m,value:re(m.format,m.value)}:m);let o=document.createElement("div");o.className="mw-toolbar",o.setAttribute("role","toolbar"),o.setAttribute("aria-label",n.label??"\u0424\u043E\u0440\u043C\u0430\u0442\u0438\u0440\u043E\u0432\u0430\u043D\u0438\u0435");let s,i=!1,a=0,c=[],d=t.map(m=>{let b=document.createElement("button");b.type="button",b.textContent=m.text,b.title=m.label,b.setAttribute("aria-label",m.label);let x=N=>N.preventDefault(),T=()=>{if(!(i||b.disabled||r.isReadOnly())&&(r.focus(),s&&$(r.surface,s),!(m.enabled&&!m.enabled(r)))){if(m.run)m.run(r);else if(m.format){let N=r.getFormats(),M=N.mixed?.includes(m.format);r.format(m.format,!M&&N[m.format]===(m.value??!0)?!1:m.value??!0)}f()}};return b.addEventListener("mousedown",x),b.addEventListener("click",T),c.push(()=>{b.removeEventListener("mousedown",x),b.removeEventListener("click",T)}),o.append(b),b}),f=()=>{if(i)return;s=ae(r.surface)??s;let m=r.getFormats();d.forEach((b,x)=>{let T=t[x];b.disabled=r.isReadOnly()||(T.enabled?!T.enabled(r):!1),T.format&&!["indent","clear"].includes(T.format)&&b.setAttribute("aria-pressed",m.mixed?.includes(T.format)?"mixed":String(m[T.format]===(T.value??!0)))}),(d[a]?.disabled||!d[a])&&(a=d.findIndex(b=>!b.disabled)),d.forEach((b,x)=>{b.tabIndex=x===a?0:-1})},u=m=>{let b=d.filter(M=>!M.disabled);if(!b.length)return;let x=b.indexOf(document.activeElement);if(x<0||m.ctrlKey||m.metaKey||m.altKey)return;if(m.key==="Escape"){m.preventDefault(),r.focus(),s&&$(r.surface,s);return}let T=getComputedStyle(o).direction==="rtl"?-1:1,N=m.key==="Home"?0:m.key==="End"?b.length-1:m.key==="ArrowRight"?(x+T+b.length)%b.length:m.key==="ArrowLeft"?(x-T+b.length)%b.length:-1;N>=0&&(m.preventDefault(),a=d.indexOf(b[N]),f(),b[N].focus())};o.addEventListener("keydown",u);let p=r.subscribe(m=>{m.source==="api"&&(s=void 0),f()}),g=r.onSelectionChange(f);return e.append(o),f(),()=>{if(!i){i=!0,p(),g(),o.removeEventListener("keydown",u);for(let m of c)m();o.remove()}}};export{Wt as createEditor,_t as createPluginEvent,Xt as createToolbar,He as sanitizeHTML};
|
|
2
2
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
|
-
"sources": ["../src/document/index.ts", "../src/selection/index.ts", "../src/lists/index.ts", "../src/formatting/inline-attributes.ts", "../src/formatting/links.ts", "../src/formatting/index.ts", "../src/events/index.ts", "../src/editor/create-editor.ts", "../src/ui/toolbar/index.ts"],
|
|
4
|
-
"sourcesContent": ["import type { DocumentTag, TextNode, ElementNode, DocumentNode, EditorDocument } from './types.js';\nexport type { DocumentTag, TextNode, ElementNode, DocumentNode, EditorDocument } from './types.js';\n/** Versioned, framework-independent document tree. Only supported HTML semantics are stored. */\nexport const documentTags = ['p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'blockquote', 'pre', 'code', 'strong', 'em', 'u', 's', 'sub', 'sup', 'a', 'span', 'br', 'hr', 'ul', 'ol', 'li', 'img', 'figure', 'figcaption', 'table', 'caption', 'colgroup', 'col', 'thead', 'tbody', 'tfoot', 'tr', 'td', 'th'] as const;\nconst tags = new Set<string>(documentTags);\nconst omitted = new Set(['script', 'style', 'iframe', 'object', 'embed', 'svg', 'math', 'template', 'form', 'input', 'button', 'textarea', 'select', 'noscript', 'link', 'meta', 'base']);\nconst aliases: Record<string, string> = { b: 'strong', i: 'em', strike: 's', div: 'p' };\nconst MAX_NODES = 100000;\nconst MAX_DEPTH = 100;\nconst safeURL = (value: string, image: boolean): string | undefined => {\n const trimmed = value.trim();\n if (!trimmed || /[\\u0000-\\u0020\\u007f]/.test(trimmed))\n return;\n // Explicit protocols and relative references only. Never data:, blob:, or script URLs.\n const protocol = /^([a-z][a-z\\d+.-]*):/i.exec(trimmed)?.[1].toLowerCase();\n if (protocol && !(image ? ['http', 'https'] : ['http', 'https', 'mailto', 'tel']).includes(protocol))\n return;\n if (trimmed.startsWith('\\\\') || trimmed.startsWith('//'))\n return;\n return trimmed;\n};\nconst safeStyle = (value: string): string => {\n const result: string[] = [];\n for (const declaration of value.split(';')) {\n const separator = declaration.indexOf(':');\n if (separator < 0)\n continue;\n const property = declaration.slice(0, separator).trim().toLowerCase();\n const content = declaration.slice(separator + 1).trim().toLowerCase();\n const color = /^(#[a-f\\d]{3,8}|[a-z]{1,24}|(?:rgb|rgba|hsl|hsla)\\([\\d\\s.,%+-]+\\))$/;\n const length = /^(?:\\d{1,4}(?:\\.\\d{1,3})?)(?:px|%|em|rem)$/;\n const valid = ['color', 'background-color', 'border-color'].includes(property) ? color.test(content)\n : ['width', 'height', 'font-size'].includes(property) ? length.test(content)\n : property === 'text-align' ? ['left', 'center', 'right', 'justify'].includes(content)\n : property === 'font-weight' ? /^(bold|normal|[1-9]00)$/.test(content)\n : property === 'font-style' ? ['italic', 'normal'].includes(content)\n : property === 'text-decoration' ? /^(underline|line-through|none)$/.test(content)\n : false;\n if (valid)\n result.push(`${property}: ${content}`);\n }\n return result.join('; ');\n};\nconst attributesFor = (tag: DocumentTag, input: Record<string, unknown>): Record<string, string> => {\n const output: Record<string, string> = {};\n for (const [key, value] of Object.entries(input)) {\n if (typeof value !== 'string' || value.length > 20000)\n continue;\n if (key === 'style') {\n const clean = safeStyle(value);\n if (clean)\n output.style = clean;\n }\n else if (key === 'title' || (tag === 'img' && key === 'alt'))\n output[key] = value;\n else if ((tag === 'a' && key === 'href') || (tag === 'img' && key === 'src')) {\n const clean = safeURL(value, tag === 'img');\n if (clean)\n output[key] = clean;\n }\n else if ((['td', 'th'].includes(tag) && ['rowspan', 'colspan'].includes(key)) || (['img', 'col', 'table'].includes(tag) && ['width', 'height', 'span'].includes(key))) {\n if (/^\\d{1,4}$/.test(value) && Number(value) > 0 && Number(value) <= 1000)\n output[key] = value;\n }\n else if (tag === 'a' && key === 'target' && ['_self', '_blank'].includes(value))\n output.target = value;\n else if (tag === 'a' && key === 'rel') {\n const tokens = [...new Set(value.toLowerCase().split(/\\s+/).filter((token) => ['noopener', 'noreferrer'].includes(token)))];\n if (tokens.length)\n output.rel = tokens.join(' ');\n }\n else if (tag === 'th' && key === 'scope' && ['row', 'col', 'rowgroup', 'colgroup'].includes(value))\n output[key] = value;\n }\n if (tag === 'img' && (output.width || output.height)) {\n const dimensions = ['width', 'height'].filter((key) => output[key]);\n const styles = (output.style ?? '').split(';').map((part) => part.trim()).filter((part) => part && !dimensions.includes(part.slice(0, part.indexOf(':')).trim()));\n output.style = [...styles, ...dimensions.map((key) => `${key}: ${output[key]}px`)].join('; ');\n }\n if (tag === 'a' && output.target === '_blank')\n output.rel = 'noopener noreferrer';\n return output;\n};\nconst readDOM = (node: Node, depth: number, budget: {\n count: number;\n}): DocumentNode[] => {\n if (++budget.count > MAX_NODES || depth > MAX_DEPTH)\n throw new RangeError('Document exceeds structural limits.');\n if (node.nodeType === 3)\n return [{ type: 'text', text: node.textContent ?? '' }];\n if (node.nodeType !== 1)\n return [];\n const element = node as Element;\n const original = element.localName.toLowerCase();\n if (element.namespaceURI !== 'http://www.w3.org/1999/xhtml' || omitted.has(original))\n return [];\n const children = [...element.childNodes].flatMap((child) => readDOM(child, depth + 1, budget));\n const tag = aliases[original] ?? original;\n if (!tags.has(tag))\n return children;\n const attributes = attributesFor(tag as DocumentTag, Object.fromEntries([...element.attributes].map((attr) => [attr.name, attr.value])));\n if (tag === 'img' && !attributes.src)\n return [];\n return [{ type: 'element', tag: tag as DocumentTag, attributes, children }];\n};\nexport const parseHTML = (html: string): EditorDocument => {\n if (html.length > 5000000)\n throw new RangeError('HTML exceeds the document size limit.');\n // A template is inert: script execution and active resource loading are never used for import.\n const template = document.createElement('template');\n template.innerHTML = html;\n const budget = { count: 0 };\n return { version: 1, children: [...template.content.childNodes].flatMap((node) => readDOM(node, 0, budget)) };\n};\nexport const validateDocument = (input: unknown): EditorDocument => {\n if (!input || typeof input !== 'object' || !('version' in input) || input.version !== 1 || !('children' in input) || !Array.isArray(input.children))\n throw new TypeError('Expected a version 1 document.');\n let count = 0;\n let textLength = 0;\n const visit = (value: unknown, depth: number): DocumentNode => {\n if (++count > MAX_NODES || depth > MAX_DEPTH)\n throw new RangeError('Document exceeds structural limits.');\n if (!value || typeof value !== 'object' || !('type' in value))\n throw new TypeError('Invalid document node.');\n if (value.type === 'text' && 'text' in value && typeof value.text === 'string') {\n textLength += value.text.length;\n if (textLength > 5000000)\n throw new RangeError('Document text exceeds size limit.');\n return { type: 'text', text: value.text };\n }\n if (value.type !== 'element' || !('tag' in value) || typeof value.tag !== 'string' || !tags.has(value.tag) || !('children' in value) || !Array.isArray(value.children))\n throw new TypeError('Invalid document element.');\n const attrs = 'attributes' in value && value.attributes && typeof value.attributes === 'object' && !Array.isArray(value.attributes) ? value.attributes : {};\n return { type: 'element', tag: value.tag as DocumentTag, attributes: attributesFor(value.tag as DocumentTag, attrs as Record<string, unknown>), children: value.children.map((child) => visit(child, depth + 1)) };\n };\n return { version: 1, children: input.children.map((child) => visit(child, 0)) };\n};\nexport const renderDocument = (value: EditorDocument): DocumentFragment => {\n const fragment = document.createDocumentFragment();\n const append = (parent: Node, node: DocumentNode) => {\n if (node.type === 'text') {\n parent.appendChild(document.createTextNode(node.text));\n return;\n }\n const element = document.createElement(node.tag);\n for (const [key, value] of Object.entries(node.attributes))\n element.setAttribute(key, value);\n for (const child of node.children)\n append(element, child);\n parent.appendChild(element);\n };\n for (const node of value.children)\n append(fragment, node);\n return fragment;\n};\nexport const documentHTML = (value: EditorDocument): string => {\n const container = document.createElement('div');\n container.append(renderDocument(value));\n return container.innerHTML;\n};\nexport const sanitizeHTML = (html: string): string => { return documentHTML(parseHTML(html)); };\n", "import type { TextSelection, SelectionBookmark } from './types.js';\nexport type { TextSelection, SelectionBookmark } from './types.js';\nexport const activeRange = (root: HTMLElement): Range | undefined => {\n const selection = root.ownerDocument.getSelection();\n if (!selection?.rangeCount)\n return;\n const range = selection.getRangeAt(0);\n if (!root.contains(range.startContainer) || !root.contains(range.endContainer))\n return;\n return range.cloneRange();\n};\nconst nodePath = (root: Node, target: Node): number[] => {\n const result: number[] = [];\n let node = target;\n while (node !== root && node.parentNode) {\n result.unshift([...node.parentNode.childNodes].indexOf(node as ChildNode));\n node = node.parentNode;\n }\n return result;\n};\nexport const bookmark = (root: HTMLElement): SelectionBookmark | undefined => {\n const range = activeRange(root);\n if (!range)\n return;\n const selection = root.ownerDocument.getSelection()!;\n return { start: nodePath(root, range.startContainer), startOffset: range.startOffset, end: nodePath(root, range.endContainer), endOffset: range.endOffset, backward: !range.collapsed && selection.anchorNode === range.endContainer && selection.anchorOffset === range.endOffset };\n};\nexport const restoreBookmark = (root: HTMLElement, saved: SelectionBookmark | undefined): void => {\n if (!saved)\n return;\n const resolve = (path: number[]) => path.reduce<Node>((node, index) => node.childNodes[index] ?? node, root);\n const start = resolve(saved.start);\n const end = resolve(saved.end);\n const limit = (node: Node, offset: number) => Math.min(offset, node.nodeType === 3 ? (node.textContent?.length ?? 0) : node.childNodes.length);\n const selection = root.ownerDocument.getSelection();\n if (!selection)\n return;\n const startOffset = limit(start, saved.startOffset);\n const endOffset = limit(end, saved.endOffset);\n if (saved.backward)\n selection.setBaseAndExtent(end, endOffset, start, startOffset);\n else\n selection.setBaseAndExtent(start, startOffset, end, endOffset);\n};\nexport const readTextSelection = (root: HTMLElement): TextSelection | undefined => {\n const range = activeRange(root);\n if (!range)\n return;\n const prefix = root.ownerDocument.createRange();\n prefix.selectNodeContents(root);\n prefix.setEnd(range.startContainer, range.startOffset);\n return { index: prefix.toString().length, length: range.toString().length };\n};\nexport const selectText = (root: HTMLElement, index: number, length = 0): void => {\n if (![index, length].every((value) => Number.isInteger(value) && value >= 0))\n throw new RangeError('Selection offsets must be non-negative integers.');\n const walker = root.ownerDocument.createTreeWalker(root, 4);\n const nodes: Text[] = [];\n let current: Node | null;\n while ((current = walker.nextNode()))\n nodes.push(current as Text);\n const locate = (offset: number): [\n Node,\n number\n ] => {\n for (const node of nodes) {\n if (offset <= node.length)\n return [node, offset];\n offset -= node.length;\n }\n const last = nodes.at(-1);\n return last ? [last, last.length] : [root.querySelector('p,h1,h2,h3,h4,h5,h6,li,blockquote,pre') ?? root, 0];\n };\n const [start, startOffset] = locate(index);\n const [end, endOffset] = locate(index + length);\n const range = root.ownerDocument.createRange();\n range.setStart(start, startOffset);\n range.setEnd(end, endOffset);\n root.focus({ preventScroll: true });\n const selection = root.ownerDocument.getSelection();\n selection?.removeAllRanges();\n selection?.addRange(range);\n};\nexport const placeCaret = (element: HTMLElement, end = false): void => {\n const range = element.ownerDocument.createRange();\n range.selectNodeContents(element);\n range.collapse(!end);\n const selection = element.ownerDocument.getSelection();\n selection?.removeAllRanges();\n selection?.addRange(range);\n};\n/** Keep actual DOM positions while moving blocks, including empty list items. */\nexport const preserveRange = (root: HTMLElement, mutate: () => void): void => {\n const range = activeRange(root);\n if (!range)\n return;\n const native = root.ownerDocument.getSelection()!;\n const backward = !range.collapsed && native.anchorNode === range.endContainer && native.anchorOffset === range.endOffset;\n const start = root.ownerDocument.createComment('mw-start');\n const end = range.collapsed ? undefined : root.ownerDocument.createComment('mw-end');\n if (end) {\n const tail = range.cloneRange();\n tail.collapse(false);\n tail.insertNode(end);\n }\n const head = range.cloneRange();\n head.collapse(true);\n head.insertNode(start);\n try {\n mutate();\n if (root.contains(start) && (!end || root.contains(end))) {\n const next = root.ownerDocument.createRange();\n next.setStartBefore(start);\n if (end)\n next.setEndBefore(end);\n else\n next.collapse(true);\n start.remove();\n end?.remove();\n root.normalize();\n if (backward)\n native.setBaseAndExtent(next.endContainer, next.endOffset, next.startContainer, next.startOffset);\n else {\n native.removeAllRanges();\n native.addRange(next);\n }\n }\n }\n finally {\n start.remove();\n end?.remove();\n }\n};\n", "import { activeRange, placeCaret, preserveRange } from '../selection/index.js';\nconst blocks = 'p,h1,h2,h3,h4,h5,h6,blockquote,pre,li';\nconst isList = (element: Element | null): element is HTMLUListElement | HTMLOListElement => !!element && /^(ul|ol)$/.test(element.localName);\nconst elementAt = (node: Node): Element | null => node instanceof Element ? node : node.parentElement;\nconst blockAt = (root: HTMLElement, node: Node, preferItem = true): HTMLElement | undefined => {\n const element = elementAt(node);\n const item = element?.closest<HTMLElement>('li');\n const block = (preferItem && item && root.contains(item) ? item : undefined) ?? element?.closest<HTMLElement>(blocks);\n return block && root.contains(block) ? block : undefined;\n};\nconst touches = (range: Range, node: Node): boolean => {\n const content = node.ownerDocument!.createRange();\n if (node.nodeType === 3)\n content.selectNodeContents(node);\n else\n content.selectNode(node);\n const start = range.cloneRange();\n start.collapse(true);\n const end = range.cloneRange();\n end.collapse(false);\n const first = content.cloneRange();\n first.collapse(true);\n const last = content.cloneRange();\n last.collapse(false);\n return start.compareBoundaryPoints(Range.START_TO_START, last) < 0 && end.compareBoundaryPoints(Range.START_TO_START, first) > 0;\n};\nexport const selectedBlocks = (root: HTMLElement, range = activeRange(root), preferItems = true): HTMLElement[] => {\n if (!range)\n return [];\n if (range.collapsed) {\n const block = blockAt(root, range.startContainer, preferItems);\n return block ? [block] : [];\n }\n const found = new Set<HTMLElement>();\n const walker = root.ownerDocument.createTreeWalker(root, NodeFilter.SHOW_TEXT | NodeFilter.SHOW_ELEMENT);\n let node: Node | null;\n while ((node = walker.nextNode())) {\n if (!(node.nodeType === 3 && node.textContent) && !(node instanceof Element && /^(br|img|hr)$/.test(node.localName)))\n continue;\n if (touches(range, node)) {\n const block = blockAt(root, node, preferItems);\n if (block)\n found.add(block);\n }\n }\n return [...root.querySelectorAll<HTMLElement>(blocks)].filter((block) => found.has(block));\n};\nconst topItems = (items: HTMLElement[]) => items.filter((item) => !items.some((parent) => parent !== item && parent.contains(item)));\nconst itemRange = (root: HTMLElement): HTMLLIElement[] => {\n const items = topItems(selectedBlocks(root));\n if (!items.length || items.some((item) => item.localName !== 'li' || !isList(item.parentElement)))\n return [];\n const parent = items[0].parentElement;\n if (items.some((item) => item.parentElement !== parent))\n return [];\n const siblings = [...parent!.children];\n if (siblings.indexOf(items.at(-1)!) - siblings.indexOf(items[0]) + 1 !== items.length)\n return [];\n return items as HTMLLIElement[];\n};\nconst depth = (root: HTMLElement, item: HTMLElement): number => {\n let result = 0; let parent: Element | null = item.parentElement; while (parent && parent !== root) {\n if (isList(parent))\n result++;\n parent = parent.parentElement;\n } return result;\n};\nconst compatible = (a: Element | null, b: Element): a is HTMLElement => !!a && a.localName === b.localName && isList(a) && a.getAttribute('style') === b.getAttribute('style');\nconst joinLists = (root: HTMLElement): void => {\n for (const list of [...root.querySelectorAll<HTMLElement>('ul,ol')]) {\n if (!root.contains(list))\n continue;\n const previous = list.previousSibling;\n if (previous instanceof Element && compatible(previous, list)) {\n previous.append(...list.childNodes);\n list.remove();\n }\n }\n};\nconst splitAround = (item: HTMLLIElement, replacement: Node[]): void => {\n const list = item.parentElement!;\n const tail = list.cloneNode(false) as HTMLElement;\n while (item.nextSibling)\n tail.append(item.nextSibling);\n item.remove();\n list.after(...replacement, ...(tail.childNodes.length ? [tail] : []));\n if (!list.childNodes.length)\n list.remove();\n};\nconst ownContent = (item: HTMLElement) => [...item.childNodes].filter((node) => !(node instanceof Element && isList(node)));\nconst unwrapRoot = (item: HTMLLIElement, paragraphOnly = false): void => {\n const paragraphNode = () => {\n const node = document.createElement('p'); if (item.hasAttribute('style'))\n node.setAttribute('style', item.getAttribute('style')!); return node;\n };\n let paragraph = paragraphNode();\n const nested = [...item.children].filter(isList);\n const content = ownContent(item);\n // Imported items may contain paragraphs; retain their block structure rather than nest p in p.\n const output: Node[] = [];\n for (const node of content) {\n if (paragraphOnly && node instanceof HTMLElement && /^(p|h[1-6]|blockquote|pre)$/.test(node.localName)) {\n paragraph.append(...node.childNodes);\n }\n else if (node instanceof HTMLElement && /^(p|h[1-6]|blockquote|pre)$/.test(node.localName)) {\n if (paragraph.childNodes.length)\n output.push(paragraph);\n paragraph = paragraphNode();\n output.push(node);\n }\n else\n paragraph.append(node);\n }\n if (paragraph.childNodes.length || !output.length) {\n if (!paragraph.childNodes.length)\n paragraph.append(document.createElement('br'));\n output.push(paragraph);\n }\n splitAround(item, [...output, ...nested]);\n};\nconst lift = (items: HTMLLIElement[]): void => {\n const list = items[0].parentElement!;\n const owner = list.parentElement;\n if (owner?.localName !== 'li' || !isList(owner.parentElement)) {\n for (const item of items)\n unwrapRoot(item);\n return;\n }\n const trailing = list.cloneNode(false) as HTMLElement;\n while (items.at(-1)!.nextSibling)\n trailing.append(items.at(-1)!.nextSibling!);\n if (trailing.childNodes.length)\n items.at(-1)!.append(trailing);\n owner.after(...items);\n if (!list.childNodes.length)\n list.remove();\n};\nexport const listState = (root: HTMLElement) => {\n const items = itemRange(root);\n const canIndent = !!items.length && items[0].previousElementSibling?.localName === 'li' && items.every((item) => [item, ...item.querySelectorAll<HTMLElement>('li')].every((child) => depth(root, child) < 8));\n return { listDepth: items.length ? depth(root, items[0]) : 0, canIndent, canOutdent: !!items.length };\n};\nexport const indentList = (root: HTMLElement, direction: unknown): void => {\n if (direction !== 1 && direction !== -1)\n throw new TypeError('List indentation requires 1 or -1.');\n const items = itemRange(root);\n if (!items.length)\n throw new RangeError('Select consecutive items in the same list.');\n if (direction === 1 && !listState(root).canIndent)\n return;\n preserveRange(root, () => {\n if (direction === -1)\n lift(items);\n else {\n const list = items[0].parentElement!;\n const previous = items[0].previousElementSibling!;\n let nested = previous.lastElementChild;\n if (!compatible(nested, list)) {\n nested = list.cloneNode(false) as HTMLElement;\n previous.append(nested);\n }\n nested!.append(...items);\n }\n joinLists(root);\n });\n};\nexport const applyList = (root: HTMLElement, value: unknown): void => {\n if (value !== false && value !== 'bullet' && value !== 'ordered')\n throw new TypeError('Expected bullet, ordered or false.');\n const selected = topItems(selectedBlocks(root));\n if (selected.some((block) => block.localName === 'li' && !isList(block.parentElement)))\n throw new RangeError('A list item must belong to a list.');\n preserveRange(root, () => {\n for (const block of selected) {\n if (!value) {\n if (block.localName === 'li')\n lift([block as HTMLLIElement]);\n continue;\n }\n const tag = value === 'bullet' ? 'ul' : 'ol';\n if (block.localName === 'li') {\n if (block.parentElement!.localName === tag)\n continue;\n const list = document.createElement(tag);\n if (block.parentElement!.hasAttribute('style'))\n list.setAttribute('style', block.parentElement!.getAttribute('style')!);\n splitAround(block as HTMLLIElement, [list]);\n list.append(block);\n }\n else {\n const list = document.createElement(tag);\n const item = document.createElement('li');\n if (block.hasAttribute('style'))\n item.setAttribute('style', block.getAttribute('style')!);\n item.append(...block.childNodes);\n list.append(item);\n block.replaceWith(list);\n }\n }\n joinLists(root);\n });\n};\nconst empty = (item: HTMLElement) => !item.textContent?.trim() && !item.querySelector('img,hr,ul,ol');\nconst placeholder = (item: HTMLElement): void => {\n const own = ownContent(item);\n const meaningful = own.some((node) => node.textContent || (node instanceof Element && (node.matches('br,img,hr') || node.querySelector('br,img,hr'))));\n if (!meaningful) {\n if ([...item.children].some(isList))\n item.prepend(Object.assign(document.createElement('p'), { innerHTML: '<br>' }));\n else\n item.append(document.createElement('br'));\n }\n};\nconst atStart = (item: HTMLElement, range: Range) => {\n const prefix = range.cloneRange();\n prefix.selectNodeContents(item);\n prefix.setEnd(range.startContainer, range.startOffset);\n return !prefix.toString() && !prefix.cloneContents().querySelector('img,hr,br');\n};\nexport const handlesListInput = (root: HTMLElement, inputType: string): boolean => {\n const range = activeRange(root);\n if (!range)\n return false;\n const item = blockAt(root, range.startContainer);\n if (item?.localName !== 'li' || !isList(item.parentElement) || blockAt(root, range.endContainer) !== item)\n return false;\n return ['insertParagraph', 'insertLineBreak'].includes(inputType) || (inputType === 'deleteContentBackward' && range.collapsed && atStart(item, range));\n};\nexport const editListInput = (root: HTMLElement, inputType: string): void => {\n const range = activeRange(root)!;\n const item = blockAt(root, range.startContainer) as HTMLLIElement;\n if (inputType === 'insertParagraph') {\n if (empty(item)) {\n preserveRange(root, () => {\n const owner = item.parentElement!.parentElement; if (owner?.localName === 'li' && isList(owner.parentElement))\n lift([item]);\n else\n unwrapRoot(item, true);\n });\n joinLists(root);\n return;\n }\n range.deleteContents();\n const tail = range.cloneRange();\n tail.selectNodeContents(item);\n tail.setStart(range.startContainer, range.startOffset);\n const next = item.cloneNode(false) as HTMLLIElement;\n next.append(tail.extractContents());\n item.after(next);\n placeholder(item);\n placeholder(next);\n const walker = document.createTreeWalker(next, NodeFilter.SHOW_TEXT);\n let first: Node | null;\n do {\n first = walker.nextNode();\n } while (first && (!first.textContent || first.parentElement?.closest('li') !== next));\n if (first) {\n const caret = document.createRange();\n caret.setStart(first, 0);\n caret.collapse(true);\n const selection = document.getSelection();\n selection?.removeAllRanges();\n selection?.addRange(caret);\n }\n else\n placeCaret(next.querySelector<HTMLElement>('p,h1,h2,h3,h4,h5,h6,pre') ?? next);\n }\n else if (inputType === 'insertLineBreak') {\n range.deleteContents();\n const br = document.createElement('br');\n range.insertNode(br);\n if (!br.nextSibling)\n br.after(document.createElement('br'));\n range.setStartAfter(br);\n range.collapse(true);\n const selection = document.getSelection();\n selection?.removeAllRanges();\n selection?.addRange(range);\n }\n else {\n const previous = item.previousElementSibling as HTMLLIElement | null;\n if (previous && previous.localName !== 'li')\n return;\n if (!previous) {\n preserveRange(root, () => lift([item]));\n joinLists(root);\n return;\n }\n if (!ownContent(previous).some((node) => node.textContent || (node instanceof Element && (node.localName === 'img' || node.querySelector('img'))))) {\n for (const br of [...previous.querySelectorAll('br')])\n if (br.closest('li') === previous)\n br.remove();\n }\n const marker = document.createComment('mw-join');\n const previousContent = ownContent(previous);\n const last = previousContent.at(-1);\n const target = last instanceof HTMLElement && /^(p|h[1-6]|blockquote|pre)$/.test(last.localName) ? last : previous;\n if (target === previous)\n previous.insertBefore(marker, [...previous.children].find(isList) ?? null);\n else\n target.append(marker);\n const content = ownContent(item);\n if (content[0] instanceof HTMLElement && /^(p|h[1-6])$/.test(content[0].localName))\n content.splice(0, 1, ...content[0].childNodes);\n marker.after(...content);\n for (const nested of [...item.children].filter(isList))\n previous.append(nested);\n item.remove();\n joinLists(root);\n const caret = document.createRange();\n caret.setStartBefore(marker);\n caret.collapse(true);\n marker.remove();\n const selection = document.getSelection();\n selection?.removeAllRanges();\n selection?.addRange(caret);\n }\n};\n", "import type { LinkFormat, Attributes, Operation, Piece } from './inline-attributes.types.js';\nexport type { LinkFormat } from './inline-attributes.types.js';\nimport { validateDocument } from '../document/index.js';\nimport type { DocumentNode, EditorDocument, ElementNode } from '../document/index.js';\nexport const inlineStyles: Record<string, string> = { color: 'color', background: 'background-color' };\nconst blocks = new Set(['p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'blockquote', 'pre', 'ul', 'ol', 'li', 'table', 'thead', 'tbody', 'tfoot', 'tr', 'td', 'th', 'caption', 'colgroup', 'figure', 'figcaption']);\nconst checkedAttributes = (tag: 'span' | 'a', attributes: Attributes): Attributes => (validateDocument({ version: 1, children: [{ type: 'element', tag, attributes, children: [] }] }).children[0] as ElementNode).attributes;\nexport const normalizeInlineStyle = (name: string, value: unknown): string | false => {\n if (value === false)\n return false;\n if (typeof value !== 'string' || !value.trim() || value.length > 128 || /[;{}]/.test(value))\n throw new TypeError('Expected a CSS color or false.');\n const property = inlineStyles[name];\n const attrs = checkedAttributes('span', { style: `${property}: ${value}` });\n const probe = document.createElement('span');\n probe.setAttribute('style', attrs.style ?? '');\n const color = probe.style.getPropertyValue(property);\n if (!color)\n throw new TypeError('Unsupported or invalid CSS color.');\n return color;\n};\nexport const normalizeLink = (value: unknown): {\n attributes: Attributes;\n text?: string;\n} | false => {\n if (value === false)\n return false;\n const input = typeof value === 'string' ? { href: value } : value;\n if (!input || typeof input !== 'object' || Array.isArray(input) || !('href' in input) || typeof input.href !== 'string')\n throw new TypeError('Expected a link URL, LinkFormat or false.');\n const link = input as Record<string, unknown>;\n const attributes: Attributes = { href: input.href };\n if (link.title !== undefined) {\n if (typeof link.title !== 'string' || link.title.length > 1024)\n throw new TypeError('Link title must be a string up to 1024 characters.');\n attributes.title = link.title;\n }\n if (link.target !== undefined) {\n if (link.target !== '_self' && link.target !== '_blank')\n throw new TypeError('Link target must be _self or _blank.');\n attributes.target = link.target;\n }\n if (link.text !== undefined && (typeof link.text !== 'string' || !link.text.length || link.text.length > 20000))\n throw new TypeError('New link text must contain 1\u201320000 characters.');\n const clean = checkedAttributes('a', attributes);\n if (!clean.href)\n throw new TypeError('Unsupported or unsafe link URL.');\n return { attributes: clean, ...(typeof link.text === 'string' ? { text: link.text } : {}) };\n};\nexport const mergeLinkAttributes = (previous: Attributes, patch: Attributes): Attributes => {\n const attrs = { ...previous, ...patch };\n if (!attrs.title)\n delete attrs.title;\n if (patch.target === '_self')\n delete attrs.rel;\n return checkedAttributes('a', attrs);\n};\nconst equalAttributes = (a?: Attributes, b?: Attributes) => JSON.stringify(Object.entries(a ?? {}).sort()) === JSON.stringify(Object.entries(b ?? {}).sort());\nconst withoutProperty = (attributes: Attributes, property: string): Attributes => {\n const attrs = { ...attributes };\n const style = (attrs.style ?? '').split(';').map((part) => part.trim()).filter((part) => part && part.slice(0, part.indexOf(':')).trim() !== property).join('; ');\n if (style)\n attrs.style = style;\n else\n delete attrs.style;\n return attrs;\n};\nconst groupPieces = (pieces: Piece[]): {\n pieces: Piece[];\n selected: boolean;\n link?: Attributes;\n}[] => {\n const result: {\n pieces: Piece[];\n selected: boolean;\n link?: Attributes;\n }[] = [];\n for (const piece of pieces) {\n const last = result.at(-1);\n if (last && last.selected === piece.selected && equalAttributes(last.link, piece.link))\n last.pieces.push(piece);\n else\n result.push({ pieces: [piece], selected: piece.selected, link: piece.link });\n }\n return result;\n};\nconst compact = (nodes: DocumentNode[]): DocumentNode[] => {\n const result: DocumentNode[] = [];\n for (const node of nodes) {\n const next = node.type === 'element' ? { ...node, children: compact(node.children) } : node;\n const previous = result.at(-1);\n if (next.type === 'text' && previous?.type === 'text')\n previous.text += next.text;\n else if (next.type === 'element' && previous?.type === 'element' && !blocks.has(next.tag) && !['img', 'br', 'hr'].includes(next.tag) && previous.tag === next.tag && equalAttributes(previous.attributes, next.attributes))\n previous.children = compact([...previous.children, ...next.children]);\n else\n result.push(next);\n }\n return result;\n};\nexport const transformInlineAttributes = (document: EditorDocument, from: number, to: number, operation: Operation): EditorDocument => {\n let position = 0;\n const wrap = (pieces: Piece[]): DocumentNode[] => groupPieces(pieces).flatMap((group) => {\n const children = group.pieces.map((piece) => piece.node);\n if (operation.kind === 'style')\n return group.selected && operation.value !== false ? [{ type: 'element', tag: 'span', attributes: { style: `${operation.property}: ${operation.value}` }, children } as ElementNode] : children;\n const attrs = group.selected ? operation.attributes === false ? undefined : mergeLinkAttributes(group.link ?? {}, operation.attributes) : group.link;\n return attrs ? [{ type: 'element', tag: 'a', attributes: attrs, children } as ElementNode] : children;\n });\n const visit = (node: DocumentNode, inheritedLink?: Attributes): Piece[] => {\n if (node.type === 'text') {\n const start = position;\n position += node.text.length;\n const left = Math.max(0, Math.min(node.text.length, from - start));\n const right = Math.max(left, Math.min(node.text.length, to - start));\n return [[0, left, false], [left, right, true], [right, node.text.length, false]].flatMap(([begin, end, selected]) => {\n const text = node.text.slice(begin as number, end as number);\n return text ? [{ node: { type: 'text', text } as DocumentNode, selected: Boolean(selected), link: inheritedLink }] : [];\n });\n }\n const link = operation.kind === 'link' && node.tag === 'a' ? node.attributes : inheritedLink;\n if (!node.children.length)\n return [{ node, selected: position >= from && position < to, link }];\n const children = node.children.flatMap((child) => visit(child, link));\n if (operation.kind === 'link' && node.tag === 'a')\n return children;\n if (blocks.has(node.tag))\n return [{ node: { ...node, children: wrap(children) }, selected: false }];\n return groupPieces(children).flatMap<Piece>((group) => {\n const attrs = operation.kind === 'style' && group.selected ? withoutProperty(node.attributes, operation.property) : node.attributes;\n const content = group.pieces.map((piece) => piece.node);\n if (node.tag === 'span' && !Object.keys(attrs).length)\n return group.pieces;\n return [{ node: { ...node, attributes: attrs, children: content }, selected: group.selected, link: group.link }];\n });\n };\n return { version: 1, children: compact(wrap(document.children.flatMap((node) => visit(node)))) };\n};\n", "import { documentHTML, parseHTML } from '../document/index.js';\nimport { normalizeLink, mergeLinkAttributes, transformInlineAttributes } from './inline-attributes.js';\nimport { activeRange, readTextSelection, selectText, preserveRange } from '../selection/index.js';\nexport const applyLink = (root: HTMLElement, value: unknown): void => {\n const link = normalizeLink(value);\n const range = activeRange(root);\n if (!range)\n return;\n const selection = readTextSelection(root)!;\n const element = range.startContainer.nodeType === 1 ? range.startContainer as Element : range.startContainer.parentElement;\n const anchor = element?.closest('a');\n const existing = anchor && root.contains(anchor) ? anchor : undefined;\n if (link && link.text !== undefined && (!range.collapsed || existing))\n throw new TypeError('Link text is only supported for insertion at a caret outside links.');\n if (!range.collapsed) {\n root.innerHTML = documentHTML(transformInlineAttributes(parseHTML(root.innerHTML), selection.index, selection.index + selection.length, { kind: 'link', attributes: link && link.attributes }));\n selectText(root, selection.index, selection.length);\n return;\n }\n if (existing) {\n const attrs = link && mergeLinkAttributes(Object.fromEntries([...existing.attributes].map((attr) => [attr.name, attr.value])), link.attributes);\n preserveRange(root, () => {\n if (!attrs)\n existing.replaceWith(...existing.childNodes);\n else {\n for (const attr of [...existing.attributes])\n existing.removeAttribute(attr.name);\n for (const [key, val] of Object.entries(attrs))\n existing.setAttribute(key, val);\n }\n });\n return;\n }\n if (!link || link.text === undefined)\n return;\n const created = root.ownerDocument.createElement('a');\n for (const [key, val] of Object.entries(link.attributes))\n created.setAttribute(key, val);\n created.textContent = link.text;\n const parent = element?.closest('p,li,h1,h2,h3,h4,h5,h6,blockquote,pre,td,th');\n if (parent?.childNodes.length === 1 && parent.firstChild instanceof HTMLBRElement) {\n parent.firstChild.remove();\n range.setStart(parent, 0);\n }\n range.insertNode(created);\n const tail = root.ownerDocument.createTextNode('');\n created.after(tail);\n range.setStart(tail, 0);\n range.collapse(true);\n const native = root.ownerDocument.getSelection();\n native?.removeAllRanges();\n native?.addRange(range);\n};\n", "import type { Piece } from './types.js';\nimport type { DocumentNode, DocumentTag, EditorDocument, ElementNode } from '../document/index.js';\nimport { documentHTML, parseHTML } from '../document/index.js';\nimport { activeRange, readTextSelection, selectText, preserveRange } from '../selection/index.js';\nimport { inlineStyles, normalizeInlineStyle, transformInlineAttributes } from './inline-attributes.js';\nimport { applyLink } from './links.js';\nimport { applyList, indentList, listState, selectedBlocks } from '../lists/index.js';\nexport const inlineFormats: Record<string, DocumentTag> = { bold: 'strong', italic: 'em', underline: 'u', strike: 's', code: 'code', subscript: 'sub', superscript: 'sup' };\nconst blockTags = new Set(['p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'blockquote', 'pre', 'ul', 'ol', 'li', 'table', 'thead', 'tbody', 'tfoot', 'tr', 'td', 'th', 'caption', 'colgroup', 'figure', 'figcaption']);\nconst inlineDocument = (value: EditorDocument, from: number, to: number, tag: DocumentTag, enabled: boolean): EditorDocument => {\n let position = 0;\n const visit = (node: DocumentNode, inherited: boolean): Piece[] => {\n if (node.type === 'text') {\n const start = position;\n position += node.text.length;\n const left = Math.max(0, Math.min(node.text.length, from - start));\n const right = Math.max(left, Math.min(node.text.length, to - start));\n return [[0, left, false], [left, right, true], [right, node.text.length, false]].flatMap(([begin, end, selected]) => {\n const text = node.text.slice(begin as number, end as number);\n if (!text)\n return [];\n const leaf: DocumentNode = { type: 'text', text };\n return [{ node: selected && enabled && !inherited ? { type: 'element', tag, attributes: {}, children: [leaf] } as ElementNode : leaf, selected: Boolean(selected) }];\n });\n }\n const children = node.children.flatMap((child) => visit(child, inherited || (enabled && node.tag === tag)));\n if (blockTags.has(node.tag))\n return [{ node: { ...node, children: children.map((piece) => piece.node) }, selected: false }];\n if (!children.length)\n return [{ node, selected: false }];\n const groups: {\n selected: boolean;\n children: DocumentNode[];\n }[] = [];\n for (const piece of children) {\n const last = groups.at(-1);\n if (last?.selected === piece.selected)\n last.children.push(piece.node);\n else\n groups.push({ selected: piece.selected, children: [piece.node] });\n }\n return groups.flatMap<Piece>((group) => node.tag === tag && !enabled && group.selected\n ? group.children.map((child) => ({ node: child, selected: true }))\n : [{ node: { ...node, children: group.children }, selected: group.selected }]);\n };\n return { version: 1, children: value.children.flatMap((node) => visit(node, false)).map((piece) => piece.node) };\n};\nconst closestElement = (node: Node): Element | null => { return node.nodeType === 1 ? node as Element : node.parentElement; };\nconst formatsAt = (root: HTMLElement, node: Node): Record<string, unknown> => {\n let element = closestElement(node);\n const formats: Record<string, unknown> = {};\n while (element && element !== root) {\n for (const [name, tag] of Object.entries(inlineFormats))\n if (element.localName === tag)\n formats[name] = true;\n if (/^h[1-6]$/.test(element.localName) && formats.header === undefined)\n formats.header = Number(element.localName[1]);\n if (element.localName === 'blockquote')\n formats.blockquote = true;\n if (element.localName === 'pre')\n formats['code-block'] = true;\n if ((element.localName === 'ul' || element.localName === 'ol') && formats.list === undefined)\n formats.list = element.localName === 'ul' ? 'bullet' : 'ordered';\n if (element.localName === 'a' && formats.link === undefined) {\n formats.link = element.getAttribute('href');\n formats.linkTitle = element.getAttribute('title') ?? '';\n formats.linkTarget = element.getAttribute('target') ?? '_self';\n }\n if (element instanceof HTMLElement)\n for (const [name, property] of Object.entries(inlineStyles))\n if (formats[name] === undefined && element.style.getPropertyValue(property))\n formats[name] = element.style.getPropertyValue(property);\n if (element instanceof HTMLElement && element.style.textAlign && formats.align === undefined)\n formats.align = element.style.textAlign;\n element = element.parentElement;\n }\n return formats;\n};\nexport const readFormats = (root: HTMLElement): Record<string, unknown> => {\n const range = activeRange(root);\n if (!range)\n return {};\n let formats = formatsAt(root, range.startContainer);\n const mixed = new Set<string>();\n if (!range.collapsed) {\n const { index, length } = readTextSelection(root)!;\n const walker = root.ownerDocument.createTreeWalker(root, NodeFilter.SHOW_TEXT);\n let position = 0;\n let node: Node | null;\n const samples: Record<string, unknown>[] = [];\n while ((node = walker.nextNode())) {\n const end = position + node.textContent!.length;\n if (end > index && position < index + length)\n samples.push(formatsAt(root, node));\n position = end;\n }\n if (samples.length)\n formats = samples[0];\n const keys = [...Object.keys(inlineFormats), 'header', 'list', 'blockquote', 'code-block', 'link', 'linkTitle', 'linkTarget', 'color', 'background', 'align'];\n const normalized = (sample: Record<string, unknown>, key: string) => sample[key] ?? (key === 'align' ? 'left' : key === 'header' ? 0 : false);\n for (const key of keys)\n if (samples.some((sample) => normalized(sample, key) !== normalized(samples[0], key)))\n mixed.add(key);\n }\n return { ...formats, align: formats.align ?? 'left', mixed: [...mixed], ...listState(root) };\n};\nexport const applyFormat = (root: HTMLElement, name: string, value: unknown): void => {\n const range = activeRange(root);\n if (!range)\n return;\n const selection = readTextSelection(root)!;\n if (name === 'list') {\n applyList(root, value);\n return;\n }\n if (name === 'indent') {\n indentList(root, value);\n return;\n }\n if (name === 'clear') {\n if (value !== true || !selection.length)\n return;\n let content = parseHTML(root.innerHTML);\n for (const tag of [...Object.values(inlineFormats), 'a', 'span'] as DocumentTag[])\n content = inlineDocument(content, selection.index, selection.index + selection.length, tag, false);\n root.innerHTML = documentHTML(content);\n selectText(root, selection.index, selection.length);\n return;\n }\n const tag = inlineFormats[name];\n if (tag) {\n if (range.collapsed)\n return;\n root.innerHTML = documentHTML(inlineDocument(parseHTML(root.innerHTML), selection.index, selection.index + selection.length, tag, Boolean(value)));\n selectText(root, selection.index, selection.length);\n return;\n }\n if (name === 'link') {\n applyLink(root, value);\n return;\n }\n if (Object.hasOwn(inlineStyles, name)) {\n const color = normalizeInlineStyle(name, value);\n if (!selection.length)\n return;\n root.innerHTML = documentHTML(transformInlineAttributes(parseHTML(root.innerHTML), selection.index, selection.index + selection.length, { kind: 'style', property: inlineStyles[name], value: color }));\n selectText(root, selection.index, selection.length);\n return;\n }\n let blocks = selectedBlocks(root, range, false);\n if (!blocks.length) {\n const paragraph = document.createElement('p');\n paragraph.append(range.extractContents());\n if (!paragraph.childNodes.length)\n paragraph.append(document.createElement('br'));\n range.insertNode(paragraph);\n blocks = [paragraph];\n }\n preserveRange(root, () => {\n for (const block of blocks) {\n if (name === 'align' && ['left', 'center', 'right', 'justify', false].includes(value as string | false)) {\n block.style.textAlign = value ? String(value) : '';\n continue;\n }\n const nextTag = name === 'header' ? (Number.isInteger(value) && Number(value) >= 1 && Number(value) <= 6 ? `h${value}` : 'p')\n : name === 'blockquote' ? (value ? 'blockquote' : 'p')\n : name === 'code-block' ? (value ? 'pre' : 'p') : undefined;\n if (nextTag) {\n const replacement = document.createElement(nextTag);\n if (block.localName === 'li') {\n const content = [...block.childNodes].filter((node) => !(node instanceof Element && /^(ul|ol|p|h[1-6]|pre|blockquote)$/.test(node.localName)));\n replacement.append(...content);\n block.prepend(replacement);\n }\n else {\n replacement.append(...block.childNodes);\n replacement.setAttribute('style', block.getAttribute('style') ?? '');\n block.replaceWith(replacement);\n }\n }\n }\n });\n};\n", "import type { EditorEventMap, EditorEvents, EventHub, PluginEvent, QueuedEvent } from './types.js';\nexport type { EditorEventMap, EditorEvents, PluginEvent } from './types.js';\nconst tokens = new WeakSet<object>();\nconst coreNames = new Set(['change', 'selectionchange', 'readonlychange', 'destroy']);\nexport const createPluginEvent = <T>(name: string): PluginEvent<T> => {\n if (typeof name !== 'string' || !name.trim() || name.length > 200) {\n throw new TypeError('Expected an event name with 1\u2013200 characters.');\n }\n const token = Object.freeze({ name }) as PluginEvent<T>;\n tokens.add(token);\n return token;\n};\nconst assertToken = (event: unknown): object => {\n if (!event || typeof event !== 'object' || !tokens.has(event)) {\n throw new TypeError('Expected a plugin event token. Core events cannot be emitted publicly.');\n }\n return event;\n};\nexport const createEventHub = (): EventHub => {\n const listeners = new Map<string | object, Map<(payload: unknown) => void, number>>();\n const queue: QueuedEvent[] = [];\n let registration = 0;\n let dispatching = false;\n let closing = false;\n const enqueue = (entry: QueuedEvent) => {\n if (closing && entry.key !== 'destroy')\n return;\n queue.push(entry);\n if (dispatching)\n return;\n dispatching = true;\n const failures: unknown[] = [];\n try {\n while (queue.length) {\n const next = queue.shift()!;\n if (closing && next.key !== 'destroy')\n continue;\n const bucket = listeners.get(next.key);\n for (const [listener, registered] of [...(bucket ?? [])]) {\n if ((closing && next.key !== 'destroy') || bucket?.get(listener) !== registered)\n continue;\n try {\n const payload = next.core && next.payload && typeof next.payload === 'object'\n ? { ...next.payload }\n : next.payload;\n listener(payload);\n }\n catch (error) {\n failures.push(error);\n }\n }\n if (next.key === 'destroy') {\n listeners.clear();\n queue.length = 0;\n }\n }\n }\n finally {\n dispatching = false;\n }\n if (failures.length)\n throw new AggregateError(failures, 'Editor event listeners failed.');\n };\n const on = (event: keyof EditorEventMap | PluginEvent<unknown>, listener: (payload: unknown) => void): (() => void) => {\n if (closing)\n throw new Error('Editor events have been destroyed.');\n if (typeof listener !== 'function')\n throw new TypeError('Expected an event listener.');\n const key = typeof event === 'string' && coreNames.has(event) ? event : assertToken(event);\n let bucket = listeners.get(key);\n if (!bucket) {\n bucket = new Map();\n listeners.set(key, bucket);\n }\n if (!bucket.has(listener))\n bucket.set(listener, ++registration);\n const registered = bucket.get(listener);\n return () => {\n if (bucket!.get(listener) !== registered)\n return;\n bucket!.delete(listener);\n if (!bucket!.size && listeners.get(key) === bucket)\n listeners.delete(key);\n };\n };\n const events: EditorEvents = {\n on: on as EditorEvents['on'],\n emit: (event, payload) => {\n if (closing)\n throw new Error('Editor events have been destroyed.');\n enqueue({ key: assertToken(event), payload, core: false });\n },\n };\n return {\n events,\n notify: (event, payload) => enqueue({ key: event, payload, core: true }),\n destroy: () => {\n if (closing)\n return;\n closing = true;\n queue.length = 0;\n enqueue({ key: 'destroy', payload: undefined, core: true });\n },\n };\n};\n", "import { documentHTML, parseHTML, renderDocument, sanitizeHTML, validateDocument } from '../document/index.js';\nimport { activeRange, bookmark, placeCaret, readTextSelection, restoreBookmark, selectText } from '../selection/index.js';\nimport type { SelectionBookmark } from '../selection/index.js';\nimport { editListInput, handlesListInput, indentList, listState, selectedBlocks } from '../lists/index.js';\nimport { applyFormat, inlineFormats, readFormats } from '../formatting/index.js';\nimport { inlineStyles, normalizeInlineStyle } from '../formatting/inline-attributes.js';\nimport { createEventHub } from '../events/index.js';\nimport type { EditorEvents } from '../events/types.js';\nimport type { Editor, EditorChange, EditorOptions, Snapshot } from './types.js';\nconst ensureDocument = (root: HTMLElement): boolean => {\n let normalized = false;\n if (!root.childNodes.length) {\n root.innerHTML = '<p><br></p>';\n normalized = true;\n }\n // Native input can create loose inline nodes; wrap them in paragraphs without replacing text nodes.\n let paragraph: HTMLParagraphElement | undefined;\n for (const node of [...root.childNodes]) {\n const inline = node.nodeType === 3 || (node.nodeType === 1 && /^(strong|em|u|s|a|span|code|img|br|sub|sup)$/.test((node as Element).localName));\n if (inline) {\n if (!paragraph) {\n paragraph = document.createElement('p');\n root.insertBefore(paragraph, node);\n }\n paragraph.append(node);\n normalized = true;\n }\n else\n paragraph = undefined;\n }\n if (['table', 'figure'].includes(root.lastElementChild?.localName ?? ''))\n root.append(Object.assign(document.createElement('p'), { innerHTML: '<br>' }));\n root.dataset.empty = String(!root.textContent && !root.querySelector('table,img,hr'));\n return normalized;\n};\nconst insertFragment = (root: HTMLElement, html: string): void => {\n const range = activeRange(root);\n if (!range)\n return;\n const fragment = renderDocument(parseHTML(html));\n if (!fragment.childNodes.length)\n return;\n range.deleteContents();\n const startElement = range.startContainer.nodeType === 1 ? range.startContainer as Element : range.startContainer.parentElement;\n const block = startElement?.closest('p,h1,h2,h3,h4,h5,h6,li,blockquote,pre');\n if (fragment.childNodes.length === 1 && fragment.firstChild instanceof HTMLParagraphElement && block) {\n const paragraph = fragment.firstChild;\n fragment.replaceChildren(...paragraph.childNodes);\n }\n const hasBlocks = [...fragment.childNodes].some((node) => node instanceof HTMLElement && /^(p|h[1-6]|ul|ol|table|figure|blockquote|pre)$/.test(node.localName));\n const last = fragment.lastChild!;\n if (hasBlocks && block && root.contains(block)) {\n const tailRange = document.createRange();\n tailRange.selectNodeContents(block);\n tailRange.setStart(range.startContainer, range.startOffset);\n const tail = block.cloneNode(false) as HTMLElement;\n tail.append(tailRange.extractContents());\n block.after(fragment);\n if (tail.textContent || tail.querySelector('img,br'))\n last.after(tail);\n if (!block.textContent && !block.querySelector('img'))\n block.remove();\n }\n else\n range.insertNode(fragment);\n const next = document.createRange();\n next.setStartAfter(last);\n next.collapse(true);\n const selection = document.getSelection();\n selection?.removeAllRanges();\n selection?.addRange(next);\n};\nexport const createEditor = (host: HTMLElement, options: EditorOptions = {}): Editor => {\n if (host.childNodes.length)\n throw new Error('Editor host must be empty. Pass initial HTML through value.');\n const plugins = options.plugins ?? [];\n if (new Set(plugins.map((plugin) => plugin.name)).size !== plugins.length)\n throw new Error('Duplicate editor plugin.');\n const limit = options.historyLimit ?? 100;\n if (!Number.isInteger(limit) || limit < 1 || limit > 10000)\n throw new RangeError('historyLimit must be an integer from 1 to 10000.');\n const initialDocument = parseHTML(options.value ?? '');\n const container = document.createElement('div');\n container.className = 'mw-editor';\n const surface = document.createElement('div');\n surface.className = 'mw-content';\n surface.setAttribute('role', 'textbox');\n surface.setAttribute('aria-multiline', 'true');\n surface.setAttribute('aria-label', options.label ?? '\u0422\u0435\u043A\u0441\u0442\u043E\u0432\u044B\u0439 \u0440\u0435\u0434\u0430\u043A\u0442\u043E\u0440');\n surface.dataset.placeholder = options.placeholder ?? '\u041D\u0430\u0447\u043D\u0438\u0442\u0435 \u043F\u0438\u0441\u0430\u0442\u044C\u2026';\n container.append(surface);\n host.append(container);\n surface.append(renderDocument(initialDocument));\n ensureDocument(surface);\n let destroyed = false;\n let readOnly = options.readOnly ?? false;\n let composing = false;\n let compositionStart: Snapshot | undefined;\n let pendingInput: Snapshot | undefined;\n let lastInputTime = 0;\n let lastInputType = '';\n let typingOverrides: Record<string, string | boolean> = {};\n let typingOffset: number | undefined;\n const clearTyping = () => { typingOverrides = {}; typingOffset = undefined; };\n const typingAtCaret = () => { const selection = readTextSelection(surface); return selection?.length === 0 && selection.index === typingOffset; };\n const undoStack: Snapshot[] = [];\n const redoStack: Snapshot[] = [];\n const eventHub = createEventHub();\n let transactionDepth = 0;\n let transactionFailed = false;\n let transactionError: unknown;\n let pendingSelectionNotification = false;\n const pluginAPIs = new Map<string, unknown>();\n const disposers: (() => void)[] = [];\n if (options.onChange)\n eventHub.events.on('change', options.onChange);\n const assertActive = () => {\n if (destroyed)\n throw new Error('Editor has been destroyed.');\n };\n const rejectDuringTransaction = (operation: string) => {\n if (!transactionDepth)\n return;\n const error = new Error(`${operation} is unavailable inside a transaction.`);\n transactionFailed = true;\n transactionError = error;\n throw error;\n };\n const events: EditorEvents = {\n on: eventHub.events.on,\n emit: (event, payload) => {\n assertActive();\n rejectDuringTransaction('events.emit');\n eventHub.events.emit(event, payload);\n },\n };\n const capture = (): Snapshot => ({ html: sanitizeHTML(surface.innerHTML), selection: bookmark(surface), ...(typingOffset !== undefined && Object.keys(typingOverrides).length && typingAtCaret() ? { typing: { offset: typingOffset, formats: { ...typingOverrides } } } : {}) });\n const restoreTyping = (snapshot: Snapshot) => {\n clearTyping();\n const selection = readTextSelection(surface);\n if (snapshot.typing && selection?.length === 0 && selection.index === snapshot.typing.offset) {\n typingOffset = snapshot.typing.offset;\n typingOverrides = { ...snapshot.typing.formats };\n }\n };\n let current = capture();\n let lastSelection = current.selection;\n const notifySelection = () => {\n if (destroyed)\n return;\n if (transactionDepth) {\n pendingSelectionNotification = true;\n return;\n }\n if (readTextSelection(surface) && !typingAtCaret())\n clearTyping();\n const saved = bookmark(surface);\n if (saved) {\n lastSelection = saved;\n current.selection = saved;\n }\n eventHub.notify('selectionchange', readTextSelection(surface));\n };\n const emit = (source: EditorChange['source']) => {\n const change: EditorChange = { html: editor.getHTML(), text: editor.getText(), source };\n const failures: unknown[] = [];\n try {\n eventHub.notify('change', change);\n }\n catch (error) {\n failures.push(error);\n }\n try {\n notifySelection();\n }\n catch (error) {\n failures.push(error);\n }\n if (failures.length)\n throw new AggregateError(failures, 'Editor change notification failed.');\n };\n const commitMutation = (before: Snapshot, inputType = ''): boolean => {\n const selection = readTextSelection(surface);\n if (ensureDocument(surface) && selection)\n selectText(surface, selection.index, selection.length);\n const after = capture();\n if (after.html === before.html) {\n current = after;\n return false;\n }\n const now = Date.now();\n const grouped = inputType === lastInputType && ['insertText', 'deleteContentBackward', 'deleteContentForward'].includes(inputType) && now - lastInputTime < 600 && before.selection && current.selection && JSON.stringify(before.selection) === JSON.stringify(current.selection);\n if (!grouped) {\n undoStack.push(before);\n if (undoStack.length > limit)\n undoStack.shift();\n }\n redoStack.length = 0;\n current = after;\n lastInputTime = inputType ? now : 0;\n lastInputType = inputType;\n return true;\n };\n const commit = (before: Snapshot, inputType = '') => {\n if (commitMutation(before, inputType))\n emit('user');\n };\n const restore = (snapshot: Snapshot) => {\n clearTyping();\n surface.innerHTML = snapshot.html;\n ensureDocument(surface);\n surface.focus({ preventScroll: true });\n restoreBookmark(surface, snapshot.selection);\n restoreTyping(snapshot);\n current = capture();\n lastSelection = current.selection;\n lastInputTime = 0;\n emit('user');\n };\n const runTransaction = (mutate: (surface: HTMLElement) => void, inputType = '') => {\n assertActive();\n if (readOnly)\n return;\n const invoke = () => {\n if (typeof mutate !== 'function' || mutate.constructor.name === 'AsyncFunction')\n throw new TypeError('Transactions require a synchronous callback.');\n const result: unknown = mutate(surface);\n if (result && (typeof result === 'object' || typeof result === 'function') && typeof (result as {\n then?: unknown;\n }).then === 'function') {\n if (result instanceof Promise)\n void result.catch(() => { });\n throw new TypeError('Transaction callbacks must not return a thenable.');\n }\n };\n if (transactionDepth) {\n transactionDepth++;\n try {\n invoke();\n }\n catch (error) {\n transactionFailed = true;\n transactionError = error;\n throw error;\n }\n finally {\n transactionDepth--;\n }\n return;\n }\n editor.focus();\n const before = capture();\n const previousUndo = [...undoStack];\n const previousRedo = [...redoStack];\n const previousInputTime = lastInputTime;\n const previousInputType = lastInputType;\n const previousPendingInput = pendingInput;\n const previousSelection = lastSelection;\n transactionDepth = 1;\n transactionFailed = false;\n transactionError = undefined;\n pendingSelectionNotification = false;\n let changed = false;\n try {\n invoke();\n if (transactionFailed)\n throw transactionError;\n changed = commitMutation(before, inputType);\n }\n catch (error) {\n surface.innerHTML = before.html;\n ensureDocument(surface);\n restoreBookmark(surface, before.selection);\n restoreTyping(before);\n current = capture();\n lastSelection = previousSelection;\n pendingInput = previousPendingInput;\n undoStack.splice(0, undoStack.length, ...previousUndo);\n redoStack.splice(0, redoStack.length, ...previousRedo);\n lastInputTime = previousInputTime;\n lastInputType = previousInputType;\n transactionDepth = 0;\n pendingSelectionNotification = false;\n throw error;\n }\n finally {\n transactionDepth = 0;\n }\n const selectionChanged = pendingSelectionNotification;\n pendingSelectionNotification = false;\n // Notifications are outside the rollback boundary: observers cannot undo a committed edit by throwing.\n if (changed)\n emit('user');\n else if (selectionChanged)\n notifySelection();\n };\n const editor: Editor = {\n element: container, surface, events,\n getHTML: () => { assertActive(); return sanitizeHTML(surface.innerHTML); },\n getText: () => { assertActive(); return surface.innerText; },\n getJSON: () => { assertActive(); return parseHTML(surface.innerHTML); },\n setHTML: (html) => {\n assertActive();\n rejectDuringTransaction('setHTML');\n const content = documentHTML(parseHTML(html));\n if (content === editor.getHTML())\n return;\n clearTyping();\n surface.innerHTML = content;\n ensureDocument(surface);\n undoStack.length = 0;\n redoStack.length = 0;\n lastInputTime = 0;\n lastSelection = undefined;\n current = capture();\n emit('api');\n },\n setJSON: (value) => {\n assertActive();\n rejectDuringTransaction('setJSON');\n const validated = validateDocument(value);\n editor.setHTML(documentHTML(validated));\n },\n getSelection: () => { assertActive(); return readTextSelection(surface); },\n setSelection: (index, length = 0) => { assertActive(); selectText(surface, index, length); notifySelection(); },\n getFormats: () => { assertActive(); return { ...readFormats(surface), ...(typingAtCaret() ? typingOverrides : {}) }; },\n setReadOnly: (value) => {\n assertActive();\n rejectDuringTransaction('setReadOnly');\n const changed = readOnly !== value;\n readOnly = value;\n surface.contentEditable = String(!value);\n surface.setAttribute('aria-readonly', String(value));\n container.dataset.readonly = String(value);\n const failures: unknown[] = [];\n if (changed) {\n try {\n eventHub.notify('readonlychange', value);\n }\n catch (error) {\n failures.push(error);\n }\n }\n try {\n notifySelection();\n }\n catch (error) {\n failures.push(error);\n }\n if (failures.length)\n throw new AggregateError(failures, 'Editor state notification failed.');\n },\n isReadOnly: () => { assertActive(); return readOnly; },\n format: (name, value) => {\n assertActive();\n if (readOnly)\n return;\n editor.focus();\n const selection = readTextSelection(surface);\n if (selection?.length === 0 && (Object.hasOwn(inlineFormats, name) || Object.hasOwn(inlineStyles, name))) {\n if (!typingAtCaret())\n clearTyping();\n typingOffset = selection.index;\n typingOverrides[name] = Object.hasOwn(inlineStyles, name) ? normalizeInlineStyle(name, value) : Boolean(value);\n notifySelection();\n return;\n }\n clearTyping();\n editor.transact(() => applyFormat(surface, name, value));\n },\n insertHTML: (html) => editor.transact(() => insertFragment(surface, html)),\n focus: () => {\n assertActive();\n surface.focus({ preventScroll: true });\n if (!activeRange(surface)) {\n if (lastSelection)\n restoreBookmark(surface, lastSelection);\n else\n placeCaret(surface.firstElementChild as HTMLElement ?? surface, true);\n }\n },\n undo: () => {\n assertActive();\n rejectDuringTransaction('undo');\n if (readOnly)\n return;\n const previous = undoStack.pop();\n if (previous) {\n redoStack.push(capture());\n restore(previous);\n }\n },\n redo: () => {\n assertActive();\n rejectDuringTransaction('redo');\n if (readOnly)\n return;\n const next = redoStack.pop();\n if (next) {\n undoStack.push(capture());\n restore(next);\n }\n },\n canUndo: () => { assertActive(); return undoStack.length > 0; },\n canRedo: () => { assertActive(); return redoStack.length > 0; },\n transact: (mutate) => runTransaction(mutate),\n providePlugin: (name, api) => {\n assertActive();\n if (pluginAPIs.has(name))\n throw new Error(`Plugin API already registered: ${name}`);\n pluginAPIs.set(name, api);\n return () => { pluginAPIs.delete(name); };\n },\n getPlugin: <T>(name: string) => { assertActive(); return pluginAPIs.get(name) as T | undefined; },\n subscribe: (listener) => { assertActive(); return eventHub.events.on('change', listener); },\n onSelectionChange: (listener) => { assertActive(); return eventHub.events.on('selectionchange', listener); },\n destroy: () => {\n if (destroyed)\n return;\n rejectDuringTransaction('destroy');\n destroyed = true;\n const failures: unknown[] = [];\n try {\n eventHub.destroy();\n }\n catch (error) {\n failures.push(error);\n }\n for (const dispose of disposers.reverse()) {\n try {\n dispose();\n }\n catch (error) {\n failures.push(error);\n }\n }\n pluginAPIs.clear();\n undoStack.length = 0;\n redoStack.length = 0;\n container.remove();\n if (failures.length)\n throw new AggregateError(failures, 'Editor cleanup failed.');\n },\n };\n const listen = <K extends keyof HTMLElementEventMap>(type: K, handler: (event: HTMLElementEventMap[K]) => void) => {\n surface.addEventListener(type, handler);\n disposers.push(() => surface.removeEventListener(type, handler));\n };\n listen('beforeinput', (event) => {\n if (readOnly) {\n event.preventDefault();\n return;\n }\n if (event.inputType === 'historyUndo' || event.inputType === 'historyRedo') {\n event.preventDefault();\n if (event.inputType === 'historyUndo')\n editor.undo();\n else\n editor.redo();\n return;\n }\n if (!composing && !event.isComposing && handlesListInput(surface, event.inputType)) {\n event.preventDefault();\n clearTyping();\n pendingInput = undefined;\n runTransaction(() => editListInput(surface, event.inputType));\n return;\n }\n if (event.inputType === 'insertText' && event.data && !composing && !event.isComposing && typingAtCaret() && Object.keys(typingOverrides).length) {\n event.preventDefault();\n const start = readTextSelection(surface)!.index;\n const text = event.data;\n const overrides = { ...typingOverrides };\n runTransaction(() => {\n const range = activeRange(surface)!;\n const parent = range.startContainer instanceof Element ? range.startContainer : range.startContainer.parentElement;\n const block = parent?.closest('p,h1,h2,h3,h4,h5,h6,li,blockquote,pre');\n if (block && !block.textContent && block.childNodes.length === 1 && block.firstChild instanceof HTMLBRElement) {\n block.replaceChildren();\n range.selectNodeContents(block);\n range.collapse(true);\n }\n range.insertNode(document.createTextNode(text));\n selectText(surface, start, text.length);\n for (const [name, enabled] of Object.entries(overrides))\n if ((Object.hasOwn(inlineStyles, name) ? readFormats(surface)[name] ?? false : Boolean(readFormats(surface)[name])) !== enabled)\n applyFormat(surface, name, enabled);\n selectText(surface, start + text.length);\n typingOffset = start + text.length;\n }, 'insertText');\n pendingInput = undefined;\n return;\n }\n pendingInput = capture();\n });\n listen('input', (nativeEvent) => {\n const event = nativeEvent as InputEvent;\n if (readOnly) {\n surface.innerHTML = current.html;\n return;\n }\n if (composing || event.isComposing)\n return;\n const before = pendingInput ?? current;\n pendingInput = undefined;\n commit(before, event.inputType);\n });\n listen('compositionstart', () => { clearTyping(); composing = true; compositionStart = capture(); });\n listen('compositionend', () => {\n composing = false;\n const before = compositionStart;\n compositionStart = undefined;\n pendingInput = undefined;\n if (before)\n commit(before);\n });\n listen('paste', (event) => {\n event.preventDefault();\n if (readOnly || !event.clipboardData)\n return;\n editor.focus();\n const html = event.clipboardData.getData('text/html');\n if (html)\n editor.insertHTML(html);\n else {\n const text = event.clipboardData.getData('text/plain');\n const holder = document.createElement('div');\n holder.textContent = text;\n editor.insertHTML(holder.innerHTML.replace(/\\r?\\n/g, '<br>'));\n }\n });\n listen('drop', (event) => { event.preventDefault(); });\n listen('keydown', (event) => {\n if (!composing && !event.isComposing && !readOnly && !event.ctrlKey && !event.metaKey && !event.altKey && (event.key === 'Enter' || event.key === 'Backspace')) {\n const type = event.key === 'Backspace' ? 'deleteContentBackward' : event.shiftKey ? 'insertLineBreak' : 'insertParagraph';\n if (handlesListInput(surface, type)) {\n event.preventDefault();\n clearTyping();\n pendingInput = undefined;\n runTransaction(() => editListInput(surface, type));\n return;\n }\n }\n if (!composing && !event.isComposing && !readOnly && event.key === 'Tab' && !event.ctrlKey && !event.metaKey && !event.altKey) {\n const blocks = selectedBlocks(surface);\n if (blocks.length && blocks.every((block) => block.localName === 'li' && !block.closest('td,th')) && listState(surface).canOutdent) {\n event.preventDefault();\n clearTyping();\n runTransaction(() => indentList(surface, event.shiftKey ? -1 : 1));\n return;\n }\n }\n if (composing || event.isComposing || readOnly || !(event.ctrlKey || event.metaKey) || event.altKey)\n return;\n const key = event.key.toLowerCase();\n if (key === 'z' || key === 'y') {\n event.preventDefault();\n if (key === 'y' || event.shiftKey)\n editor.redo();\n else\n editor.undo();\n }\n const name = ({ b: 'bold', i: 'italic', u: 'underline' } as Record<string, string>)[key];\n if (name) {\n event.preventDefault();\n editor.format(name, (editor.getFormats().mixed as string[] | undefined)?.includes(name) || !editor.getFormats()[name]);\n }\n });\n document.addEventListener('selectionchange', notifySelection);\n disposers.push(() => document.removeEventListener('selectionchange', notifySelection));\n try {\n editor.setReadOnly(readOnly);\n for (const plugin of plugins) {\n const dispose = plugin.setup(editor);\n if (dispose)\n disposers.push(dispose);\n }\n return editor;\n }\n catch (error) {\n editor.destroy();\n throw error;\n }\n};\n", "import type { ToolbarAction, ToolbarOptions } from './types.js';\nexport type { ToolbarAction, ToolbarOptions } from './types.js';\nimport type { Editor } from '../../index.js';\nimport { inlineStyles, normalizeInlineStyle } from '../../formatting/inline-attributes.js';\nimport { bookmark, restoreBookmark } from '../../selection/index.js';\nimport type { SelectionBookmark } from '../../selection/index.js';\nconst defaultActions: ToolbarAction[] = [\n { label: '\u041E\u0442\u043C\u0435\u043D\u0438\u0442\u044C', text: '\u21B6', run: (editor) => editor.undo(), enabled: (editor) => editor.canUndo() },\n { label: '\u041F\u043E\u0432\u0442\u043E\u0440\u0438\u0442\u044C', text: '\u21B7', run: (editor) => editor.redo(), enabled: (editor) => editor.canRedo() },\n { label: '\u041F\u043E\u043B\u0443\u0436\u0438\u0440\u043D\u044B\u0439', text: 'B', format: 'bold' },\n { label: '\u041A\u0443\u0440\u0441\u0438\u0432', text: 'I', format: 'italic' },\n { label: '\u041F\u043E\u0434\u0447\u0451\u0440\u043A\u043D\u0443\u0442\u044B\u0439', text: 'U', format: 'underline' },\n { label: '\u0417\u0430\u0433\u043E\u043B\u043E\u0432\u043E\u043A', text: 'H\u2082', format: 'header', value: 2 },\n { label: '\u041C\u0430\u0440\u043A\u0438\u0440\u043E\u0432\u0430\u043D\u043D\u044B\u0439 \u0441\u043F\u0438\u0441\u043E\u043A', text: '\u2637', format: 'list', value: 'bullet' },\n { label: '\u041D\u0443\u043C\u0435\u0440\u043E\u0432\u0430\u043D\u043D\u044B\u0439 \u0441\u043F\u0438\u0441\u043E\u043A', text: '1.', format: 'list', value: 'ordered' },\n { label: '\u0423\u0432\u0435\u043B\u0438\u0447\u0438\u0442\u044C \u043E\u0442\u0441\u0442\u0443\u043F', text: '\u21E5', format: 'indent', value: 1, enabled: (editor) => Boolean(editor.getFormats().canIndent) },\n { label: '\u0423\u043C\u0435\u043D\u044C\u0448\u0438\u0442\u044C \u043E\u0442\u0441\u0442\u0443\u043F', text: '\u21E4', format: 'indent', value: -1, enabled: (editor) => Boolean(editor.getFormats().canOutdent) },\n { label: '\u0426\u0438\u0442\u0430\u0442\u0430', text: '\u275D', format: 'blockquote' },\n { label: '\u041E\u0447\u0438\u0441\u0442\u0438\u0442\u044C \u0444\u043E\u0440\u043C\u0430\u0442\u0438\u0440\u043E\u0432\u0430\u043D\u0438\u0435', text: 'Tx', format: 'clear', enabled: (editor) => Boolean(editor.getSelection()?.length) },\n];\nexport const createToolbar = (host: HTMLElement, editor: Editor, actions = defaultActions, options: ToolbarOptions = {}): () => void => {\n actions = actions.map((action) => action.format && Object.hasOwn(inlineStyles, action.format) ? { ...action, value: normalizeInlineStyle(action.format, action.value) } : action);\n const toolbar = document.createElement('div');\n toolbar.className = 'mw-toolbar';\n toolbar.setAttribute('role', 'toolbar');\n toolbar.setAttribute('aria-label', options.label ?? '\u0424\u043E\u0440\u043C\u0430\u0442\u0438\u0440\u043E\u0432\u0430\u043D\u0438\u0435');\n let saved: SelectionBookmark | undefined;\n let disposed = false;\n let tabIndex = 0;\n const cleanups: (() => void)[] = [];\n const buttons = actions.map((action) => {\n const button = document.createElement('button');\n button.type = 'button';\n button.textContent = action.text;\n button.title = action.label;\n button.setAttribute('aria-label', action.label);\n const down = (event: MouseEvent) => event.preventDefault();\n const click = () => {\n if (disposed || button.disabled || editor.isReadOnly())\n return;\n editor.focus();\n if (saved)\n restoreBookmark(editor.surface, saved);\n if (action.enabled && !action.enabled(editor))\n return;\n if (action.run)\n action.run(editor);\n else if (action.format) {\n const formats = editor.getFormats();\n const mixed = (formats.mixed as string[] | undefined)?.includes(action.format);\n editor.format(action.format, !mixed && formats[action.format] === (action.value ?? true) ? false : action.value ?? true);\n }\n update();\n };\n button.addEventListener('mousedown', down);\n button.addEventListener('click', click);\n cleanups.push(() => { button.removeEventListener('mousedown', down); button.removeEventListener('click', click); });\n toolbar.append(button);\n return button;\n });\n const update = () => {\n if (disposed)\n return;\n saved = bookmark(editor.surface) ?? saved;\n const formats = editor.getFormats();\n buttons.forEach((button, index) => {\n const action = actions[index];\n button.disabled = editor.isReadOnly() || (action.enabled ? !action.enabled(editor) : false);\n if (action.format && !['indent', 'clear'].includes(action.format))\n button.setAttribute('aria-pressed', (formats.mixed as string[] | undefined)?.includes(action.format) ? 'mixed' : String(formats[action.format] === (action.value ?? true)));\n });\n if (buttons[tabIndex]?.disabled || !buttons[tabIndex])\n tabIndex = buttons.findIndex((button) => !button.disabled);\n buttons.forEach((button, index) => { button.tabIndex = index === tabIndex ? 0 : -1; });\n };\n const keyboard = (event: KeyboardEvent) => {\n const enabled = buttons.filter((button) => !button.disabled);\n if (!enabled.length)\n return;\n const index = enabled.indexOf(document.activeElement as HTMLButtonElement);\n if (index < 0 || event.ctrlKey || event.metaKey || event.altKey)\n return;\n if (event.key === 'Escape') {\n event.preventDefault();\n editor.focus();\n if (saved)\n restoreBookmark(editor.surface, saved);\n return;\n }\n const direction = getComputedStyle(toolbar).direction === 'rtl' ? -1 : 1;\n const next = event.key === 'Home' ? 0 : event.key === 'End' ? enabled.length - 1 : event.key === 'ArrowRight' ? (index + direction + enabled.length) % enabled.length : event.key === 'ArrowLeft' ? (index - direction + enabled.length) % enabled.length : -1;\n if (next >= 0) {\n event.preventDefault();\n tabIndex = buttons.indexOf(enabled[next]);\n update();\n enabled[next].focus();\n }\n };\n toolbar.addEventListener('keydown', keyboard);\n const unsubscribe = editor.subscribe((change) => {\n if (change.source === 'api')\n saved = undefined; update();\n });\n const unselect = editor.onSelectionChange(update);\n host.append(toolbar);\n update();\n return () => {\n if (disposed)\n return; disposed = true; unsubscribe(); unselect(); toolbar.removeEventListener('keydown', keyboard); for (const dispose of cleanups)\n dispose(); toolbar.remove();\n };\n};\n"],
|
|
5
|
-
"mappings": "AAGO,IAAMA,GAAe,CAAC,IAAK,KAAM,KAAM,KAAM,KAAM,KAAM,KAAM,aAAc,MAAO,OAAQ,SAAU,KAAM,IAAK,IAAK,MAAO,MAAO,IAAK,OAAQ,KAAM,KAAM,KAAM,KAAM,KAAM,MAAO,SAAU,aAAc,QAAS,UAAW,WAAY,MAAO,QAAS,QAAS,QAAS,KAAM,KAAM,IAAI,EACjSC,GAAO,IAAI,IAAYD,EAAY,EACnCE,GAAU,IAAI,IAAI,CAAC,SAAU,QAAS,SAAU,SAAU,QAAS,MAAO,OAAQ,WAAY,OAAQ,QAAS,SAAU,WAAY,SAAU,WAAY,OAAQ,OAAQ,MAAM,CAAC,EAClLC,GAAkC,CAAE,EAAG,SAAU,EAAG,KAAM,OAAQ,IAAK,IAAK,GAAI,EAChFC,GAAY,IACZC,GAAY,IACZC,GAAU,CAACC,EAAeC,IAAuC,CACrE,IAAMC,EAAUF,EAAM,KAAK,EAC3B,GAAI,CAACE,GAAW,wBAAwB,KAAKA,CAAO,EAClD,OAEF,IAAMC,EAAW,wBAAwB,KAAKD,CAAO,IAAI,CAAC,EAAE,YAAY,EACxE,GAAI,EAAAC,GAAY,EAAEF,EAAQ,CAAC,OAAQ,OAAO,EAAI,CAAC,OAAQ,QAAS,SAAU,KAAK,GAAG,SAASE,CAAQ,IAE/F,EAAAD,EAAQ,WAAW,IAAI,GAAKA,EAAQ,WAAW,IAAI,GAEvD,OAAOA,CACT,EACME,GAAaJ,GAA0B,CAC3C,IAAMK,EAAmB,CAAC,EAC1B,QAAWC,KAAeN,EAAM,MAAM,GAAG,EAAG,CAC1C,IAAMO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AX_DEPTH", "safeURL", "value", "image", "trimmed", "protocol", "safeStyle", "result", "declaration", "separator", "property", "content", "color", "length", "attributesFor", "tag", "input", "output", "key", "clean", "tokens", "token", "dimensions", "styles", "part", "readDOM", "node", "depth", "budget", "element", "original", "children", "child", "attributes", "attr", "parseHTML", "html", "template", "validateDocument", "count", "textLength", "visit", "attrs", "renderDocument", "fragment", "append", "parent", "documentHTML", "container", "sanitizeHTML", "activeRange", "root", "selection", "range", "nodePath", "target", "result", "node", "bookmark", "restoreBookmark", "saved", "resolve", "path", "index", "start", "end", "limit", "offset", "startOffset", "endOffset", "readTextSelection", "prefix", "selectText", "length", "value", "walker", "nodes", "current", "locate", "last", "placeCaret", "element", "preserveRange", "mutate", "native", "backward", "tail", "head", "next", "blocks", "isList", "element", "elementAt", "node", "blockAt", "root", "preferItem", "item", "block", "touches", "range", "content", "start", "end", "first", "last", "selectedBlocks", "activeRange", "preferItems", "found", "walker", "topItems", "items", "parent", "itemRange", "siblings", "depth", "result", "compatible", "a", "b", "joinLists", "list", "previous", "splitAround", "replacement", "tail", "ownContent", "unwrapRoot", "paragraphOnly", "paragraphNode", "paragraph", "nested", "output", "lift", "owner", "trailing", "listState", "canIndent", "child", "indentList", "direction", "preserveRange", "applyList", "value", "selected", "tag", "empty", "placeholder", "atStart", "prefix", "handlesListInput", "inputType", "editListInput", "next", "caret", "selection", "placeCaret", "br", "marker", "target", "inlineStyles", "blocks", "checkedAttributes", "tag", "attributes", "validateDocument", "normalizeInlineStyle", "name", "value", "property", "attrs", "probe", "color", "normalizeLink", "input", "link", "clean", "mergeLinkAttributes", "previous", "patch", "equalAttributes", "a", "b", "withoutProperty", "style", "part", "groupPieces", "pieces", "result", "piece", "last", "compact", "nodes", "node", "next", "transformInlineAttributes", "document", "from", "to", "operation", "position", "wrap", "group", "children", "visit", "inheritedLink", "start", "left", "right", "begin", "end", "selected", "text", "child", "content", "applyLink", "root", "value", "link", "normalizeLink", "range", "activeRange", "selection", "readTextSelection", "element", "anchor", "existing", "documentHTML", "transformInlineAttributes", "parseHTML", "selectText", "attrs", "mergeLinkAttributes", "attr", "preserveRange", "key", "val", "created", "parent", "tail", "native", "
|
|
3
|
+
"sources": ["../src/document/index.ts", "../src/selection/index.ts", "../src/lists/index.ts", "../src/input/block-boundaries.ts", "../src/formatting/inline-attributes.ts", "../src/formatting/links.ts", "../src/formatting/inline-document.ts", "../src/formatting/local-inline.ts", "../src/formatting/index.ts", "../src/events/index.ts", "../src/editor/html-snapshots.ts", "../src/editor/create-editor.ts", "../src/ui/toolbar/index.ts"],
|
|
4
|
+
"sourcesContent": ["import type { DocumentTag, TextNode, ElementNode, DocumentNode, EditorDocument } from './types.js';\nexport type { DocumentTag, TextNode, ElementNode, DocumentNode, EditorDocument } from './types.js';\n/** Versioned, framework-independent document tree. Only supported HTML semantics are stored. */\nexport const documentTags = ['p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'blockquote', 'pre', 'code', 'strong', 'em', 'u', 's', 'sub', 'sup', 'a', 'span', 'br', 'hr', 'ul', 'ol', 'li', 'img', 'figure', 'figcaption', 'table', 'caption', 'colgroup', 'col', 'thead', 'tbody', 'tfoot', 'tr', 'td', 'th'] as const;\nconst tags = new Set<string>(documentTags);\nconst omitted = new Set(['script', 'style', 'iframe', 'object', 'embed', 'svg', 'math', 'template', 'form', 'input', 'button', 'textarea', 'select', 'noscript', 'link', 'meta', 'base']);\nconst aliases: Record<string, string> = { b: 'strong', i: 'em', strike: 's', div: 'p' };\nconst MAX_NODES = 100000;\nconst MAX_DEPTH = 100;\nconst safeURL = (value: string, image: boolean): string | undefined => {\n const trimmed = value.trim();\n if (!trimmed || /[\\u0000-\\u0020\\u007f]/.test(trimmed))\n return;\n // Explicit protocols and relative references only. Never data:, blob:, or script URLs.\n const protocol = /^([a-z][a-z\\d+.-]*):/i.exec(trimmed)?.[1].toLowerCase();\n if (protocol && !(image ? ['http', 'https'] : ['http', 'https', 'mailto', 'tel']).includes(protocol))\n return;\n if (trimmed.startsWith('\\\\') || trimmed.startsWith('//'))\n return;\n return trimmed;\n};\nconst safeStyle = (value: string): string => {\n const result: string[] = [];\n for (const declaration of value.split(';')) {\n const separator = declaration.indexOf(':');\n if (separator < 0)\n continue;\n const property = declaration.slice(0, separator).trim().toLowerCase();\n const content = declaration.slice(separator + 1).trim().toLowerCase();\n const color = /^(#[a-f\\d]{3,8}|[a-z]{1,24}|(?:rgb|rgba|hsl|hsla)\\([\\d\\s.,%+-]+\\))$/;\n const length = /^(?:\\d{1,4}(?:\\.\\d{1,3})?)(?:px|%|em|rem)$/;\n const valid = ['color', 'background-color', 'border-color'].includes(property) ? color.test(content)\n : ['width', 'height', 'font-size'].includes(property) ? length.test(content)\n : property === 'text-align' ? ['left', 'center', 'right', 'justify'].includes(content)\n : property === 'font-weight' ? /^(bold|normal|[1-9]00)$/.test(content)\n : property === 'font-style' ? ['italic', 'normal'].includes(content)\n : property === 'text-decoration' ? /^(underline|line-through|none)$/.test(content)\n : false;\n if (valid)\n result.push(`${property}: ${content}`);\n }\n return result.join('; ');\n};\nconst attributesFor = (tag: DocumentTag, input: Record<string, unknown>): Record<string, string> => {\n const output: Record<string, string> = {};\n for (const [key, value] of Object.entries(input)) {\n if (typeof value !== 'string' || value.length > 20000)\n continue;\n if (key === 'style') {\n const clean = safeStyle(value);\n if (clean)\n output.style = clean;\n }\n else if (key === 'title' || (tag === 'img' && key === 'alt'))\n output[key] = value;\n else if ((tag === 'a' && key === 'href') || (tag === 'img' && key === 'src')) {\n const clean = safeURL(value, tag === 'img');\n if (clean)\n output[key] = clean;\n }\n else if ((['td', 'th'].includes(tag) && ['rowspan', 'colspan'].includes(key)) || (['img', 'col', 'table'].includes(tag) && ['width', 'height', 'span'].includes(key))) {\n if (/^\\d{1,4}$/.test(value) && Number(value) > 0 && Number(value) <= 1000)\n output[key] = value;\n }\n else if (tag === 'a' && key === 'target' && ['_self', '_blank'].includes(value))\n output.target = value;\n else if (tag === 'a' && key === 'rel') {\n const tokens = [...new Set(value.toLowerCase().split(/\\s+/).filter((token) => ['noopener', 'noreferrer'].includes(token)))];\n if (tokens.length)\n output.rel = tokens.join(' ');\n }\n else if (tag === 'th' && key === 'scope' && ['row', 'col', 'rowgroup', 'colgroup'].includes(value))\n output[key] = value;\n }\n if (tag === 'img' && (output.width || output.height)) {\n const dimensions = ['width', 'height'].filter((key) => output[key]);\n const styles = (output.style ?? '').split(';').map((part) => part.trim()).filter((part) => part && !dimensions.includes(part.slice(0, part.indexOf(':')).trim()));\n output.style = [...styles, ...dimensions.map((key) => `${key}: ${output[key]}px`)].join('; ');\n }\n if (tag === 'a' && output.target === '_blank')\n output.rel = 'noopener noreferrer';\n return output;\n};\nconst readDOM = (node: Node, depth: number, budget: {\n count: number;\n}): DocumentNode[] => {\n if (++budget.count > MAX_NODES || depth > MAX_DEPTH)\n throw new RangeError('Document exceeds structural limits.');\n if (node.nodeType === 3)\n return [{ type: 'text', text: node.textContent ?? '' }];\n if (node.nodeType !== 1)\n return [];\n const element = node as Element;\n const original = element.localName.toLowerCase();\n if (element.namespaceURI !== 'http://www.w3.org/1999/xhtml' || omitted.has(original))\n return [];\n const children = [...element.childNodes].flatMap((child) => readDOM(child, depth + 1, budget));\n const tag = aliases[original] ?? original;\n if (!tags.has(tag))\n return children;\n const attributes = attributesFor(tag as DocumentTag, Object.fromEntries([...element.attributes].map((attr) => [attr.name, attr.value])));\n if (tag === 'img' && !attributes.src)\n return [];\n return [{ type: 'element', tag: tag as DocumentTag, attributes, children }];\n};\nexport const parseHTML = (html: string): EditorDocument => {\n if (html.length > 5000000)\n throw new RangeError('HTML exceeds the document size limit.');\n // A template is inert: script execution and active resource loading are never used for import.\n const template = document.createElement('template');\n template.innerHTML = html;\n const budget = { count: 0 };\n return { version: 1, children: [...template.content.childNodes].flatMap((node) => readDOM(node, 0, budget)) };\n};\nexport const validateDocument = (input: unknown): EditorDocument => {\n if (!input || typeof input !== 'object' || !('version' in input) || input.version !== 1 || !('children' in input) || !Array.isArray(input.children))\n throw new TypeError('Expected a version 1 document.');\n let count = 0;\n let textLength = 0;\n const visit = (value: unknown, depth: number): DocumentNode => {\n if (++count > MAX_NODES || depth > MAX_DEPTH)\n throw new RangeError('Document exceeds structural limits.');\n if (!value || typeof value !== 'object' || !('type' in value))\n throw new TypeError('Invalid document node.');\n if (value.type === 'text' && 'text' in value && typeof value.text === 'string') {\n textLength += value.text.length;\n if (textLength > 5000000)\n throw new RangeError('Document text exceeds size limit.');\n return { type: 'text', text: value.text };\n }\n if (value.type !== 'element' || !('tag' in value) || typeof value.tag !== 'string' || !tags.has(value.tag) || !('children' in value) || !Array.isArray(value.children))\n throw new TypeError('Invalid document element.');\n const attrs = 'attributes' in value && value.attributes && typeof value.attributes === 'object' && !Array.isArray(value.attributes) ? value.attributes : {};\n return { type: 'element', tag: value.tag as DocumentTag, attributes: attributesFor(value.tag as DocumentTag, attrs as Record<string, unknown>), children: value.children.map((child) => visit(child, depth + 1)) };\n };\n return { version: 1, children: input.children.map((child) => visit(child, 0)) };\n};\nexport const renderDocument = (value: EditorDocument): DocumentFragment => {\n const fragment = document.createDocumentFragment();\n const append = (parent: Node, node: DocumentNode) => {\n if (node.type === 'text') {\n parent.appendChild(document.createTextNode(node.text));\n return;\n }\n const element = document.createElement(node.tag);\n for (const [key, value] of Object.entries(node.attributes))\n element.setAttribute(key, value);\n for (const child of node.children)\n append(element, child);\n parent.appendChild(element);\n };\n for (const node of value.children)\n append(fragment, node);\n return fragment;\n};\nexport const documentHTML = (value: EditorDocument): string => {\n const container = document.createElement('div');\n container.append(renderDocument(value));\n return container.innerHTML;\n};\nexport const sanitizeHTML = (html: string): string => { return documentHTML(parseHTML(html)); };\n", "import type { TextSelection, SelectionBookmark } from './types.js';\nexport type { TextSelection, SelectionBookmark } from './types.js';\nexport const activeRange = (root: HTMLElement): Range | undefined => {\n const selection = root.ownerDocument.getSelection();\n if (!selection?.rangeCount)\n return;\n const range = selection.getRangeAt(0);\n if (!root.contains(range.startContainer) || !root.contains(range.endContainer))\n return;\n return range.cloneRange();\n};\nconst nodePath = (root: Node, target: Node): number[] => {\n const result: number[] = [];\n let node = target;\n while (node !== root && node.parentNode) {\n result.unshift([...node.parentNode.childNodes].indexOf(node as ChildNode));\n node = node.parentNode;\n }\n return result;\n};\nexport const bookmark = (root: HTMLElement): SelectionBookmark | undefined => {\n const range = activeRange(root);\n if (!range)\n return;\n const selection = root.ownerDocument.getSelection()!;\n return { start: nodePath(root, range.startContainer), startOffset: range.startOffset, end: nodePath(root, range.endContainer), endOffset: range.endOffset, backward: !range.collapsed && selection.anchorNode === range.endContainer && selection.anchorOffset === range.endOffset };\n};\nexport const restoreBookmark = (root: HTMLElement, saved: SelectionBookmark | undefined): void => {\n if (!saved)\n return;\n const resolve = (path: number[]) => path.reduce<Node>((node, index) => node.childNodes[index] ?? node, root);\n const start = resolve(saved.start);\n const end = resolve(saved.end);\n const limit = (node: Node, offset: number) => Math.min(offset, node.nodeType === 3 ? (node.textContent?.length ?? 0) : node.childNodes.length);\n const selection = root.ownerDocument.getSelection();\n if (!selection)\n return;\n const startOffset = limit(start, saved.startOffset);\n const endOffset = limit(end, saved.endOffset);\n if (saved.backward)\n selection.setBaseAndExtent(end, endOffset, start, startOffset);\n else\n selection.setBaseAndExtent(start, startOffset, end, endOffset);\n};\nexport const readTextSelection = (root: HTMLElement): TextSelection | undefined => {\n const range = activeRange(root);\n if (!range)\n return;\n const prefix = root.ownerDocument.createRange();\n prefix.selectNodeContents(root);\n prefix.setEnd(range.startContainer, range.startOffset);\n return { index: prefix.toString().length, length: range.toString().length };\n};\nexport const selectText = (root: HTMLElement, index: number, length = 0): void => {\n if (![index, length].every((value) => Number.isInteger(value) && value >= 0))\n throw new RangeError('Selection offsets must be non-negative integers.');\n const walker = root.ownerDocument.createTreeWalker(root, 4);\n const nodes: Text[] = [];\n let current: Node | null;\n while ((current = walker.nextNode()))\n nodes.push(current as Text);\n const locate = (offset: number): [\n Node,\n number\n ] => {\n for (const node of nodes) {\n if (offset <= node.length)\n return [node, offset];\n offset -= node.length;\n }\n const last = nodes.at(-1);\n return last ? [last, last.length] : [root.querySelector('p,h1,h2,h3,h4,h5,h6,li,blockquote,pre') ?? root, 0];\n };\n const [start, startOffset] = locate(index);\n const [end, endOffset] = locate(index + length);\n const range = root.ownerDocument.createRange();\n range.setStart(start, startOffset);\n range.setEnd(end, endOffset);\n root.focus({ preventScroll: true });\n const selection = root.ownerDocument.getSelection();\n selection?.removeAllRanges();\n selection?.addRange(range);\n};\nexport const placeCaret = (element: HTMLElement, end = false): void => {\n const range = element.ownerDocument.createRange();\n range.selectNodeContents(element);\n range.collapse(!end);\n const selection = element.ownerDocument.getSelection();\n selection?.removeAllRanges();\n selection?.addRange(range);\n};\n/** Keep actual DOM positions while moving blocks, including empty list items. */\nexport const preserveRange = (root: HTMLElement, mutate: () => void): void => {\n const range = activeRange(root);\n if (!range)\n return;\n const native = root.ownerDocument.getSelection()!;\n const backward = !range.collapsed && native.anchorNode === range.endContainer && native.anchorOffset === range.endOffset;\n const start = root.ownerDocument.createComment('mw-start');\n const end = range.collapsed ? undefined : root.ownerDocument.createComment('mw-end');\n if (end) {\n const tail = range.cloneRange();\n tail.collapse(false);\n tail.insertNode(end);\n }\n const head = range.cloneRange();\n head.collapse(true);\n head.insertNode(start);\n try {\n mutate();\n if (root.contains(start) && (!end || root.contains(end))) {\n const next = root.ownerDocument.createRange();\n next.setStartBefore(start);\n if (end)\n next.setEndBefore(end);\n else\n next.collapse(true);\n start.remove();\n end?.remove();\n root.normalize();\n if (backward)\n native.setBaseAndExtent(next.endContainer, next.endOffset, next.startContainer, next.startOffset);\n else {\n native.removeAllRanges();\n native.addRange(next);\n }\n }\n }\n finally {\n start.remove();\n end?.remove();\n }\n};\n", "import { activeRange, placeCaret, preserveRange } from '../selection/index.js';\nconst blocks = 'p,h1,h2,h3,h4,h5,h6,blockquote,pre,li';\nconst isList = (element: Element | null): element is HTMLUListElement | HTMLOListElement => !!element && /^(ul|ol)$/.test(element.localName);\nconst elementAt = (node: Node): Element | null => node instanceof Element ? node : node.parentElement;\nconst blockAt = (root: HTMLElement, node: Node, preferItem = true): HTMLElement | undefined => {\n const element = elementAt(node);\n const item = element?.closest<HTMLElement>('li');\n const block = (preferItem && item && root.contains(item) ? item : undefined) ?? element?.closest<HTMLElement>(blocks);\n return block && root.contains(block) ? block : undefined;\n};\nconst touches = (range: Range, node: Node): boolean => {\n const content = node.ownerDocument!.createRange();\n if (node.nodeType === 3)\n content.selectNodeContents(node);\n else\n content.selectNode(node);\n const start = range.cloneRange();\n start.collapse(true);\n const end = range.cloneRange();\n end.collapse(false);\n const first = content.cloneRange();\n first.collapse(true);\n const last = content.cloneRange();\n last.collapse(false);\n return start.compareBoundaryPoints(Range.START_TO_START, last) < 0 && end.compareBoundaryPoints(Range.START_TO_START, first) > 0;\n};\nexport const selectedBlocks = (root: HTMLElement, range = activeRange(root), preferItems = true): HTMLElement[] => {\n if (!range)\n return [];\n if (range.collapsed) {\n const block = blockAt(root, range.startContainer, preferItems);\n return block ? [block] : [];\n }\n const found = new Set<HTMLElement>();\n const walker = root.ownerDocument.createTreeWalker(root, NodeFilter.SHOW_TEXT | NodeFilter.SHOW_ELEMENT);\n let node: Node | null;\n while ((node = walker.nextNode())) {\n if (!(node.nodeType === 3 && node.textContent) && !(node instanceof Element && /^(br|img|hr)$/.test(node.localName)))\n continue;\n if (touches(range, node)) {\n const block = blockAt(root, node, preferItems);\n if (block)\n found.add(block);\n }\n }\n return [...root.querySelectorAll<HTMLElement>(blocks)].filter((block) => found.has(block));\n};\nconst topItems = (items: HTMLElement[]) => items.filter((item) => !items.some((parent) => parent !== item && parent.contains(item)));\nconst itemRange = (root: HTMLElement): HTMLLIElement[] => {\n const items = topItems(selectedBlocks(root));\n if (!items.length || items.some((item) => item.localName !== 'li' || !isList(item.parentElement)))\n return [];\n const parent = items[0].parentElement;\n if (items.some((item) => item.parentElement !== parent))\n return [];\n const siblings = [...parent!.children];\n if (siblings.indexOf(items.at(-1)!) - siblings.indexOf(items[0]) + 1 !== items.length)\n return [];\n return items as HTMLLIElement[];\n};\nconst depth = (root: HTMLElement, item: HTMLElement): number => {\n let result = 0; let parent: Element | null = item.parentElement; while (parent && parent !== root) {\n if (isList(parent))\n result++;\n parent = parent.parentElement;\n } return result;\n};\nconst compatible = (a: Element | null, b: Element): a is HTMLElement => !!a && a.localName === b.localName && isList(a) && a.getAttribute('style') === b.getAttribute('style');\nconst joinLists = (root: HTMLElement): void => {\n for (const list of [...root.querySelectorAll<HTMLElement>('ul,ol')]) {\n if (!root.contains(list))\n continue;\n const previous = list.previousSibling;\n if (previous instanceof Element && compatible(previous, list)) {\n previous.append(...list.childNodes);\n list.remove();\n }\n }\n};\nconst splitAround = (item: HTMLLIElement, replacement: Node[]): void => {\n const list = item.parentElement!;\n const tail = list.cloneNode(false) as HTMLElement;\n while (item.nextSibling)\n tail.append(item.nextSibling);\n item.remove();\n list.after(...replacement, ...(tail.childNodes.length ? [tail] : []));\n if (!list.childNodes.length)\n list.remove();\n};\nconst ownContent = (item: HTMLElement) => [...item.childNodes].filter((node) => !(node instanceof Element && isList(node)));\nconst unwrapRoot = (item: HTMLLIElement, paragraphOnly = false): void => {\n const paragraphNode = () => {\n const node = document.createElement('p'); if (item.hasAttribute('style'))\n node.setAttribute('style', item.getAttribute('style')!); return node;\n };\n let paragraph = paragraphNode();\n const nested = [...item.children].filter(isList);\n const content = ownContent(item);\n // Imported items may contain paragraphs; retain their block structure rather than nest p in p.\n const output: Node[] = [];\n for (const node of content) {\n if (paragraphOnly && node instanceof HTMLElement && /^(p|h[1-6]|blockquote|pre)$/.test(node.localName)) {\n paragraph.append(...node.childNodes);\n }\n else if (node instanceof HTMLElement && /^(p|h[1-6]|blockquote|pre)$/.test(node.localName)) {\n if (paragraph.childNodes.length)\n output.push(paragraph);\n paragraph = paragraphNode();\n output.push(node);\n }\n else\n paragraph.append(node);\n }\n if (paragraph.childNodes.length || !output.length) {\n if (!paragraph.childNodes.length)\n paragraph.append(document.createElement('br'));\n output.push(paragraph);\n }\n splitAround(item, [...output, ...nested]);\n};\nconst lift = (items: HTMLLIElement[]): void => {\n const list = items[0].parentElement!;\n const owner = list.parentElement;\n if (owner?.localName !== 'li' || !isList(owner.parentElement)) {\n for (const item of items)\n unwrapRoot(item);\n return;\n }\n const trailing = list.cloneNode(false) as HTMLElement;\n while (items.at(-1)!.nextSibling)\n trailing.append(items.at(-1)!.nextSibling!);\n if (trailing.childNodes.length)\n items.at(-1)!.append(trailing);\n owner.after(...items);\n if (!list.childNodes.length)\n list.remove();\n};\nexport const listState = (root: HTMLElement) => {\n const items = itemRange(root);\n const canIndent = !!items.length && items[0].previousElementSibling?.localName === 'li' && items.every((item) => [item, ...item.querySelectorAll<HTMLElement>('li')].every((child) => depth(root, child) < 8));\n return { listDepth: items.length ? depth(root, items[0]) : 0, canIndent, canOutdent: !!items.length };\n};\nexport const indentList = (root: HTMLElement, direction: unknown): void => {\n if (direction !== 1 && direction !== -1)\n throw new TypeError('List indentation requires 1 or -1.');\n const items = itemRange(root);\n if (!items.length)\n throw new RangeError('Select consecutive items in the same list.');\n if (direction === 1 && !listState(root).canIndent)\n return;\n preserveRange(root, () => {\n if (direction === -1)\n lift(items);\n else {\n const list = items[0].parentElement!;\n const previous = items[0].previousElementSibling!;\n let nested = previous.lastElementChild;\n if (!compatible(nested, list)) {\n nested = list.cloneNode(false) as HTMLElement;\n previous.append(nested);\n }\n nested!.append(...items);\n }\n joinLists(root);\n });\n};\nexport const applyList = (root: HTMLElement, value: unknown): void => {\n if (value !== false && value !== 'bullet' && value !== 'ordered')\n throw new TypeError('Expected bullet, ordered or false.');\n const selected = topItems(selectedBlocks(root));\n if (selected.some((block) => block.localName === 'li' && !isList(block.parentElement)))\n throw new RangeError('A list item must belong to a list.');\n preserveRange(root, () => {\n for (const block of selected) {\n if (!value) {\n if (block.localName === 'li')\n lift([block as HTMLLIElement]);\n continue;\n }\n const tag = value === 'bullet' ? 'ul' : 'ol';\n if (block.localName === 'li') {\n if (block.parentElement!.localName === tag)\n continue;\n const list = document.createElement(tag);\n if (block.parentElement!.hasAttribute('style'))\n list.setAttribute('style', block.parentElement!.getAttribute('style')!);\n splitAround(block as HTMLLIElement, [list]);\n list.append(block);\n }\n else {\n const list = document.createElement(tag);\n const item = document.createElement('li');\n if (block.hasAttribute('style'))\n item.setAttribute('style', block.getAttribute('style')!);\n item.append(...block.childNodes);\n list.append(item);\n block.replaceWith(list);\n }\n }\n joinLists(root);\n });\n};\nconst empty = (item: HTMLElement) => !item.textContent?.trim() && !item.querySelector('img,hr,ul,ol');\nconst placeholder = (item: HTMLElement): void => {\n const own = ownContent(item);\n const meaningful = own.some((node) => node.textContent || (node instanceof Element && (node.matches('br,img,hr') || node.querySelector('br,img,hr'))));\n if (!meaningful) {\n if ([...item.children].some(isList))\n item.prepend(Object.assign(document.createElement('p'), { innerHTML: '<br>' }));\n else\n item.append(document.createElement('br'));\n }\n};\nconst atStart = (item: HTMLElement, range: Range) => {\n const prefix = range.cloneRange();\n prefix.selectNodeContents(item);\n prefix.setEnd(range.startContainer, range.startOffset);\n return !prefix.toString() && !prefix.cloneContents().querySelector('img,hr,br');\n};\nexport const handlesListInput = (root: HTMLElement, inputType: string): boolean => {\n const range = activeRange(root);\n if (!range)\n return false;\n const item = blockAt(root, range.startContainer);\n if (item?.localName !== 'li' || !isList(item.parentElement) || blockAt(root, range.endContainer) !== item)\n return false;\n return ['insertParagraph', 'insertLineBreak'].includes(inputType) || (inputType === 'deleteContentBackward' && range.collapsed && atStart(item, range));\n};\nexport const editListInput = (root: HTMLElement, inputType: string): void => {\n const range = activeRange(root)!;\n const item = blockAt(root, range.startContainer) as HTMLLIElement;\n if (inputType === 'insertParagraph') {\n if (empty(item)) {\n preserveRange(root, () => {\n const owner = item.parentElement!.parentElement; if (owner?.localName === 'li' && isList(owner.parentElement))\n lift([item]);\n else\n unwrapRoot(item, true);\n });\n joinLists(root);\n return;\n }\n range.deleteContents();\n const tail = range.cloneRange();\n tail.selectNodeContents(item);\n tail.setStart(range.startContainer, range.startOffset);\n const next = item.cloneNode(false) as HTMLLIElement;\n next.append(tail.extractContents());\n item.after(next);\n placeholder(item);\n placeholder(next);\n const walker = document.createTreeWalker(next, NodeFilter.SHOW_TEXT);\n let first: Node | null;\n do {\n first = walker.nextNode();\n } while (first && (!first.textContent || first.parentElement?.closest('li') !== next));\n if (first) {\n const caret = document.createRange();\n caret.setStart(first, 0);\n caret.collapse(true);\n const selection = document.getSelection();\n selection?.removeAllRanges();\n selection?.addRange(caret);\n }\n else\n placeCaret(next.querySelector<HTMLElement>('p,h1,h2,h3,h4,h5,h6,pre') ?? next);\n }\n else if (inputType === 'insertLineBreak') {\n range.deleteContents();\n const br = document.createElement('br');\n range.insertNode(br);\n if (!br.nextSibling)\n br.after(document.createElement('br'));\n range.setStartAfter(br);\n range.collapse(true);\n const selection = document.getSelection();\n selection?.removeAllRanges();\n selection?.addRange(range);\n }\n else {\n const previous = item.previousElementSibling as HTMLLIElement | null;\n if (previous && previous.localName !== 'li')\n return;\n if (!previous) {\n preserveRange(root, () => lift([item]));\n joinLists(root);\n return;\n }\n if (!ownContent(previous).some((node) => node.textContent || (node instanceof Element && (node.localName === 'img' || node.querySelector('img'))))) {\n for (const br of [...previous.querySelectorAll('br')])\n if (br.closest('li') === previous)\n br.remove();\n }\n const marker = document.createComment('mw-join');\n const previousContent = ownContent(previous);\n const last = previousContent.at(-1);\n const target = last instanceof HTMLElement && /^(p|h[1-6]|blockquote|pre)$/.test(last.localName) ? last : previous;\n if (target === previous)\n previous.insertBefore(marker, [...previous.children].find(isList) ?? null);\n else\n target.append(marker);\n const content = ownContent(item);\n if (content[0] instanceof HTMLElement && /^(p|h[1-6])$/.test(content[0].localName))\n content.splice(0, 1, ...content[0].childNodes);\n marker.after(...content);\n for (const nested of [...item.children].filter(isList))\n previous.append(nested);\n item.remove();\n joinLists(root);\n const caret = document.createRange();\n caret.setStartBefore(marker);\n caret.collapse(true);\n marker.remove();\n const selection = document.getSelection();\n selection?.removeAllRanges();\n selection?.addRange(caret);\n }\n};\n", "import { activeRange, placeCaret } from '../selection/index.js';\n\nconst blockTags = new Set(['p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6']);\nconst inlineTags = new Set(['strong', 'em', 'u', 's', 'sub', 'sup', 'a', 'span', 'code', 'br']);\nconst inlineTree = (element: Element): boolean => [...element.childNodes].every((node) => node.nodeType === 3 || (node instanceof HTMLElement && inlineTags.has(node.localName) && inlineTree(node)));\nconst parentOf = (node: Node): Element | null => node.nodeType === 1 ? node as Element : node.parentElement;\nconst editableBlock = (root: HTMLElement, node: Node): HTMLElement | undefined => {\n const block = parentOf(node)?.closest<HTMLElement>('p,h1,h2,h3,h4,h5,h6');\n if (!(block instanceof HTMLElement) || block.namespaceURI !== 'http://www.w3.org/1999/xhtml' || !root.contains(block) || block.closest('li,figure,pre') || !inlineTree(block)) return;\n const parent = block.parentElement;\n if (parent !== root && !['blockquote', 'td', 'th'].includes(parent?.localName ?? '')) return;\n return block;\n};\nconst hasContent = (fragment: DocumentFragment): boolean => Boolean(fragment.textContent || fragment.querySelector('br'));\nconst selectedBlock = (root: HTMLElement): HTMLElement | undefined => {\n const range = activeRange(root);\n if (!range) return;\n const block = editableBlock(root, range.startContainer);\n return block && editableBlock(root, range.endContainer) === block ? block : undefined;\n};\nconst atEdge = (block: HTMLElement, range: Range, end: boolean): boolean => {\n if (!block.textContent && block.querySelectorAll('br').length <= 1) return true;\n const remainder = block.ownerDocument.createRange();\n remainder.selectNodeContents(block);\n if (end) remainder.setStart(range.endContainer, range.endOffset);\n else remainder.setEnd(range.startContainer, range.startOffset);\n // An actual line break is content even though Range.toString omits it.\n const fragment = remainder.cloneContents();\n return !hasContent(fragment);\n};\nconst siblingBlock = (root: HTMLElement, block: HTMLElement, forward: boolean): HTMLElement | undefined => {\n const sibling = forward ? block.nextSibling : block.previousSibling;\n return sibling instanceof HTMLElement && blockTags.has(sibling.localName) && editableBlock(root, sibling) === sibling ? sibling : undefined;\n};\n\nexport const handlesBlockInput = (root: HTMLElement, inputType: string): boolean => {\n const block = selectedBlock(root);\n const range = activeRange(root);\n if (!block || !range) return false;\n if (inputType === 'insertParagraph' || inputType === 'insertLineBreak') return true;\n if (!range.collapsed) return false;\n if (inputType === 'deleteContentBackward') return atEdge(block, range, false);\n if (inputType === 'deleteContentForward') return atEdge(block, range, true);\n return false;\n};\n\n/** Called inside the editor's existing transaction after handlesBlockInput succeeds. */\nexport const editBlockInput = (root: HTMLElement, inputType: string): void => {\n const block = selectedBlock(root);\n const range = activeRange(root);\n if (!block || !range || !handlesBlockInput(root, inputType)) return;\n const document = root.ownerDocument;\n if (inputType === 'insertParagraph') {\n range.deleteContents();\n const tailRange = document.createRange();\n tailRange.selectNodeContents(block);\n tailRange.setStart(range.startContainer, range.startOffset);\n const tail = tailRange.extractContents();\n const emptyHeading = block.localName !== 'p' && !block.textContent && !tail.textContent && block.querySelectorAll('br').length + tail.querySelectorAll('br').length <= 1;\n const headingEnd = block.localName !== 'p' && (!hasContent(tail) || emptyHeading);\n if (emptyHeading) {\n const paragraph = document.createElement('p');\n for (const attribute of block.attributes) paragraph.setAttribute(attribute.name, attribute.value);\n paragraph.append(document.createElement('br'));\n block.replaceWith(paragraph);\n placeCaret(paragraph);\n return;\n }\n const next = headingEnd ? document.createElement('p') : block.cloneNode(false) as HTMLElement;\n if (headingEnd) {\n for (const attribute of block.attributes) next.setAttribute(attribute.name, attribute.value);\n }\n next.append(tail);\n if (!next.textContent && !next.querySelector('br')) next.replaceChildren(document.createElement('br'));\n if (!block.textContent && !block.querySelector('br')) block.replaceChildren(document.createElement('br'));\n block.after(next);\n placeCaret(next);\n return;\n }\n if (inputType === 'insertLineBreak') {\n range.deleteContents();\n if (!block.textContent && block.querySelectorAll('br').length <= 1) {\n block.replaceChildren();\n range.selectNodeContents(block);\n range.collapse(true);\n }\n const terminal = atEdge(block, range, true);\n const lineBreak = document.createElement('br');\n range.insertNode(lineBreak);\n if (terminal) lineBreak.after(document.createElement('br'));\n const caret = document.createRange();\n caret.setStartAfter(lineBreak);\n caret.collapse(true);\n const selection = document.getSelection();\n selection?.removeAllRanges();\n selection?.addRange(caret);\n return;\n }\n const forward = inputType === 'deleteContentForward';\n const sibling = siblingBlock(root, block, forward);\n if (!sibling) return;\n const left = forward ? block : sibling;\n const right = forward ? sibling : block;\n if (!left.textContent && left.childNodes.length === 1 && left.firstChild instanceof HTMLBRElement) left.replaceChildren();\n if (!right.textContent && right.childNodes.length === 1 && right.firstChild instanceof HTMLBRElement) right.replaceChildren();\n const join = document.createRange();\n join.selectNodeContents(left);\n join.collapse(false);\n left.append(...right.childNodes);\n right.remove();\n if (!left.childNodes.length) left.append(document.createElement('br'));\n left.normalize();\n const selection = document.getSelection();\n selection?.removeAllRanges();\n selection?.addRange(join);\n};\n", "import type { LinkFormat, Attributes, Operation, Piece } from './inline-attributes.types.js';\nexport type { LinkFormat } from './inline-attributes.types.js';\nimport { validateDocument } from '../document/index.js';\nimport type { DocumentNode, EditorDocument, ElementNode } from '../document/index.js';\nexport const inlineStyles: Record<string, string> = { color: 'color', background: 'background-color' };\nconst blocks = new Set(['p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'blockquote', 'pre', 'ul', 'ol', 'li', 'table', 'thead', 'tbody', 'tfoot', 'tr', 'td', 'th', 'caption', 'colgroup', 'figure', 'figcaption']);\nconst checkedAttributes = (tag: 'span' | 'a', attributes: Attributes): Attributes => (validateDocument({ version: 1, children: [{ type: 'element', tag, attributes, children: [] }] }).children[0] as ElementNode).attributes;\nexport const normalizeInlineStyle = (name: string, value: unknown): string | false => {\n if (value === false)\n return false;\n if (typeof value !== 'string' || !value.trim() || value.length > 128 || /[;{}]/.test(value))\n throw new TypeError('Expected a CSS color or false.');\n const property = inlineStyles[name];\n const attrs = checkedAttributes('span', { style: `${property}: ${value}` });\n const probe = document.createElement('span');\n probe.setAttribute('style', attrs.style ?? '');\n const color = probe.style.getPropertyValue(property);\n if (!color)\n throw new TypeError('Unsupported or invalid CSS color.');\n return color;\n};\nexport const normalizeLink = (value: unknown): {\n attributes: Attributes;\n text?: string;\n} | false => {\n if (value === false)\n return false;\n const input = typeof value === 'string' ? { href: value } : value;\n if (!input || typeof input !== 'object' || Array.isArray(input) || !('href' in input) || typeof input.href !== 'string')\n throw new TypeError('Expected a link URL, LinkFormat or false.');\n const link = input as Record<string, unknown>;\n const attributes: Attributes = { href: input.href };\n if (link.title !== undefined) {\n if (typeof link.title !== 'string' || link.title.length > 1024)\n throw new TypeError('Link title must be a string up to 1024 characters.');\n attributes.title = link.title;\n }\n if (link.target !== undefined) {\n if (link.target !== '_self' && link.target !== '_blank')\n throw new TypeError('Link target must be _self or _blank.');\n attributes.target = link.target;\n }\n if (link.text !== undefined && (typeof link.text !== 'string' || !link.text.length || link.text.length > 20000))\n throw new TypeError('New link text must contain 1\u201320000 characters.');\n const clean = checkedAttributes('a', attributes);\n if (!clean.href)\n throw new TypeError('Unsupported or unsafe link URL.');\n return { attributes: clean, ...(typeof link.text === 'string' ? { text: link.text } : {}) };\n};\nexport const mergeLinkAttributes = (previous: Attributes, patch: Attributes): Attributes => {\n const attrs = { ...previous, ...patch };\n if (!attrs.title)\n delete attrs.title;\n if (patch.target === '_self')\n delete attrs.rel;\n return checkedAttributes('a', attrs);\n};\nconst equalAttributes = (a?: Attributes, b?: Attributes) => JSON.stringify(Object.entries(a ?? {}).sort()) === JSON.stringify(Object.entries(b ?? {}).sort());\nconst withoutProperty = (attributes: Attributes, property: string): Attributes => {\n const attrs = { ...attributes };\n const style = (attrs.style ?? '').split(';').map((part) => part.trim()).filter((part) => part && part.slice(0, part.indexOf(':')).trim() !== property).join('; ');\n if (style)\n attrs.style = style;\n else\n delete attrs.style;\n return attrs;\n};\nconst groupPieces = (pieces: Piece[]): {\n pieces: Piece[];\n selected: boolean;\n link?: Attributes;\n}[] => {\n const result: {\n pieces: Piece[];\n selected: boolean;\n link?: Attributes;\n }[] = [];\n for (const piece of pieces) {\n const last = result.at(-1);\n if (last && last.selected === piece.selected && equalAttributes(last.link, piece.link))\n last.pieces.push(piece);\n else\n result.push({ pieces: [piece], selected: piece.selected, link: piece.link });\n }\n return result;\n};\nconst compact = (nodes: DocumentNode[]): DocumentNode[] => {\n const result: DocumentNode[] = [];\n for (const node of nodes) {\n const next = node.type === 'element' ? { ...node, children: compact(node.children) } : node;\n const previous = result.at(-1);\n if (next.type === 'text' && previous?.type === 'text')\n previous.text += next.text;\n else if (next.type === 'element' && previous?.type === 'element' && !blocks.has(next.tag) && !['img', 'br', 'hr'].includes(next.tag) && previous.tag === next.tag && equalAttributes(previous.attributes, next.attributes))\n previous.children = compact([...previous.children, ...next.children]);\n else\n result.push(next);\n }\n return result;\n};\nexport const transformInlineAttributes = (document: EditorDocument, from: number, to: number, operation: Operation): EditorDocument => {\n let position = 0;\n const wrap = (pieces: Piece[]): DocumentNode[] => groupPieces(pieces).flatMap((group) => {\n const children = group.pieces.map((piece) => piece.node);\n if (operation.kind === 'style')\n return group.selected && operation.value !== false ? [{ type: 'element', tag: 'span', attributes: { style: `${operation.property}: ${operation.value}` }, children } as ElementNode] : children;\n const attrs = group.selected ? operation.attributes === false ? undefined : mergeLinkAttributes(group.link ?? {}, operation.attributes) : group.link;\n return attrs ? [{ type: 'element', tag: 'a', attributes: attrs, children } as ElementNode] : children;\n });\n const visit = (node: DocumentNode, inheritedLink?: Attributes): Piece[] => {\n if (node.type === 'text') {\n const start = position;\n position += node.text.length;\n const left = Math.max(0, Math.min(node.text.length, from - start));\n const right = Math.max(left, Math.min(node.text.length, to - start));\n return [[0, left, false], [left, right, true], [right, node.text.length, false]].flatMap(([begin, end, selected]) => {\n const text = node.text.slice(begin as number, end as number);\n return text ? [{ node: { type: 'text', text } as DocumentNode, selected: Boolean(selected), link: inheritedLink }] : [];\n });\n }\n const link = operation.kind === 'link' && node.tag === 'a' ? node.attributes : inheritedLink;\n if (!node.children.length)\n return [{ node, selected: position >= from && position < to, link }];\n const children = node.children.flatMap((child) => visit(child, link));\n if (operation.kind === 'link' && node.tag === 'a')\n return children;\n if (blocks.has(node.tag))\n return [{ node: { ...node, children: wrap(children) }, selected: false }];\n return groupPieces(children).flatMap<Piece>((group) => {\n const attrs = operation.kind === 'style' && group.selected ? withoutProperty(node.attributes, operation.property) : node.attributes;\n const content = group.pieces.map((piece) => piece.node);\n if (node.tag === 'span' && !Object.keys(attrs).length)\n return group.pieces;\n return [{ node: { ...node, attributes: attrs, children: content }, selected: group.selected, link: group.link }];\n });\n };\n return { version: 1, children: compact(wrap(document.children.flatMap((node) => visit(node)))) };\n};\n", "import { documentHTML, parseHTML } from '../document/index.js';\nimport { normalizeLink, mergeLinkAttributes, transformInlineAttributes } from './inline-attributes.js';\nimport { activeRange, readTextSelection, selectText, preserveRange } from '../selection/index.js';\nexport const applyLink = (root: HTMLElement, value: unknown): void => {\n const link = normalizeLink(value);\n const range = activeRange(root);\n if (!range)\n return;\n const selection = readTextSelection(root)!;\n const element = range.startContainer.nodeType === 1 ? range.startContainer as Element : range.startContainer.parentElement;\n const anchor = element?.closest('a');\n const existing = anchor && root.contains(anchor) ? anchor : undefined;\n if (link && link.text !== undefined && (!range.collapsed || existing))\n throw new TypeError('Link text is only supported for insertion at a caret outside links.');\n if (!range.collapsed) {\n root.innerHTML = documentHTML(transformInlineAttributes(parseHTML(root.innerHTML), selection.index, selection.index + selection.length, { kind: 'link', attributes: link && link.attributes }));\n selectText(root, selection.index, selection.length);\n return;\n }\n if (existing) {\n const attrs = link && mergeLinkAttributes(Object.fromEntries([...existing.attributes].map((attr) => [attr.name, attr.value])), link.attributes);\n preserveRange(root, () => {\n if (!attrs)\n existing.replaceWith(...existing.childNodes);\n else {\n for (const attr of [...existing.attributes])\n existing.removeAttribute(attr.name);\n for (const [key, val] of Object.entries(attrs))\n existing.setAttribute(key, val);\n }\n });\n return;\n }\n if (!link || link.text === undefined)\n return;\n const created = root.ownerDocument.createElement('a');\n for (const [key, val] of Object.entries(link.attributes))\n created.setAttribute(key, val);\n created.textContent = link.text;\n const parent = element?.closest('p,li,h1,h2,h3,h4,h5,h6,blockquote,pre,td,th');\n if (parent?.childNodes.length === 1 && parent.firstChild instanceof HTMLBRElement) {\n parent.firstChild.remove();\n range.setStart(parent, 0);\n }\n range.insertNode(created);\n const tail = root.ownerDocument.createTextNode('');\n created.after(tail);\n range.setStart(tail, 0);\n range.collapse(true);\n const native = root.ownerDocument.getSelection();\n native?.removeAllRanges();\n native?.addRange(range);\n};\n", "import type { DocumentNode, DocumentTag, EditorDocument, ElementNode } from '../document/index.js';\nimport type { InlineGroup, Piece } from './types.js';\n\nconst blockTags = new Set(['p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'blockquote', 'pre', 'ul', 'ol', 'li', 'table', 'thead', 'tbody', 'tfoot', 'tr', 'td', 'th', 'caption', 'colgroup', 'figure', 'figcaption']);\n\nconst textLength = (node: DocumentNode): number => node.type === 'text'\n ? node.text.length\n : node.children.reduce((length, child) => length + textLength(child), 0);\n\nexport const inlineDocument = (value: EditorDocument, from: number, to: number, tag: DocumentTag, enabled: boolean): EditorDocument => {\n let position = 0;\n const visit = (node: DocumentNode): Piece[] => {\n if (node.type === 'text') {\n const start = position;\n position += node.text.length;\n const left = Math.max(0, Math.min(node.text.length, from - start));\n const right = Math.max(left, Math.min(node.text.length, to - start));\n return [[0, left, false], [left, right, true], [right, node.text.length, false]].flatMap(([begin, end, selected]) => {\n const text = node.text.slice(begin as number, end as number);\n if (!text)\n return [];\n const leaf: DocumentNode = { type: 'text', text };\n return [{ node: selected && enabled ? { type: 'element', tag, attributes: {}, children: [leaf] } as ElementNode : leaf, selected: Boolean(selected) }];\n });\n }\n // Descendants already inherit this mark. Keep their validated wrapper shape unchanged.\n if (enabled && node.tag === tag) {\n position += textLength(node);\n return [{ node, selected: false }];\n }\n const children = node.children.flatMap(visit);\n if (blockTags.has(node.tag))\n return [{ node: { ...node, children: children.map((piece) => piece.node) }, selected: false }];\n if (!children.length)\n return [{ node, selected: false }];\n const groups: InlineGroup[] = [];\n for (const piece of children) {\n const last = groups.at(-1);\n if (last?.selected === piece.selected)\n last.children.push(piece.node);\n else\n groups.push({ selected: piece.selected, children: [piece.node] });\n }\n return groups.flatMap<Piece>((group) => node.tag === tag && !enabled && group.selected\n ? group.children.map((child) => ({ node: child, selected: true }))\n : [{ node: { ...node, children: group.children }, selected: group.selected }]);\n };\n return { version: 1, children: value.children.flatMap(visit).map((piece) => piece.node) };\n};\n", "import type { DocumentTag } from '../document/index.js';\nimport { parseHTML, renderDocument } from '../document/index.js';\nimport { selectText } from '../selection/index.js';\nimport { inlineDocument } from './inline-document.js';\n\nconst leaves = 'p,h1,h2,h3,h4,h5,h6';\nconst inlineTags = new Set(['strong', 'em', 'u', 's', 'sub', 'sup', 'a', 'span', 'code']);\nconst structuralAncestors = new Set(['blockquote', 'ul', 'ol', 'li', 'table', 'thead', 'tbody', 'tfoot', 'tr', 'td', 'th']);\nconst elementAt = (node: Node): Element | null => node.nodeType === 1 ? node as Element : node.parentElement;\nconst isInlineTree = (parent: Element): boolean => {\n for (const node of parent.childNodes) {\n if (node.nodeType === 3) continue;\n if (node.nodeType !== 1) return false;\n const element = node as Element;\n if (element.namespaceURI !== 'http://www.w3.org/1999/xhtml' || !inlineTags.has(element.localName) || !isInlineTree(element)) return false;\n }\n return true;\n};\n\n/** Transform one schema-validated leaf while keeping unrelated editor DOM connected. */\nexport const applyLocalInline = (root: HTMLElement, range: Range, tag: DocumentTag, enabled: boolean): boolean => {\n const block = elementAt(range.startContainer)?.closest<HTMLElement>(leaves);\n if (!block || !root.contains(block) || block.namespaceURI !== 'http://www.w3.org/1999/xhtml') return false;\n if (elementAt(range.endContainer)?.closest(leaves) !== block || !isInlineTree(block)) return false;\n for (let parent = block.parentElement; parent && parent !== root; parent = parent.parentElement) {\n if (parent.namespaceURI !== 'http://www.w3.org/1999/xhtml' || !structuralAncestors.has(parent.localName)) return false;\n }\n\n const prefix = root.ownerDocument.createRange();\n prefix.selectNodeContents(block);\n prefix.setEnd(range.startContainer, range.startOffset);\n const from = prefix.toString().length;\n const length = range.toString().length;\n if (!length || from + length > (block.textContent?.length ?? 0)) return false;\n const native = root.ownerDocument.getSelection();\n const backward = native?.anchorNode === range.endContainer && native.anchorOffset === range.endOffset;\n const content = inlineDocument(parseHTML(block.outerHTML), from, from + length, tag, enabled);\n const fragment = renderDocument(content);\n const replacement = fragment.firstElementChild;\n if (fragment.childNodes.length !== 1 || !(replacement instanceof HTMLElement) || replacement.localName !== block.localName) return false;\n\n // HTML history replay merges adjacent text nodes; capture the same local node shape.\n replacement.normalize();\n if (replacement.outerHTML === block.outerHTML) return true;\n\n block.replaceWith(fragment);\n selectText(replacement, from, length);\n root.focus({ preventScroll: true });\n if (backward && native?.rangeCount) {\n const selected = native.getRangeAt(0);\n native.setBaseAndExtent(selected.endContainer, selected.endOffset, selected.startContainer, selected.startOffset);\n }\n return true;\n};\n", "import type { DocumentTag } from '../document/index.js';\nimport { documentHTML, parseHTML } from '../document/index.js';\nimport { activeRange, readTextSelection, selectText, preserveRange } from '../selection/index.js';\nimport { inlineStyles, normalizeInlineStyle, transformInlineAttributes } from './inline-attributes.js';\nimport { applyLink } from './links.js';\nimport { inlineDocument } from './inline-document.js';\nimport { applyLocalInline } from './local-inline.js';\nimport { applyList, indentList, listState, selectedBlocks } from '../lists/index.js';\nexport const inlineFormats: Record<string, DocumentTag> = { bold: 'strong', italic: 'em', underline: 'u', strike: 's', code: 'code', subscript: 'sub', superscript: 'sup' };\n\nconst closestElement = (node: Node): Element | null => { return node.nodeType === 1 ? node as Element : node.parentElement; };\nconst formatsAt = (root: HTMLElement, node: Node): Record<string, unknown> => {\n let element = closestElement(node);\n const formats: Record<string, unknown> = {};\n while (element && element !== root) {\n for (const [name, tag] of Object.entries(inlineFormats))\n if (element.localName === tag)\n formats[name] = true;\n if (/^h[1-6]$/.test(element.localName) && formats.header === undefined)\n formats.header = Number(element.localName[1]);\n if (element.localName === 'blockquote')\n formats.blockquote = true;\n if (element.localName === 'pre')\n formats['code-block'] = true;\n if ((element.localName === 'ul' || element.localName === 'ol') && formats.list === undefined)\n formats.list = element.localName === 'ul' ? 'bullet' : 'ordered';\n if (element.localName === 'a' && formats.link === undefined) {\n formats.link = element.getAttribute('href');\n formats.linkTitle = element.getAttribute('title') ?? '';\n formats.linkTarget = element.getAttribute('target') ?? '_self';\n }\n if (element instanceof HTMLElement)\n for (const [name, property] of Object.entries(inlineStyles))\n if (formats[name] === undefined && element.style.getPropertyValue(property))\n formats[name] = element.style.getPropertyValue(property);\n if (element instanceof HTMLElement && element.style.textAlign && formats.align === undefined)\n formats.align = element.style.textAlign;\n element = element.parentElement;\n }\n return formats;\n};\nexport const readFormats = (root: HTMLElement): Record<string, unknown> => {\n const range = activeRange(root);\n if (!range)\n return {};\n let formats = formatsAt(root, range.startContainer);\n const mixed = new Set<string>();\n if (!range.collapsed) {\n const { index, length } = readTextSelection(root)!;\n const walker = root.ownerDocument.createTreeWalker(root, NodeFilter.SHOW_TEXT);\n let position = 0;\n let node: Node | null;\n const samples: Record<string, unknown>[] = [];\n while ((node = walker.nextNode())) {\n const end = position + node.textContent!.length;\n if (end > index && position < index + length)\n samples.push(formatsAt(root, node));\n position = end;\n }\n if (samples.length)\n formats = samples[0];\n const keys = [...Object.keys(inlineFormats), 'header', 'list', 'blockquote', 'code-block', 'link', 'linkTitle', 'linkTarget', 'color', 'background', 'align'];\n const normalized = (sample: Record<string, unknown>, key: string) => sample[key] ?? (key === 'align' ? 'left' : key === 'header' ? 0 : false);\n for (const key of keys)\n if (samples.some((sample) => normalized(sample, key) !== normalized(samples[0], key)))\n mixed.add(key);\n }\n return { ...formats, align: formats.align ?? 'left', mixed: [...mixed], ...listState(root) };\n};\nexport const applyFormat = (root: HTMLElement, name: string, value: unknown): void => {\n const range = activeRange(root);\n if (!range)\n return;\n const tag = inlineFormats[name];\n if (tag && !range.collapsed && applyLocalInline(root, range, tag, Boolean(value)))\n return;\n const selection = readTextSelection(root)!;\n if (name === 'list') {\n applyList(root, value);\n return;\n }\n if (name === 'indent') {\n indentList(root, value);\n return;\n }\n if (name === 'clear') {\n if (value !== true || !selection.length)\n return;\n let content = parseHTML(root.innerHTML);\n for (const tag of [...Object.values(inlineFormats), 'a', 'span'] as DocumentTag[])\n content = inlineDocument(content, selection.index, selection.index + selection.length, tag, false);\n root.innerHTML = documentHTML(content);\n selectText(root, selection.index, selection.length);\n return;\n }\n if (tag) {\n if (range.collapsed)\n return;\n root.innerHTML = documentHTML(inlineDocument(parseHTML(root.innerHTML), selection.index, selection.index + selection.length, tag, Boolean(value)));\n selectText(root, selection.index, selection.length);\n return;\n }\n if (name === 'link') {\n applyLink(root, value);\n return;\n }\n if (Object.hasOwn(inlineStyles, name)) {\n const color = normalizeInlineStyle(name, value);\n if (!selection.length)\n return;\n root.innerHTML = documentHTML(transformInlineAttributes(parseHTML(root.innerHTML), selection.index, selection.index + selection.length, { kind: 'style', property: inlineStyles[name], value: color }));\n selectText(root, selection.index, selection.length);\n return;\n }\n let blocks = selectedBlocks(root, range, false);\n if (!blocks.length) {\n const paragraph = document.createElement('p');\n paragraph.append(range.extractContents());\n if (!paragraph.childNodes.length)\n paragraph.append(document.createElement('br'));\n range.insertNode(paragraph);\n blocks = [paragraph];\n }\n preserveRange(root, () => {\n for (const block of blocks) {\n if (name === 'align' && ['left', 'center', 'right', 'justify', false].includes(value as string | false)) {\n block.style.textAlign = value ? String(value) : '';\n continue;\n }\n const nextTag = name === 'header' ? (Number.isInteger(value) && Number(value) >= 1 && Number(value) <= 6 ? `h${value}` : 'p')\n : name === 'blockquote' ? (value ? 'blockquote' : 'p')\n : name === 'code-block' ? (value ? 'pre' : 'p') : undefined;\n if (nextTag) {\n const replacement = document.createElement(nextTag);\n if (block.localName === 'li') {\n const content = [...block.childNodes].filter((node) => !(node instanceof Element && /^(ul|ol|p|h[1-6]|pre|blockquote)$/.test(node.localName)));\n replacement.append(...content);\n block.prepend(replacement);\n }\n else {\n replacement.append(...block.childNodes);\n replacement.setAttribute('style', block.getAttribute('style') ?? '');\n block.replaceWith(replacement);\n }\n }\n }\n });\n};\n", "import type { EditorEventMap, EditorEvents, EventHub, PluginEvent, QueuedEvent } from './types.js';\nexport type { EditorEventMap, EditorEvents, PluginEvent } from './types.js';\nconst tokens = new WeakSet<object>();\nconst coreNames = new Set(['change', 'selectionchange', 'readonlychange', 'destroy']);\nexport const createPluginEvent = <T>(name: string): PluginEvent<T> => {\n if (typeof name !== 'string' || !name.trim() || name.length > 200) {\n throw new TypeError('Expected an event name with 1\u2013200 characters.');\n }\n const token = Object.freeze({ name }) as PluginEvent<T>;\n tokens.add(token);\n return token;\n};\nconst assertToken = (event: unknown): object => {\n if (!event || typeof event !== 'object' || !tokens.has(event)) {\n throw new TypeError('Expected a plugin event token. Core events cannot be emitted publicly.');\n }\n return event;\n};\nexport const createEventHub = (): EventHub => {\n const listeners = new Map<string | object, Map<(payload: unknown) => void, number>>();\n const queue: QueuedEvent[] = [];\n let registration = 0;\n let dispatching = false;\n let closing = false;\n const enqueue = (entry: QueuedEvent) => {\n if (closing && entry.key !== 'destroy')\n return;\n queue.push(entry);\n if (dispatching)\n return;\n dispatching = true;\n const failures: unknown[] = [];\n try {\n while (queue.length) {\n const next = queue.shift()!;\n if (closing && next.key !== 'destroy')\n continue;\n const bucket = listeners.get(next.key);\n for (const [listener, registered] of [...(bucket ?? [])]) {\n if ((closing && next.key !== 'destroy') || bucket?.get(listener) !== registered)\n continue;\n try {\n const payload = next.core && next.payload && typeof next.payload === 'object'\n ? { ...next.payload }\n : next.payload;\n listener(payload);\n }\n catch (error) {\n failures.push(error);\n }\n }\n if (next.key === 'destroy') {\n listeners.clear();\n queue.length = 0;\n }\n }\n }\n finally {\n dispatching = false;\n }\n if (failures.length)\n throw new AggregateError(failures, 'Editor event listeners failed.');\n };\n const on = (event: keyof EditorEventMap | PluginEvent<unknown>, listener: (payload: unknown) => void): (() => void) => {\n if (closing)\n throw new Error('Editor events have been destroyed.');\n if (typeof listener !== 'function')\n throw new TypeError('Expected an event listener.');\n const key = typeof event === 'string' && coreNames.has(event) ? event : assertToken(event);\n let bucket = listeners.get(key);\n if (!bucket) {\n bucket = new Map();\n listeners.set(key, bucket);\n }\n if (!bucket.has(listener))\n bucket.set(listener, ++registration);\n const registered = bucket.get(listener);\n return () => {\n if (bucket!.get(listener) !== registered)\n return;\n bucket!.delete(listener);\n if (!bucket!.size && listeners.get(key) === bucket)\n listeners.delete(key);\n };\n };\n const events: EditorEvents = {\n on: on as EditorEvents['on'],\n emit: (event, payload) => {\n if (closing)\n throw new Error('Editor events have been destroyed.');\n enqueue({ key: assertToken(event), payload, core: false });\n },\n };\n return {\n events,\n notify: (event, payload) => enqueue({ key: event, payload, core: true }),\n destroy: () => {\n if (closing)\n return;\n closing = true;\n queue.length = 0;\n enqueue({ key: 'destroy', payload: undefined, core: true });\n },\n };\n};\n", "import { sanitizeHTML } from '../document/index.js';\n\n/** Reuse only a successfully validated string for the exact current serialized DOM. */\nexport const createHTMLSnapshots = (surface: HTMLElement) => {\n let previousInput: string | undefined;\n let previousHTML = '';\n\n const read = (): string => {\n const input = surface.innerHTML;\n if (input === previousInput)\n return previousHTML;\n\n // Keep the last successful pair intact when validation rejects a new input.\n const html = sanitizeHTML(input);\n previousInput = input;\n previousHTML = html;\n return html;\n };\n\n const clear = (): void => {\n previousInput = undefined;\n previousHTML = '';\n };\n\n return { read, clear };\n};\n", "import { documentHTML, parseHTML, renderDocument, validateDocument } from '../document/index.js';\nimport { activeRange, bookmark, placeCaret, readTextSelection, restoreBookmark, selectText } from '../selection/index.js';\nimport type { SelectionBookmark } from '../selection/index.js';\nimport { editListInput, handlesListInput, indentList, listState, selectedBlocks } from '../lists/index.js';\nimport { editBlockInput, handlesBlockInput } from '../input/index.js';\nimport { applyFormat, inlineFormats, readFormats } from '../formatting/index.js';\nimport { inlineStyles, normalizeInlineStyle } from '../formatting/inline-attributes.js';\nimport { createEventHub } from '../events/index.js';\nimport type { EditorEvents } from '../events/types.js';\nimport type { Editor, EditorChange, EditorOptions, Snapshot } from './types.js';\nimport { createHTMLSnapshots } from './html-snapshots.js';\nconst isCompositionInput = (event: InputEvent): boolean => event.isComposing || event.inputType === 'insertCompositionText' || event.inputType === 'insertFromComposition' || event.inputType === 'deleteCompositionText';\nconst ensureDocument = (root: HTMLElement): boolean => {\n let normalized = false;\n if (!root.childNodes.length) {\n root.innerHTML = '<p><br></p>';\n normalized = true;\n }\n // Native input can create loose inline nodes; wrap them in paragraphs without replacing text nodes.\n let paragraph: HTMLParagraphElement | undefined;\n for (const node of [...root.childNodes]) {\n const inline = node.nodeType === 3 || (node.nodeType === 1 && /^(strong|em|u|s|a|span|code|img|br|sub|sup)$/.test((node as Element).localName));\n if (inline) {\n if (!paragraph) {\n paragraph = document.createElement('p');\n root.insertBefore(paragraph, node);\n }\n paragraph.append(node);\n normalized = true;\n }\n else\n paragraph = undefined;\n }\n if (['table', 'figure'].includes(root.lastElementChild?.localName ?? ''))\n root.append(Object.assign(document.createElement('p'), { innerHTML: '<br>' }));\n root.dataset.empty = String(!root.textContent && !root.querySelector('table,img,hr'));\n return normalized;\n};\nconst insertFragment = (root: HTMLElement, html: string): void => {\n const range = activeRange(root);\n if (!range)\n return;\n const fragment = renderDocument(parseHTML(html));\n if (!fragment.childNodes.length)\n return;\n range.deleteContents();\n const startElement = range.startContainer.nodeType === 1 ? range.startContainer as Element : range.startContainer.parentElement;\n const block = startElement?.closest('p,h1,h2,h3,h4,h5,h6,li,blockquote,pre');\n if (fragment.childNodes.length === 1 && fragment.firstChild instanceof HTMLParagraphElement && block) {\n const paragraph = fragment.firstChild;\n fragment.replaceChildren(...paragraph.childNodes);\n }\n const hasBlocks = [...fragment.childNodes].some((node) => node instanceof HTMLElement && /^(p|h[1-6]|ul|ol|table|figure|blockquote|pre)$/.test(node.localName));\n const last = fragment.lastChild!;\n if (hasBlocks && block && root.contains(block)) {\n const tailRange = document.createRange();\n tailRange.selectNodeContents(block);\n tailRange.setStart(range.startContainer, range.startOffset);\n const tail = block.cloneNode(false) as HTMLElement;\n tail.append(tailRange.extractContents());\n block.after(fragment);\n if (tail.textContent || tail.querySelector('img,br'))\n last.after(tail);\n if (!block.textContent && !block.querySelector('img'))\n block.remove();\n }\n else\n range.insertNode(fragment);\n const next = document.createRange();\n next.setStartAfter(last);\n next.collapse(true);\n const selection = document.getSelection();\n selection?.removeAllRanges();\n selection?.addRange(next);\n};\nexport const createEditor = (host: HTMLElement, options: EditorOptions = {}): Editor => {\n if (host.childNodes.length)\n throw new Error('Editor host must be empty. Pass initial HTML through value.');\n const plugins = options.plugins ?? [];\n if (new Set(plugins.map((plugin) => plugin.name)).size !== plugins.length)\n throw new Error('Duplicate editor plugin.');\n const limit = options.historyLimit ?? 100;\n if (!Number.isInteger(limit) || limit < 1 || limit > 10000)\n throw new RangeError('historyLimit must be an integer from 1 to 10000.');\n const initialDocument = parseHTML(options.value ?? '');\n const container = document.createElement('div');\n container.className = 'mw-editor';\n const surface = document.createElement('div');\n surface.className = 'mw-content';\n surface.setAttribute('role', 'textbox');\n surface.setAttribute('aria-multiline', 'true');\n surface.setAttribute('aria-label', options.label ?? '\u0422\u0435\u043A\u0441\u0442\u043E\u0432\u044B\u0439 \u0440\u0435\u0434\u0430\u043A\u0442\u043E\u0440');\n surface.dataset.placeholder = options.placeholder ?? '\u041D\u0430\u0447\u043D\u0438\u0442\u0435 \u043F\u0438\u0441\u0430\u0442\u044C\u2026';\n container.append(surface);\n host.append(container);\n surface.append(renderDocument(initialDocument));\n ensureDocument(surface);\n let destroyed = false;\n let readOnly = options.readOnly ?? false;\n let composing = false;\n let compositionStart: Snapshot | undefined;\n let canceledComposition = false;\n let compositionTail: Snapshot | undefined;\n let compositionUndoRecorded = false;\n let pendingInput: Snapshot | undefined;\n let lastInputTime = 0;\n let lastInputType = '';\n let typingOverrides: Record<string, string | boolean> = {};\n let typingOffset: number | undefined;\n const clearTyping = () => { typingOverrides = {}; typingOffset = undefined; };\n const typingAtCaret = () => { const selection = readTextSelection(surface); return selection?.length === 0 && selection.index === typingOffset; };\n const undoStack: Snapshot[] = [];\n const redoStack: Snapshot[] = [];\n const eventHub = createEventHub();\n let transactionDepth = 0;\n let transactionFailed = false;\n let transactionError: unknown;\n let pendingSelectionNotification = false;\n const pluginAPIs = new Map<string, unknown>();\n const disposers: (() => void)[] = [];\n if (options.onChange)\n eventHub.events.on('change', options.onChange);\n const assertActive = () => {\n if (destroyed)\n throw new Error('Editor has been destroyed.');\n };\n const rejectDuringTransaction = (operation: string) => {\n if (!transactionDepth)\n return;\n const error = new Error(`${operation} is unavailable inside a transaction.`);\n transactionFailed = true;\n transactionError = error;\n throw error;\n };\n const events: EditorEvents = {\n on: eventHub.events.on,\n emit: (event, payload) => {\n assertActive();\n rejectDuringTransaction('events.emit');\n eventHub.events.emit(event, payload);\n },\n };\n const htmlSnapshots = createHTMLSnapshots(surface);\n const capture = (): Snapshot => ({ html: htmlSnapshots.read(), selection: bookmark(surface), ...(typingOffset !== undefined && Object.keys(typingOverrides).length && typingAtCaret() ? { typing: { offset: typingOffset, formats: { ...typingOverrides } } } : {}) });\n const restoreTyping = (snapshot: Snapshot) => {\n clearTyping();\n const selection = readTextSelection(surface);\n if (snapshot.typing && selection?.length === 0 && selection.index === snapshot.typing.offset) {\n typingOffset = snapshot.typing.offset;\n typingOverrides = { ...snapshot.typing.formats };\n }\n };\n let current = capture();\n let lastSelection = current.selection;\n const clearCompositionTail = () => {\n compositionTail = undefined;\n compositionUndoRecorded = false;\n };\n const cancelComposition = (rollback: boolean) => {\n const before = compositionStart;\n canceledComposition = canceledComposition || composing || compositionTail !== undefined;\n composing = false;\n compositionStart = undefined;\n pendingInput = undefined;\n clearCompositionTail();\n if (rollback && before) {\n surface.innerHTML = before.html;\n ensureDocument(surface);\n restoreBookmark(surface, before.selection);\n restoreTyping(before);\n current = capture();\n lastSelection = current.selection;\n }\n };\n const restoreCurrentDOM = () => {\n surface.innerHTML = current.html;\n ensureDocument(surface);\n restoreBookmark(surface, current.selection);\n };\n const notifySelection = () => {\n if (destroyed)\n return;\n if (transactionDepth) {\n pendingSelectionNotification = true;\n return;\n }\n if (readTextSelection(surface) && !typingAtCaret())\n clearTyping();\n const saved = bookmark(surface);\n if (saved) {\n lastSelection = saved;\n current.selection = saved;\n }\n eventHub.notify('selectionchange', readTextSelection(surface));\n };\n const emit = (source: EditorChange['source']) => {\n const change: EditorChange = { html: editor.getHTML(), text: editor.getText(), source };\n const failures: unknown[] = [];\n try {\n eventHub.notify('change', change);\n }\n catch (error) {\n failures.push(error);\n }\n try {\n notifySelection();\n }\n catch (error) {\n failures.push(error);\n }\n if (failures.length)\n throw new AggregateError(failures, 'Editor change notification failed.');\n };\n const commitMutation = (before: Snapshot, inputType = ''): boolean => {\n const selection = readTextSelection(surface);\n if (ensureDocument(surface) && selection)\n selectText(surface, selection.index, selection.length);\n const after = capture();\n if (after.html === before.html) {\n current = after;\n return false;\n }\n const now = Date.now();\n const grouped = inputType === lastInputType && ['insertText', 'deleteContentBackward', 'deleteContentForward'].includes(inputType) && now - lastInputTime < 600 && before.selection && current.selection && JSON.stringify(before.selection) === JSON.stringify(current.selection);\n if (!grouped) {\n undoStack.push(before);\n if (undoStack.length > limit)\n undoStack.shift();\n }\n redoStack.length = 0;\n current = after;\n lastInputTime = inputType ? now : 0;\n lastInputType = inputType;\n return true;\n };\n const commit = (before: Snapshot, inputType = '') => {\n if (commitMutation(before, inputType))\n emit('user');\n };\n const restore = (snapshot: Snapshot) => {\n clearTyping();\n surface.innerHTML = snapshot.html;\n ensureDocument(surface);\n surface.focus({ preventScroll: true });\n restoreBookmark(surface, snapshot.selection);\n restoreTyping(snapshot);\n current = capture();\n lastSelection = current.selection;\n lastInputTime = 0;\n emit('user');\n };\n const runTransaction = (mutate: (surface: HTMLElement) => void, inputType = '') => {\n assertActive();\n if (readOnly || composing)\n return;\n clearCompositionTail();\n const invoke = () => {\n if (typeof mutate !== 'function' || mutate.constructor.name === 'AsyncFunction')\n throw new TypeError('Transactions require a synchronous callback.');\n const result: unknown = mutate(surface);\n if (result && (typeof result === 'object' || typeof result === 'function') && typeof (result as {\n then?: unknown;\n }).then === 'function') {\n if (result instanceof Promise)\n void result.catch(() => { });\n throw new TypeError('Transaction callbacks must not return a thenable.');\n }\n };\n if (transactionDepth) {\n transactionDepth++;\n try {\n invoke();\n }\n catch (error) {\n transactionFailed = true;\n transactionError = error;\n throw error;\n }\n finally {\n transactionDepth--;\n }\n return;\n }\n editor.focus();\n const before = capture();\n const previousUndo = [...undoStack];\n const previousRedo = [...redoStack];\n const previousInputTime = lastInputTime;\n const previousInputType = lastInputType;\n const previousPendingInput = pendingInput;\n const previousSelection = lastSelection;\n transactionDepth = 1;\n transactionFailed = false;\n transactionError = undefined;\n pendingSelectionNotification = false;\n let changed = false;\n try {\n invoke();\n if (transactionFailed)\n throw transactionError;\n changed = commitMutation(before, inputType);\n }\n catch (error) {\n surface.innerHTML = before.html;\n ensureDocument(surface);\n restoreBookmark(surface, before.selection);\n restoreTyping(before);\n current = capture();\n lastSelection = previousSelection;\n pendingInput = previousPendingInput;\n undoStack.splice(0, undoStack.length, ...previousUndo);\n redoStack.splice(0, redoStack.length, ...previousRedo);\n lastInputTime = previousInputTime;\n lastInputType = previousInputType;\n transactionDepth = 0;\n pendingSelectionNotification = false;\n throw error;\n }\n finally {\n transactionDepth = 0;\n }\n const selectionChanged = pendingSelectionNotification;\n pendingSelectionNotification = false;\n // Notifications are outside the rollback boundary: observers cannot undo a committed edit by throwing.\n if (changed)\n emit('user');\n else if (selectionChanged)\n notifySelection();\n };\n const editor: Editor = {\n element: container, surface, events,\n getHTML: () => { assertActive(); return htmlSnapshots.read(); },\n getText: () => { assertActive(); return surface.innerText; },\n getJSON: () => { assertActive(); return parseHTML(surface.innerHTML); },\n setHTML: (html) => {\n assertActive();\n rejectDuringTransaction('setHTML');\n const content = documentHTML(parseHTML(html));\n if (content === editor.getHTML())\n return;\n cancelComposition(false);\n clearTyping();\n surface.innerHTML = content;\n ensureDocument(surface);\n undoStack.length = 0;\n redoStack.length = 0;\n lastInputTime = 0;\n lastSelection = undefined;\n current = capture();\n emit('api');\n },\n setJSON: (value) => {\n assertActive();\n rejectDuringTransaction('setJSON');\n const validated = validateDocument(value);\n editor.setHTML(documentHTML(validated));\n },\n getSelection: () => { assertActive(); return readTextSelection(surface); },\n setSelection: (index, length = 0) => { assertActive(); selectText(surface, index, length); notifySelection(); },\n getFormats: () => { assertActive(); return { ...readFormats(surface), ...(typingAtCaret() ? typingOverrides : {}) }; },\n setReadOnly: (value) => {\n assertActive();\n rejectDuringTransaction('setReadOnly');\n const changed = readOnly !== value;\n if (changed && value)\n cancelComposition(true);\n readOnly = value;\n surface.contentEditable = String(!value);\n surface.setAttribute('aria-readonly', String(value));\n container.dataset.readonly = String(value);\n const failures: unknown[] = [];\n if (changed) {\n try {\n eventHub.notify('readonlychange', value);\n }\n catch (error) {\n failures.push(error);\n }\n }\n try {\n notifySelection();\n }\n catch (error) {\n failures.push(error);\n }\n if (failures.length)\n throw new AggregateError(failures, 'Editor state notification failed.');\n },\n isReadOnly: () => { assertActive(); return readOnly; },\n format: (name, value) => {\n assertActive();\n if (readOnly || composing)\n return;\n clearCompositionTail();\n editor.focus();\n const selection = readTextSelection(surface);\n if (selection?.length === 0 && (Object.hasOwn(inlineFormats, name) || Object.hasOwn(inlineStyles, name))) {\n if (!typingAtCaret())\n clearTyping();\n typingOffset = selection.index;\n typingOverrides[name] = Object.hasOwn(inlineStyles, name) ? normalizeInlineStyle(name, value) : Boolean(value);\n notifySelection();\n return;\n }\n clearTyping();\n editor.transact(() => applyFormat(surface, name, value));\n },\n insertHTML: (html) => editor.transact(() => insertFragment(surface, html)),\n focus: () => {\n assertActive();\n surface.focus({ preventScroll: true });\n if (!activeRange(surface)) {\n if (lastSelection)\n restoreBookmark(surface, lastSelection);\n else\n placeCaret(surface.firstElementChild as HTMLElement ?? surface, true);\n }\n },\n undo: () => {\n assertActive();\n rejectDuringTransaction('undo');\n if (readOnly || composing)\n return;\n clearCompositionTail();\n const previous = undoStack.pop();\n if (previous) {\n redoStack.push(capture());\n restore(previous);\n }\n },\n redo: () => {\n assertActive();\n rejectDuringTransaction('redo');\n if (readOnly || composing)\n return;\n clearCompositionTail();\n const next = redoStack.pop();\n if (next) {\n undoStack.push(capture());\n restore(next);\n }\n },\n canUndo: () => { assertActive(); return undoStack.length > 0; },\n canRedo: () => { assertActive(); return redoStack.length > 0; },\n transact: (mutate) => runTransaction(mutate),\n providePlugin: (name, api) => {\n assertActive();\n if (pluginAPIs.has(name))\n throw new Error(`Plugin API already registered: ${name}`);\n pluginAPIs.set(name, api);\n return () => { pluginAPIs.delete(name); };\n },\n getPlugin: <T>(name: string) => { assertActive(); return pluginAPIs.get(name) as T | undefined; },\n subscribe: (listener) => { assertActive(); return eventHub.events.on('change', listener); },\n onSelectionChange: (listener) => { assertActive(); return eventHub.events.on('selectionchange', listener); },\n destroy: () => {\n if (destroyed)\n return;\n rejectDuringTransaction('destroy');\n cancelComposition(false);\n destroyed = true;\n const failures: unknown[] = [];\n try {\n eventHub.destroy();\n }\n catch (error) {\n failures.push(error);\n }\n for (const dispose of disposers.reverse()) {\n try {\n dispose();\n }\n catch (error) {\n failures.push(error);\n }\n }\n pluginAPIs.clear();\n undoStack.length = 0;\n redoStack.length = 0;\n htmlSnapshots.clear();\n container.remove();\n if (failures.length)\n throw new AggregateError(failures, 'Editor cleanup failed.');\n },\n };\n const listen = <K extends keyof HTMLElementEventMap>(type: K, handler: (event: HTMLElementEventMap[K]) => void) => {\n surface.addEventListener(type, handler);\n disposers.push(() => surface.removeEventListener(type, handler));\n };\n listen('beforeinput', (event) => {\n if (event.defaultPrevented)\n return;\n if (readOnly) {\n event.preventDefault();\n return;\n }\n const compositionInput = isCompositionInput(event);\n if (canceledComposition && compositionInput) {\n event.preventDefault();\n return;\n }\n if (composing || event.isComposing)\n return;\n if (!compositionInput) {\n canceledComposition = false;\n clearCompositionTail();\n }\n if (event.inputType === 'historyUndo' || event.inputType === 'historyRedo') {\n event.preventDefault();\n if (event.inputType === 'historyUndo')\n editor.undo();\n else\n editor.redo();\n return;\n }\n if (!composing && !event.isComposing && handlesListInput(surface, event.inputType)) {\n event.preventDefault();\n clearTyping();\n pendingInput = undefined;\n runTransaction(() => editListInput(surface, event.inputType));\n return;\n }\n if (handlesBlockInput(surface, event.inputType)) {\n event.preventDefault();\n clearTyping();\n pendingInput = undefined;\n runTransaction(() => editBlockInput(surface, event.inputType));\n return;\n }\n if (event.inputType === 'insertText' && event.data && !composing && !event.isComposing && typingAtCaret() && Object.keys(typingOverrides).length) {\n event.preventDefault();\n const start = readTextSelection(surface)!.index;\n const text = event.data;\n const overrides = { ...typingOverrides };\n runTransaction(() => {\n const range = activeRange(surface)!;\n const parent = range.startContainer instanceof Element ? range.startContainer : range.startContainer.parentElement;\n const block = parent?.closest('p,h1,h2,h3,h4,h5,h6,li,blockquote,pre');\n if (block && !block.textContent && block.childNodes.length === 1 && block.firstChild instanceof HTMLBRElement) {\n block.replaceChildren();\n range.selectNodeContents(block);\n range.collapse(true);\n }\n range.insertNode(document.createTextNode(text));\n selectText(surface, start, text.length);\n for (const [name, enabled] of Object.entries(overrides))\n if ((Object.hasOwn(inlineStyles, name) ? readFormats(surface)[name] ?? false : Boolean(readFormats(surface)[name])) !== enabled)\n applyFormat(surface, name, enabled);\n selectText(surface, start + text.length);\n typingOffset = start + text.length;\n }, 'insertText');\n pendingInput = undefined;\n return;\n }\n pendingInput = capture();\n });\n listen('input', (nativeEvent) => {\n const event = nativeEvent as InputEvent;\n const compositionInput = isCompositionInput(event);\n if (readOnly || (canceledComposition && compositionInput)) {\n restoreCurrentDOM();\n return;\n }\n if (composing || event.isComposing)\n return;\n if (compositionTail && compositionInput) {\n const before = compositionTail;\n const changed = htmlSnapshots.read() !== current.html;\n pendingInput = undefined;\n if (!changed)\n return;\n // Replace only our own last undo entry, never an intervening application edit.\n if (compositionUndoRecorded && undoStack.at(-1) === before)\n undoStack.pop();\n compositionUndoRecorded = commitMutation(before);\n emit('user');\n return;\n }\n canceledComposition = false;\n clearCompositionTail();\n const before = pendingInput ?? current;\n pendingInput = undefined;\n commit(before, event.inputType);\n });\n listen('compositionstart', () => {\n if (readOnly) {\n canceledComposition = true;\n return;\n }\n if (composing)\n return;\n clearTyping();\n clearCompositionTail();\n pendingInput = undefined;\n canceledComposition = false;\n compositionStart = capture();\n composing = true;\n });\n listen('compositionend', () => {\n if (canceledComposition) {\n pendingInput = undefined;\n restoreCurrentDOM();\n return;\n }\n composing = false;\n const before = compositionStart;\n compositionStart = undefined;\n pendingInput = undefined;\n if (before) {\n compositionTail = before;\n compositionUndoRecorded = commitMutation(before);\n if (compositionUndoRecorded)\n emit('user');\n }\n });\n listen('paste', (event) => {\n event.preventDefault();\n if (readOnly || composing || !event.clipboardData)\n return;\n editor.focus();\n const html = event.clipboardData.getData('text/html');\n if (html)\n editor.insertHTML(html);\n else {\n const text = event.clipboardData.getData('text/plain');\n const holder = document.createElement('div');\n holder.textContent = text;\n editor.insertHTML(holder.innerHTML.replace(/\\r?\\n/g, '<br>'));\n }\n });\n listen('drop', (event) => { event.preventDefault(); });\n listen('keydown', (event) => {\n if (event.keyCode === 229)\n return;\n if (!composing && !event.isComposing && !readOnly && !event.ctrlKey && !event.metaKey && !event.altKey && (event.key === 'Enter' || event.key === 'Backspace' || event.key === 'Delete')) {\n const type = event.key === 'Backspace' ? 'deleteContentBackward' : event.key === 'Delete' ? 'deleteContentForward' : event.shiftKey ? 'insertLineBreak' : 'insertParagraph';\n if (handlesListInput(surface, type)) {\n event.preventDefault();\n clearTyping();\n pendingInput = undefined;\n runTransaction(() => editListInput(surface, type));\n return;\n }\n // Enter must reach beforeinput so optional typing rules can consume it first.\n if ((event.key !== 'Enter' || event.shiftKey) && handlesBlockInput(surface, type)) {\n event.preventDefault();\n clearTyping();\n pendingInput = undefined;\n runTransaction(() => editBlockInput(surface, type));\n return;\n }\n }\n if (!composing && !event.isComposing && !readOnly && event.key === 'Tab' && !event.ctrlKey && !event.metaKey && !event.altKey) {\n const blocks = selectedBlocks(surface);\n if (blocks.length && blocks.every((block) => block.localName === 'li' && !block.closest('td,th')) && listState(surface).canOutdent) {\n event.preventDefault();\n clearTyping();\n runTransaction(() => indentList(surface, event.shiftKey ? -1 : 1));\n return;\n }\n }\n if (composing || event.isComposing || readOnly || !(event.ctrlKey || event.metaKey) || event.altKey)\n return;\n const key = event.key.toLowerCase();\n if (key === 'z' || key === 'y') {\n event.preventDefault();\n if (key === 'y' || event.shiftKey)\n editor.redo();\n else\n editor.undo();\n }\n const name = ({ b: 'bold', i: 'italic', u: 'underline' } as Record<string, string>)[key];\n if (name) {\n event.preventDefault();\n editor.format(name, (editor.getFormats().mixed as string[] | undefined)?.includes(name) || !editor.getFormats()[name]);\n }\n });\n document.addEventListener('selectionchange', notifySelection);\n disposers.push(() => document.removeEventListener('selectionchange', notifySelection));\n try {\n editor.setReadOnly(readOnly);\n for (const plugin of plugins) {\n const dispose = plugin.setup(editor);\n if (dispose)\n disposers.push(dispose);\n }\n return editor;\n }\n catch (error) {\n editor.destroy();\n throw error;\n }\n};\n", "import type { ToolbarAction, ToolbarOptions } from './types.js';\nexport type { ToolbarAction, ToolbarOptions } from './types.js';\nimport type { Editor } from '../../index.js';\nimport { inlineStyles, normalizeInlineStyle } from '../../formatting/inline-attributes.js';\nimport { bookmark, restoreBookmark } from '../../selection/index.js';\nimport type { SelectionBookmark } from '../../selection/index.js';\nconst defaultActions: ToolbarAction[] = [\n { label: '\u041E\u0442\u043C\u0435\u043D\u0438\u0442\u044C', text: '\u21B6', run: (editor) => editor.undo(), enabled: (editor) => editor.canUndo() },\n { label: '\u041F\u043E\u0432\u0442\u043E\u0440\u0438\u0442\u044C', text: '\u21B7', run: (editor) => editor.redo(), enabled: (editor) => editor.canRedo() },\n { label: '\u041F\u043E\u043B\u0443\u0436\u0438\u0440\u043D\u044B\u0439', text: 'B', format: 'bold' },\n { label: '\u041A\u0443\u0440\u0441\u0438\u0432', text: 'I', format: 'italic' },\n { label: '\u041F\u043E\u0434\u0447\u0451\u0440\u043A\u043D\u0443\u0442\u044B\u0439', text: 'U', format: 'underline' },\n { label: '\u0417\u0430\u0433\u043E\u043B\u043E\u0432\u043E\u043A', text: 'H\u2082', format: 'header', value: 2 },\n { label: '\u041C\u0430\u0440\u043A\u0438\u0440\u043E\u0432\u0430\u043D\u043D\u044B\u0439 \u0441\u043F\u0438\u0441\u043E\u043A', text: '\u2637', format: 'list', value: 'bullet' },\n { label: '\u041D\u0443\u043C\u0435\u0440\u043E\u0432\u0430\u043D\u043D\u044B\u0439 \u0441\u043F\u0438\u0441\u043E\u043A', text: '1.', format: 'list', value: 'ordered' },\n { label: '\u0423\u0432\u0435\u043B\u0438\u0447\u0438\u0442\u044C \u043E\u0442\u0441\u0442\u0443\u043F', text: '\u21E5', format: 'indent', value: 1, enabled: (editor) => Boolean(editor.getFormats().canIndent) },\n { label: '\u0423\u043C\u0435\u043D\u044C\u0448\u0438\u0442\u044C \u043E\u0442\u0441\u0442\u0443\u043F', text: '\u21E4', format: 'indent', value: -1, enabled: (editor) => Boolean(editor.getFormats().canOutdent) },\n { label: '\u0426\u0438\u0442\u0430\u0442\u0430', text: '\u275D', format: 'blockquote' },\n { label: '\u041E\u0447\u0438\u0441\u0442\u0438\u0442\u044C \u0444\u043E\u0440\u043C\u0430\u0442\u0438\u0440\u043E\u0432\u0430\u043D\u0438\u0435', text: 'Tx', format: 'clear', enabled: (editor) => Boolean(editor.getSelection()?.length) },\n];\nexport const createToolbar = (host: HTMLElement, editor: Editor, actions = defaultActions, options: ToolbarOptions = {}): () => void => {\n actions = actions.map((action) => action.format && Object.hasOwn(inlineStyles, action.format) ? { ...action, value: normalizeInlineStyle(action.format, action.value) } : action);\n const toolbar = document.createElement('div');\n toolbar.className = 'mw-toolbar';\n toolbar.setAttribute('role', 'toolbar');\n toolbar.setAttribute('aria-label', options.label ?? '\u0424\u043E\u0440\u043C\u0430\u0442\u0438\u0440\u043E\u0432\u0430\u043D\u0438\u0435');\n let saved: SelectionBookmark | undefined;\n let disposed = false;\n let tabIndex = 0;\n const cleanups: (() => void)[] = [];\n const buttons = actions.map((action) => {\n const button = document.createElement('button');\n button.type = 'button';\n button.textContent = action.text;\n button.title = action.label;\n button.setAttribute('aria-label', action.label);\n const down = (event: MouseEvent) => event.preventDefault();\n const click = () => {\n if (disposed || button.disabled || editor.isReadOnly())\n return;\n editor.focus();\n if (saved)\n restoreBookmark(editor.surface, saved);\n if (action.enabled && !action.enabled(editor))\n return;\n if (action.run)\n action.run(editor);\n else if (action.format) {\n const formats = editor.getFormats();\n const mixed = (formats.mixed as string[] | undefined)?.includes(action.format);\n editor.format(action.format, !mixed && formats[action.format] === (action.value ?? true) ? false : action.value ?? true);\n }\n update();\n };\n button.addEventListener('mousedown', down);\n button.addEventListener('click', click);\n cleanups.push(() => { button.removeEventListener('mousedown', down); button.removeEventListener('click', click); });\n toolbar.append(button);\n return button;\n });\n const update = () => {\n if (disposed)\n return;\n saved = bookmark(editor.surface) ?? saved;\n const formats = editor.getFormats();\n buttons.forEach((button, index) => {\n const action = actions[index];\n button.disabled = editor.isReadOnly() || (action.enabled ? !action.enabled(editor) : false);\n if (action.format && !['indent', 'clear'].includes(action.format))\n button.setAttribute('aria-pressed', (formats.mixed as string[] | undefined)?.includes(action.format) ? 'mixed' : String(formats[action.format] === (action.value ?? true)));\n });\n if (buttons[tabIndex]?.disabled || !buttons[tabIndex])\n tabIndex = buttons.findIndex((button) => !button.disabled);\n buttons.forEach((button, index) => { button.tabIndex = index === tabIndex ? 0 : -1; });\n };\n const keyboard = (event: KeyboardEvent) => {\n const enabled = buttons.filter((button) => !button.disabled);\n if (!enabled.length)\n return;\n const index = enabled.indexOf(document.activeElement as HTMLButtonElement);\n if (index < 0 || event.ctrlKey || event.metaKey || event.altKey)\n return;\n if (event.key === 'Escape') {\n event.preventDefault();\n editor.focus();\n if (saved)\n restoreBookmark(editor.surface, saved);\n return;\n }\n const direction = getComputedStyle(toolbar).direction === 'rtl' ? -1 : 1;\n const next = event.key === 'Home' ? 0 : event.key === 'End' ? enabled.length - 1 : event.key === 'ArrowRight' ? (index + direction + enabled.length) % enabled.length : event.key === 'ArrowLeft' ? (index - direction + enabled.length) % enabled.length : -1;\n if (next >= 0) {\n event.preventDefault();\n tabIndex = buttons.indexOf(enabled[next]);\n update();\n enabled[next].focus();\n }\n };\n toolbar.addEventListener('keydown', keyboard);\n const unsubscribe = editor.subscribe((change) => {\n if (change.source === 'api')\n saved = undefined; update();\n });\n const unselect = editor.onSelectionChange(update);\n host.append(toolbar);\n update();\n return () => {\n if (disposed)\n return; disposed = true; unsubscribe(); unselect(); toolbar.removeEventListener('keydown', keyboard); for (const dispose of cleanups)\n dispose(); toolbar.remove();\n };\n};\n"],
|
|
5
|
+
"mappings": "AAGO,IAAMA,GAAe,CAAC,IAAK,KAAM,KAAM,KAAM,KAAM,KAAM,KAAM,aAAc,MAAO,OAAQ,SAAU,KAAM,IAAK,IAAK,MAAO,MAAO,IAAK,OAAQ,KAAM,KAAM,KAAM,KAAM,KAAM,MAAO,SAAU,aAAc,QAAS,UAAW,WAAY,MAAO,QAAS,QAAS,QAAS,KAAM,KAAM,IAAI,EACjSC,GAAO,IAAI,IAAYD,EAAY,EACnCE,GAAU,IAAI,IAAI,CAAC,SAAU,QAAS,SAAU,SAAU,QAAS,MAAO,OAAQ,WAAY,OAAQ,QAAS,SAAU,WAAY,SAAU,WAAY,OAAQ,OAAQ,MAAM,CAAC,EAClLC,GAAkC,CAAE,EAAG,SAAU,EAAG,KAAM,OAAQ,IAAK,IAAK,GAAI,EAChFC,GAAY,IACZC,GAAY,IACZC,GAAU,CAACC,EAAeC,IAAuC,CACrE,IAAMC,EAAUF,EAAM,KAAK,EAC3B,GAAI,CAACE,GAAW,wBAAwB,KAAKA,CAAO,EAClD,OAEF,IAAMC,EAAW,wBAAwB,KAAKD,CAAO,IAAI,CAAC,EAAE,YAAY,EACxE,GAAI,EAAAC,GAAY,EAAE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CAAQ,EAC5C,IAAMI,EAAc5B,EAAO,UAAW6B,GAAW,CAC3CA,EAAO,SAAW,QACpBpB,EAAQ,QAAWY,EAAO,CAC9B,CAAC,EACKS,EAAW9B,EAAO,kBAAkBqB,CAAM,EAChD,OAAAnB,EAAK,OAAOM,CAAO,EACnBa,EAAO,EACA,IAAM,CACX,GAAI,CAAAX,EACM,CAAAA,EAAW,GAAMkB,EAAY,EAAGE,EAAS,EAAGtB,EAAQ,oBAAoB,UAAWgB,CAAQ,EAAG,QAAWO,KAAWnB,EAC5HmB,EAAQ,EAAGvB,EAAQ,OAAO,EAC9B,CACF",
|
|
6
|
+
"names": ["documentTags", "tags", "omitted", "aliases", "MAX_NODES", "MAX_DEPTH", "safeURL", "value", "image", "trimmed", "protocol", "safeStyle", "result", "declaration", "separator", "property", "content", "color", "length", "attributesFor", "tag", "input", "output", "key", "clean", "tokens", "token", "dimensions", "styles", "part", "readDOM", "node", "depth", "budget", "element", "original", "children", "child", "attributes", "attr", "parseHTML", "html", "template", "validateDocument", "count", "textLength", "visit", "attrs", "renderDocument", "fragment", "append", "parent", "documentHTML", "container", "sanitizeHTML", "activeRange", "root", "selection", "range", "nodePath", "target", "result", "node", "bookmark", "restoreBookmark", "saved", "resolve", "path", "index", "start", "end", "limit", "offset", "startOffset", "endOffset", "readTextSelection", "prefix", "selectText", "length", "value", "walker", "nodes", "current", "locate", "last", "placeCaret", "element", "preserveRange", "mutate", "native", "backward", "tail", "head", "next", "blocks", "isList", "element", "elementAt", "node", "blockAt", "root", "preferItem", "item", "block", "touches", "range", "content", "start", "end", "first", "last", "selectedBlocks", "activeRange", "preferItems", "found", "walker", "topItems", "items", "parent", "itemRange", "siblings", "depth", "result", "compatible", "a", "b", "joinLists", "list", "previous", "splitAround", "replacement", "tail", "ownContent", "unwrapRoot", "paragraphOnly", "paragraphNode", "paragraph", "nested", "output", "lift", "owner", "trailing", "listState", "canIndent", "child", "indentList", "direction", "preserveRange", "applyList", "value", "selected", "tag", "empty", "placeholder", "atStart", "prefix", "handlesListInput", "inputType", "editListInput", "next", "caret", "selection", "placeCaret", "br", "marker", "target", "blockTags", "inlineTags", "inlineTree", "element", "node", "parentOf", "editableBlock", "root", "block", "parent", "hasContent", "fragment", "selectedBlock", "range", "activeRange", "atEdge", "end", "remainder", "siblingBlock", "forward", "sibling", "handlesBlockInput", "inputType", "editBlockInput", "document", "tailRange", "tail", "emptyHeading", "headingEnd", "paragraph", "attribute", "placeCaret", "next", "terminal", "lineBreak", "caret", "selection", "left", "right", "join", "inlineStyles", "blocks", "checkedAttributes", "tag", "attributes", "validateDocument", "normalizeInlineStyle", "name", "value", "property", "attrs", "probe", "color", "normalizeLink", "input", "link", "clean", "mergeLinkAttributes", "previous", "patch", "equalAttributes", "a", "b", "withoutProperty", "style", "part", "groupPieces", "pieces", "result", "piece", "last", "compact", "nodes", "node", "next", "transformInlineAttributes", "document", "from", "to", "operation", "position", "wrap", "group", "children", "visit", "inheritedLink", "start", "left", "right", "begin", "end", "selected", "text", "child", "content", "applyLink", "root", "value", "link", "normalizeLink", "range", "activeRange", "selection", "readTextSelection", "element", "anchor", "existing", "documentHTML", "transformInlineAttributes", "parseHTML", "selectText", "attrs", "mergeLinkAttributes", "attr", "preserveRange", "key", "val", "created", "parent", "tail", "native", "blockTags", "textLength", "node", "length", "child", "inlineDocument", "value", "from", "to", "tag", "enabled", "position", "visit", "start", "left", "right", "begin", "end", "selected", "text", "leaf", "children", "piece", "groups", "last", "group", "leaves", "inlineTags", "structuralAncestors", "elementAt", "node", "isInlineTree", "parent", "element", "applyLocalInline", "root", "range", "tag", "enabled", "block", "prefix", "from", "length", "native", "backward", "content", "inlineDocument", "parseHTML", "fragment", "renderDocument", "replacement", "selectText", "selected", "inlineFormats", "closestElement", "node", "formatsAt", "root", "element", "formats", "name", "tag", "property", "inlineStyles", "readFormats", "range", "activeRange", "mixed", "index", "length", "readTextSelection", "walker", "position", "samples", "end", "keys", "normalized", "sample", "key", "listState", "applyFormat", "value", "applyLocalInline", "selection", "applyList", "indentList", "content", "parseHTML", "inlineDocument", "documentHTML", "selectText", "applyLink", "color", "normalizeInlineStyle", "transformInlineAttributes", "blocks", "selectedBlocks", "paragraph", "preserveRange", "block", "nextTag", "replacement", "tokens", "coreNames", "createPluginEvent", "name", "token", "assertToken", "event", "createEventHub", "listeners", "queue", "registration", "dispatching", "closing", "enqueue", "entry", "failures", "next", "bucket", "listener", "registered", "payload", "error", "key", "createHTMLSnapshots", "surface", "previousInput", "previousHTML", "input", "html", "sanitizeHTML", "isCompositionInput", "event", "ensureDocument", "root", "normalized", "paragraph", "node", "insertFragment", "html", "range", "activeRange", "fragment", "renderDocument", "parseHTML", "block", "hasBlocks", "last", "tailRange", "tail", "next", "selection", "createEditor", "host", "options", "plugins", "plugin", "limit", "initialDocument", "container", "surface", "destroyed", "readOnly", "composing", "compositionStart", "canceledComposition", "compositionTail", "compositionUndoRecorded", "pendingInput", "lastInputTime", "lastInputType", "typingOverrides", "typingOffset", "clearTyping", "typingAtCaret", "readTextSelection", "undoStack", "redoStack", "eventHub", "createEventHub", "transactionDepth", "transactionFailed", "transactionError", "pendingSelectionNotification", "pluginAPIs", "disposers", "assertActive", "rejectDuringTransaction", "operation", "error", "events", "payload", "htmlSnapshots", "createHTMLSnapshots", "capture", "bookmark", "restoreTyping", "snapshot", "current", "lastSelection", "clearCompositionTail", "cancelComposition", "rollback", "before", "restoreBookmark", "restoreCurrentDOM", "notifySelection", "saved", "emit", "source", "change", "editor", "failures", "commitMutation", "inputType", "selectText", "after", "now", "commit", "restore", "runTransaction", "mutate", "invoke", "result", "previousUndo", "previousRedo", "previousInputTime", "previousInputType", "previousPendingInput", "previousSelection", "changed", "selectionChanged", "content", "documentHTML", "value", "validated", "validateDocument", "index", "length", "readFormats", "name", "inlineFormats", "inlineStyles", "normalizeInlineStyle", "applyFormat", "placeCaret", "previous", "api", "listener", "dispose", "listen", "type", "handler", "compositionInput", "handlesListInput", "editListInput", "handlesBlockInput", "editBlockInput", "start", "text", "overrides", "enabled", "nativeEvent", "holder", "blocks", "selectedBlocks", "listState", "indentList", "key", "defaultActions", "editor", "createToolbar", "host", "actions", "options", "action", "inlineStyles", "normalizeInlineStyle", "toolbar", "saved", "disposed", "tabIndex", "cleanups", "buttons", "button", "down", "event", "click", "restoreBookmark", "formats", "mixed", "update", "bookmark", "index", "keyboard", "enabled", "direction", "next", "unsubscribe", "change", "unselect", "dispose"]
|
|
7
7
|
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { editBlockInput, handlesBlockInput } from './block-boundaries.js';
|