@morfira-dev/wysiwyg-core 0.2.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -50,11 +50,5 @@ export interface Editor {
50
50
  destroy(): void;
51
51
  }
52
52
  export declare const createEditor: (host: HTMLElement, options?: EditorOptions) => Editor;
53
- export interface ToolbarAction {
54
- label: string;
55
- text: string;
56
- format?: string;
57
- value?: unknown;
58
- run?: (editor: Editor) => void;
59
- }
60
- export declare const createToolbar: (host: HTMLElement, editor: Editor, actions?: ToolbarAction[]) => () => void;
53
+ export { createToolbar } from './toolbar.js';
54
+ export type { ToolbarAction, ToolbarOptions } from './toolbar.js';
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- var me=["p","h1","h2","h3","h4","h5","h6","blockquote","pre","code","strong","em","u","s","sub","sup","a","span","br","hr","ul","ol","li","img","table","caption","colgroup","col","thead","tbody","tfoot","tr","td","th"],oe=new Set(me),fe=new Set(["script","style","iframe","object","embed","svg","math","template","form","input","button","textarea","select","noscript","link","meta","base"]),pe={b:"strong",i:"em",strike:"s",div:"p"},se=1e5,ie=100,he=(n,o)=>{let e=n.trim();if(!e||/[\u0000-\u0020\u007f]/.test(e))return;let t=/^([a-z][a-z\d+.-]*):/i.exec(e)?.[1].toLowerCase();if(!(t&&!(o?["http","https"]:["http","https","mailto","tel"]).includes(t))&&!(e.startsWith("\\")||e.startsWith("//")))return e},ge=n=>{let o=[];for(let e of n.split(";")){let t=e.indexOf(":");if(t<0)continue;let s=e.slice(0,t).trim().toLowerCase(),l=e.slice(t+1).trim().toLowerCase(),i=/^(#[a-f\d]{3,8}|[a-z]{1,24}|(?:rgb|rgba|hsl|hsla)\([\d\s.,%+-]+\))$/,u=/^(?:\d{1,4}(?:\.\d{1,3})?)(?:px|%|em|rem)$/;(["color","background-color","border-color"].includes(s)?i.test(l):["width","height","font-size"].includes(s)?u.test(l):s==="text-align"?["left","center","right","justify"].includes(l):s==="font-weight"?/^(bold|normal|[1-9]00)$/.test(l):s==="font-style"?["italic","normal"].includes(l):s==="text-decoration"?/^(underline|line-through|none)$/.test(l):!1)&&o.push(`${s}: ${l}`)}return o.join("; ")},ce=(n,o)=>{let e={};for(let[t,s]of Object.entries(o))if(!(typeof s!="string"||s.length>2e4))if(t==="style"){let l=ge(s);l&&(e.style=l)}else if(t==="title"||n==="img"&&t==="alt")e[t]=s;else if(n==="a"&&t==="href"||n==="img"&&t==="src"){let l=he(s,n==="img");l&&(e[t]=l)}else["td","th"].includes(n)&&["rowspan","colspan"].includes(t)||["img","col","table"].includes(n)&&["width","height","span"].includes(t)?/^\d{1,4}$/.test(s)&&Number(s)>0&&Number(s)<=1e3&&(e[t]=s):n==="th"&&t==="scope"&&["row","col","rowgroup","colgroup"].includes(s)&&(e[t]=s);return e},le=(n,o,e)=>{if(++e.count>se||o>ie)throw new RangeError("Document exceeds structural limits.");if(n.nodeType===3)return[{type:"text",text:n.textContent??""}];if(n.nodeType!==1)return[];let t=n,s=t.localName.toLowerCase();if(t.namespaceURI!=="http://www.w3.org/1999/xhtml"||fe.has(s))return[];let l=[...t.childNodes].flatMap(c=>le(c,o+1,e)),i=pe[s]??s;if(!oe.has(i))return l;let u=ce(i,Object.fromEntries([...t.attributes].map(c=>[c.name,c.value])));return i==="img"&&!u.src?[]:[{type:"element",tag:i,attributes:u,children:l}]},M=n=>{if(n.length>5e6)throw new RangeError("HTML exceeds the document size limit.");let o=document.createElement("template");o.innerHTML=n;let e={count:0};return{version:1,children:[...o.content.childNodes].flatMap(t=>le(t,0,e))}},$=n=>{if(!n||typeof n!="object"||!("version"in n)||n.version!==1||!("children"in n)||!Array.isArray(n.children))throw new TypeError("Expected a version 1 document.");let o=0,e=0,t=(s,l)=>{if(++o>se||l>ie)throw new RangeError("Document exceeds structural limits.");if(!s||typeof s!="object"||!("type"in s))throw new TypeError("Invalid document node.");if(s.type==="text"&&"text"in s&&typeof s.text=="string"){if(e+=s.text.length,e>5e6)throw new RangeError("Document text exceeds size limit.");return{type:"text",text:s.text}}if(s.type!=="element"||!("tag"in s)||typeof s.tag!="string"||!oe.has(s.tag)||!("children"in s)||!Array.isArray(s.children))throw new TypeError("Invalid document element.");let i="attributes"in s&&s.attributes&&typeof s.attributes=="object"&&!Array.isArray(s.attributes)?s.attributes:{};return{type:"element",tag:s.tag,attributes:ce(s.tag,i),children:s.children.map(u=>t(u,l+1))}};return{version:1,children:n.children.map(s=>t(s,0))}},U=n=>{let o=document.createDocumentFragment(),e=(t,s)=>{if(s.type==="text"){t.appendChild(document.createTextNode(s.text));return}let l=document.createElement(s.tag);for(let[i,u]of Object.entries(s.attributes))l.setAttribute(i,u);for(let i of s.children)e(l,i);t.appendChild(l)};for(let t of n.children)e(o,t);return o},A=n=>{let o=document.createElement("div");return o.append(U(n)),o.innerHTML},K=n=>A(M(n));var C=n=>{let o=n.ownerDocument.getSelection();if(!o?.rangeCount)return;let e=o.getRangeAt(0);if(!(!n.contains(e.startContainer)||!n.contains(e.endContainer)))return e.cloneRange()},ae=(n,o)=>{let e=[],t=o;for(;t!==n&&t.parentNode;)e.unshift([...t.parentNode.childNodes].indexOf(t)),t=t.parentNode;return e},V=n=>{let o=C(n);if(!o)return;let e=n.ownerDocument.getSelection();return{start:ae(n,o.startContainer),startOffset:o.startOffset,end:ae(n,o.endContainer),endOffset:o.endOffset,backward:!o.collapsed&&e.anchorNode===o.endContainer&&e.anchorOffset===o.endOffset}},W=(n,o)=>{if(!o)return;let e=f=>f.reduce((a,d)=>a.childNodes[d]??a,n),t=e(o.start),s=e(o.end),l=(f,a)=>Math.min(a,f.nodeType===3?f.textContent?.length??0:f.childNodes.length),i=n.ownerDocument.getSelection();if(!i)return;let u=l(t,o.startOffset),c=l(s,o.endOffset);o.backward?i.setBaseAndExtent(s,c,t,u):i.setBaseAndExtent(t,u,s,c)},H=n=>{let o=C(n);if(!o)return;let e=n.ownerDocument.createRange();return e.selectNodeContents(n),e.setEnd(o.startContainer,o.startOffset),{index:e.toString().length,length:o.toString().length}},v=(n,o,e=0)=>{if(![o,e].every(x=>Number.isInteger(x)&&x>=0))throw new RangeError("Selection offsets must be non-negative integers.");let t=n.ownerDocument.createTreeWalker(n,4),s=[],l;for(;l=t.nextNode();)s.push(l);let i=x=>{for(let w of s){if(x<=w.length)return[w,x];x-=w.length}let y=s.at(-1);return y?[y,y.length]:[n.querySelector("p,h1,h2,h3,h4,h5,h6,li,blockquote,pre")??n,0]},[u,c]=i(o),[f,a]=i(o+e),d=n.ownerDocument.createRange();d.setStart(u,c),d.setEnd(f,a),n.focus({preventScroll:!0});let p=n.ownerDocument.getSelection();p?.removeAllRanges(),p?.addRange(d)},de=(n,o=!1)=>{let e=n.ownerDocument.createRange();e.selectNodeContents(n),e.collapse(!o);let t=n.ownerDocument.getSelection();t?.removeAllRanges(),t?.addRange(e)};var J={bold:"strong",italic:"em",underline:"u",strike:"s",code:"code",subscript:"sub",superscript:"sup"},be=new Set(["p","h1","h2","h3","h4","h5","h6","blockquote","pre","ul","ol","li","table","thead","tbody","tfoot","tr","td","th","caption","colgroup"]),xe=(n,o,e,t,s)=>{let l=0,i=(u,c)=>{if(u.type==="text"){let d=l;l+=u.text.length;let p=Math.max(0,Math.min(u.text.length,o-d)),x=Math.max(p,Math.min(u.text.length,e-d));return[[0,p,!1],[p,x,!0],[x,u.text.length,!1]].flatMap(([y,w,k])=>{let R=u.text.slice(y,w);if(!R)return[];let E={type:"text",text:R};return[{node:k&&s&&!c?{type:"element",tag:t,attributes:{},children:[E]}:E,selected:!!k}]})}let f=u.children.flatMap(d=>i(d,c||s&&u.tag===t));if(be.has(u.tag))return[{node:{...u,children:f.map(d=>d.node)},selected:!1}];if(!f.length)return[{node:u,selected:!1}];let a=[];for(let d of f){let p=a.at(-1);p?.selected===d.selected?p.children.push(d.node):a.push({selected:d.selected,children:[d.node]})}return a.flatMap(d=>u.tag===t&&!s&&d.selected?d.children.map(p=>({node:p,selected:!0})):[{node:{...u,children:d.children},selected:d.selected}])};return{version:1,children:n.children.flatMap(u=>i(u,!1)).map(u=>u.node)}},ue=n=>n.nodeType===1?n:n.parentElement,Y=n=>{let o=C(n);if(!o)return{};let e=ue(o.startContainer),t={};for(;e&&e!==n;){for(let[s,l]of Object.entries(J))e.localName===l&&(t[s]=!0);/^h[1-6]$/.test(e.localName)&&(t.header=Number(e.localName[1])),e.localName==="blockquote"&&(t.blockquote=!0),e.localName==="pre"&&(t["code-block"]=!0),(e.localName==="ul"||e.localName==="ol")&&(t.list=e.localName==="ul"?"bullet":"ordered"),e.localName==="a"&&(t.link=e.getAttribute("href")),e=e.parentElement}return t},Z=(n,o,e)=>{let t=C(n);if(!t)return;let s=H(n),l=J[o];if(l){if(t.collapsed)return;n.innerHTML=A(xe(M(n.innerHTML),s.index,s.index+s.length,l,!!e)),v(n,s.index,s.length);return}if(o==="link"){if(e){if(typeof e=="string"&&!t.collapsed){let f=M("<a></a>").children[0];f.attributes.href=e;let a=document.createElement("div");a.innerHTML=A($({version:1,children:[f]}));let d=M(a.innerHTML).children[0];if(!d.attributes.href)return;let p=document.createElement("a");p.setAttribute("href",d.attributes.href),p.append(t.extractContents()),t.insertNode(p),t.selectNodeContents(p);let x=document.getSelection();x?.removeAllRanges(),x?.addRange(t)}}else{let c=ue(t.startContainer)?.closest("a");c&&n.contains(c)&&c.replaceWith(...c.childNodes)}return}let u=[...n.querySelectorAll("p,h1,h2,h3,h4,h5,h6,blockquote,pre,li")].filter(c=>c.querySelector("p,h1,h2,h3,h4,h5,h6,blockquote,pre,li")?!1:t.collapsed?c.contains(t.startContainer):t.intersectsNode(c));if(!u.length){let c=document.createElement("p");c.append(t.extractContents()),c.childNodes.length||c.append(document.createElement("br")),t.insertNode(c),u=[c]}for(let c of u){if(o==="align"&&["left","center","right","justify",!1].includes(e)){c.style.textAlign=e?String(e):"";continue}if(o==="list"){if(!e&&c.localName==="li"){let a=c.parentElement,d=document.createElement("p");d.append(...c.childNodes);let p=a.cloneNode(!1);for(;c.nextSibling;)p.append(c.nextSibling);c.remove(),a.after(d),p.childNodes.length&&d.after(p),a.childNodes.length||a.remove()}else if(e==="bullet"||e==="ordered")if(c.localName==="li"){let a=c.parentElement,d=document.createElement(e==="bullet"?"ul":"ol");d.append(...a.childNodes),a.replaceWith(d)}else{let a=document.createElement(e==="bullet"?"ul":"ol"),d=document.createElement("li");d.append(...c.childNodes),a.append(d),c.replaceWith(a)}continue}let f=o==="header"?Number.isInteger(e)&&Number(e)>=1&&Number(e)<=6?`h${e}`:"p":o==="blockquote"?e?"blockquote":"p":o==="code-block"?e?"pre":"p":void 0;if(f){let a=document.createElement(f);a.append(...c.childNodes),c.replaceWith(a)}}v(n,s.index,s.length)};var _=n=>{let o=!1;n.childNodes.length||(n.innerHTML="<p><br></p>",o=!0);let e;for(let t of[...n.childNodes])t.nodeType===3||t.nodeType===1&&/^(strong|em|u|s|a|span|code|img|br|sub|sup)$/.test(t.localName)?(e||(e=document.createElement("p"),n.insertBefore(e,t)),e.append(t),o=!0):e=void 0;return n.lastElementChild?.localName==="table"&&n.append(Object.assign(document.createElement("p"),{innerHTML:"<br>"})),n.dataset.empty=String(!n.textContent&&!n.querySelector("table,img,hr")),o},Ee=(n,o)=>{let e=C(n);if(!e)return;let t=U(M(o));if(!t.childNodes.length)return;e.deleteContents();let l=(e.startContainer.nodeType===1?e.startContainer:e.startContainer.parentElement)?.closest("p,h1,h2,h3,h4,h5,h6,li,blockquote,pre");if(t.childNodes.length===1&&t.firstChild instanceof HTMLParagraphElement&&l){let a=t.firstChild;t.replaceChildren(...a.childNodes)}let i=[...t.childNodes].some(a=>a instanceof HTMLElement&&/^(p|h[1-6]|ul|ol|table|blockquote|pre)$/.test(a.localName)),u=t.lastChild;if(i&&l&&n.contains(l)){let a=document.createRange();a.selectNodeContents(l),a.setStart(e.startContainer,e.startOffset);let d=l.cloneNode(!1);d.append(a.extractContents()),l.after(t),(d.textContent||d.querySelector("img,br"))&&u.after(d),!l.textContent&&!l.querySelector("img")&&l.remove()}else e.insertNode(t);let c=document.createRange();c.setStartAfter(u),c.collapse(!0);let f=document.getSelection();f?.removeAllRanges(),f?.addRange(c)},Ce=(n,o={})=>{if(n.childNodes.length)throw new Error("Editor host must be empty. Pass initial HTML through value.");let e=o.plugins??[];if(new Set(e.map(r=>r.name)).size!==e.length)throw new Error("Duplicate editor plugin.");let t=o.historyLimit??100;if(!Number.isInteger(t)||t<1||t>1e4)throw new RangeError("historyLimit must be an integer from 1 to 10000.");let s=M(o.value??""),l=document.createElement("div");l.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",o.label??"\u0422\u0435\u043A\u0441\u0442\u043E\u0432\u044B\u0439 \u0440\u0435\u0434\u0430\u043A\u0442\u043E\u0440"),i.dataset.placeholder=o.placeholder??"\u041D\u0430\u0447\u043D\u0438\u0442\u0435 \u043F\u0438\u0441\u0430\u0442\u044C\u2026",l.append(i),n.append(l),i.append(U(s)),_(i);let u=!1,c=o.readOnly??!1,f=!1,a,d,p=0,x="",y={},w,k=()=>{y={},w=void 0},R=()=>{let r=H(i);return r?.length===0&&r.index===w},E=[],D=[],B=new Set,I=new Set,P=new Map,z=[];o.onChange&&B.add(o.onChange);let g=()=>{if(u)throw new Error("Editor has been destroyed.")},S=()=>({html:K(i.innerHTML),selection:V(i)}),T=S(),F=T.selection,j=()=>{if(u)return;H(i)&&!R()&&k();let r=V(i);r&&(F=r,T.selection=r);for(let m of I)m()},X=r=>{let m={html:b.getHTML(),text:b.getText(),source:r};for(let h of[...B])h(m);j()},G=(r,m="")=>{let h=H(i);_(i)&&h&&v(i,h.index,h.length);let L=S();if(L.html===r.html){T=L;return}let N=Date.now();m===x&&["insertText","deleteContentBackward","deleteContentForward"].includes(m)&&N-p<600&&r.selection&&T.selection&&JSON.stringify(r.selection)===JSON.stringify(T.selection)||(E.push(r),E.length>t&&E.shift()),D.length=0,T=L,p=m?N:0,x=m,X("user")},ee=r=>{k(),i.innerHTML=r.html,_(i),i.focus({preventScroll:!0}),W(i,r.selection),T=S(),F=T.selection,p=0,X("user")},te=(r,m="")=>{if(g(),c)return;b.focus();let h=S(),L=[...E],N=[...D];try{r(i),G(h,m)}catch(Q){throw i.innerHTML=h.html,W(i,h.selection),T=S(),E.splice(0,E.length,...L),D.splice(0,D.length,...N),Q}},b={element:l,surface:i,getHTML:()=>(g(),K(i.innerHTML)),getText:()=>(g(),i.innerText),getJSON:()=>(g(),M(i.innerHTML)),setHTML:r=>{g();let m=A(M(r));m!==b.getHTML()&&(k(),i.innerHTML=m,_(i),E.length=0,D.length=0,p=0,F=void 0,T=S(),X("api"))},setJSON:r=>{g();let m=$(r);b.setHTML(A(m))},getSelection:()=>(g(),H(i)),setSelection:(r,m=0)=>{g(),v(i,r,m),j()},getFormats:()=>(g(),{...Y(i),...R()?y:{}}),setReadOnly:r=>{g(),c=r,i.contentEditable=String(!r),i.setAttribute("aria-readonly",String(r)),l.dataset.readonly=String(r),j()},isReadOnly:()=>(g(),c),format:(r,m)=>{if(g(),c)return;b.focus();let h=H(i);if(h?.length===0&&Object.hasOwn(J,r)){R()||k(),w=h.index,y[r]=!!m,j();return}k(),b.transact(()=>Z(i,r,m))},insertHTML:r=>b.transact(()=>Ee(i,r)),focus:()=>{g(),i.focus({preventScroll:!0}),C(i)||(F?W(i,F):de(i.firstElementChild??i,!0))},undo:()=>{if(g(),c)return;let r=E.pop();r&&(D.push(S()),ee(r))},redo:()=>{if(g(),c)return;let r=D.pop();r&&(E.push(S()),ee(r))},canUndo:()=>(g(),E.length>0),canRedo:()=>(g(),D.length>0),transact:r=>te(r),providePlugin:(r,m)=>{if(g(),P.has(r))throw new Error(`Plugin API already registered: ${r}`);return P.set(r,m),()=>{P.delete(r)}},getPlugin:r=>(g(),P.get(r)),subscribe:r=>(g(),B.add(r),()=>{B.delete(r)}),onSelectionChange:r=>(g(),I.add(r),()=>{I.delete(r)}),destroy:()=>{if(u)return;u=!0;let r=[];for(let m of z.reverse())try{m()}catch(h){r.push(h)}if(B.clear(),I.clear(),P.clear(),E.length=0,D.length=0,l.remove(),r.length)throw new AggregateError(r,"Editor cleanup failed.")}},O=(r,m)=>{i.addEventListener(r,m),z.push(()=>i.removeEventListener(r,m))};O("beforeinput",r=>{if(c){r.preventDefault();return}if(r.inputType==="historyUndo"||r.inputType==="historyRedo"){r.preventDefault(),r.inputType==="historyUndo"?b.undo():b.redo();return}if(r.inputType==="insertText"&&r.data&&!f&&!r.isComposing&&R()&&Object.keys(y).length){r.preventDefault();let m=H(i).index,h=r.data,L={...y};te(()=>{let N=C(i),q=(N.startContainer instanceof Element?N.startContainer:N.startContainer.parentElement)?.closest("p,h1,h2,h3,h4,h5,h6,li,blockquote,pre");q&&!q.textContent&&q.childNodes.length===1&&q.firstChild instanceof HTMLBRElement&&(q.replaceChildren(),N.selectNodeContents(q),N.collapse(!0)),N.insertNode(document.createTextNode(h)),v(i,m,h.length);for(let[ne,re]of Object.entries(L))!!Y(i)[ne]!==re&&Z(i,ne,re);v(i,m+h.length),w=m+h.length},"insertText"),d=void 0;return}d=S()}),O("input",r=>{let m=r;if(c){i.innerHTML=T.html;return}f||m.isComposing||(G(d??T,m.inputType),d=void 0)}),O("compositionstart",()=>{k(),f=!0,a=S()}),O("compositionend",()=>{f=!1,a&&G(a),a=void 0,d=void 0}),O("paste",r=>{if(r.preventDefault(),c||!r.clipboardData)return;b.focus();let m=r.clipboardData.getData("text/html");if(m)b.insertHTML(m);else{let h=r.clipboardData.getData("text/plain"),L=document.createElement("div");L.textContent=h,b.insertHTML(L.innerHTML.replace(/\r?\n/g,"<br>"))}}),O("drop",r=>{r.preventDefault()}),O("keydown",r=>{if(f||r.isComposing||c||!(r.ctrlKey||r.metaKey)||r.altKey)return;let m=r.key.toLowerCase();(m==="z"||m==="y")&&(r.preventDefault(),m==="y"||r.shiftKey?b.redo():b.undo());let h={b:"bold",i:"italic",u:"underline"}[m];h&&(r.preventDefault(),b.format(h,!b.getFormats()[h]))}),document.addEventListener("selectionchange",j),z.push(()=>document.removeEventListener("selectionchange",j));try{b.setReadOnly(c);for(let r of e){let m=r.setup(b);m&&z.push(m)}return b}catch(r){throw b.destroy(),r}},Te=[{label:"\u041E\u0442\u043C\u0435\u043D\u0438\u0442\u044C",text:"\u21B6",run:n=>n.undo()},{label:"\u041F\u043E\u0432\u0442\u043E\u0440\u0438\u0442\u044C",text:"\u21B7",run:n=>n.redo()},{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:"\u0426\u0438\u0442\u0430\u0442\u0430",text:"\u275D",format:"blockquote"}],He=(n,o,e=Te)=>{let t=document.createElement("div");t.className="mw-toolbar",t.setAttribute("role","toolbar"),t.setAttribute("aria-label","\u0424\u043E\u0440\u043C\u0430\u0442\u0438\u0440\u043E\u0432\u0430\u043D\u0438\u0435");let s,l=e.map(f=>{let a=document.createElement("button");return a.type="button",a.textContent=f.text,a.title=f.label,a.setAttribute("aria-label",f.label),a.addEventListener("mousedown",d=>d.preventDefault()),a.addEventListener("click",()=>{o.isReadOnly()||(s?o.setSelection(s.index,s.length):o.focus(),f.run?f.run(o):f.format&&o.format(f.format,o.getFormats()[f.format]===(f.value??!0)?!1:f.value??!0),i())}),t.append(a),a}),i=()=>{s=o.getSelection()??s;let f=o.getFormats();l.forEach((a,d)=>{a.disabled=o.isReadOnly();let p=e[d];p.format&&a.setAttribute("aria-pressed",String(f[p.format]===(p.value??!0)))})},u=o.subscribe(i),c=o.onSelectionChange(i);return n.append(t),i(),()=>{u(),c(),t.remove()}};export{Ce as createEditor,He as createToolbar,K as sanitizeHTML};
1
+ var Ae=["p","h1","h2","h3","h4","h5","h6","blockquote","pre","code","strong","em","u","s","sub","sup","a","span","br","hr","ul","ol","li","img","table","caption","colgroup","col","thead","tbody","tfoot","tr","td","th"],he=new Set(Ae),Be=new Set(["script","style","iframe","object","embed","svg","math","template","form","input","button","textarea","select","noscript","link","meta","base"]),Ie={b:"strong",i:"em",strike:"s",div:"p"},be=1e5,Ee=100,qe=(e,o)=>{let n=e.trim();if(!n||/[\u0000-\u0020\u007f]/.test(n))return;let t=/^([a-z][a-z\d+.-]*):/i.exec(n)?.[1].toLowerCase();if(!(t&&!(o?["http","https"]:["http","https","mailto","tel"]).includes(t))&&!(n.startsWith("\\")||n.startsWith("//")))return n},je=e=>{let o=[];for(let n of e.split(";")){let t=n.indexOf(":");if(t<0)continue;let r=n.slice(0,t).trim().toLowerCase(),i=n.slice(t+1).trim().toLowerCase(),s=/^(#[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(r)?s.test(i):["width","height","font-size"].includes(r)?a.test(i):r==="text-align"?["left","center","right","justify"].includes(i):r==="font-weight"?/^(bold|normal|[1-9]00)$/.test(i):r==="font-style"?["italic","normal"].includes(i):r==="text-decoration"?/^(underline|line-through|none)$/.test(i):!1)&&o.push(`${r}: ${i}`)}return o.join("; ")},Te=(e,o)=>{let n={};for(let[t,r]of Object.entries(o))if(!(typeof r!="string"||r.length>2e4))if(t==="style"){let i=je(r);i&&(n.style=i)}else if(t==="title"||e==="img"&&t==="alt")n[t]=r;else if(e==="a"&&t==="href"||e==="img"&&t==="src"){let i=qe(r,e==="img");i&&(n[t]=i)}else["td","th"].includes(e)&&["rowspan","colspan"].includes(t)||["img","col","table"].includes(e)&&["width","height","span"].includes(t)?/^\d{1,4}$/.test(r)&&Number(r)>0&&Number(r)<=1e3&&(n[t]=r):e==="th"&&t==="scope"&&["row","col","rowgroup","colgroup"].includes(r)&&(n[t]=r);return n},xe=(e,o,n)=>{if(++n.count>be||o>Ee)throw new RangeError("Document exceeds structural limits.");if(e.nodeType===3)return[{type:"text",text:e.textContent??""}];if(e.nodeType!==1)return[];let t=e,r=t.localName.toLowerCase();if(t.namespaceURI!=="http://www.w3.org/1999/xhtml"||Be.has(r))return[];let i=[...t.childNodes].flatMap(c=>xe(c,o+1,n)),s=Ie[r]??r;if(!he.has(s))return i;let a=Te(s,Object.fromEntries([...t.attributes].map(c=>[c.name,c.value])));return s==="img"&&!a.src?[]:[{type:"element",tag:s,attributes:a,children:i}]},R=e=>{if(e.length>5e6)throw new RangeError("HTML exceeds the document size limit.");let o=document.createElement("template");o.innerHTML=e;let n={count:0};return{version:1,children:[...o.content.childNodes].flatMap(t=>xe(t,0,n))}},Z=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 o=0,n=0,t=(r,i)=>{if(++o>be||i>Ee)throw new RangeError("Document exceeds structural limits.");if(!r||typeof r!="object"||!("type"in r))throw new TypeError("Invalid document node.");if(r.type==="text"&&"text"in r&&typeof r.text=="string"){if(n+=r.text.length,n>5e6)throw new RangeError("Document text exceeds size limit.");return{type:"text",text:r.text}}if(r.type!=="element"||!("tag"in r)||typeof r.tag!="string"||!he.has(r.tag)||!("children"in r)||!Array.isArray(r.children))throw new TypeError("Invalid document element.");let s="attributes"in r&&r.attributes&&typeof r.attributes=="object"&&!Array.isArray(r.attributes)?r.attributes:{};return{type:"element",tag:r.tag,attributes:Te(r.tag,s),children:r.children.map(a=>t(a,i+1))}};return{version:1,children:e.children.map(r=>t(r,0))}},ee=e=>{let o=document.createDocumentFragment(),n=(t,r)=>{if(r.type==="text"){t.appendChild(document.createTextNode(r.text));return}let i=document.createElement(r.tag);for(let[s,a]of Object.entries(r.attributes))i.setAttribute(s,a);for(let s of r.children)n(i,s);t.appendChild(i)};for(let t of e.children)n(o,t);return o},O=e=>{let o=document.createElement("div");return o.append(ee(e)),o.innerHTML},te=e=>O(R(e));var M=e=>{let o=e.ownerDocument.getSelection();if(!o?.rangeCount)return;let n=o.getRangeAt(0);if(!(!e.contains(n.startContainer)||!e.contains(n.endContainer)))return n.cloneRange()},ye=(e,o)=>{let n=[],t=o;for(;t!==e&&t.parentNode;)n.unshift([...t.parentNode.childNodes].indexOf(t)),t=t.parentNode;return n},U=e=>{let o=M(e);if(!o)return;let n=e.ownerDocument.getSelection();return{start:ye(e,o.startContainer),startOffset:o.startOffset,end:ye(e,o.endContainer),endOffset:o.endOffset,backward:!o.collapsed&&n.anchorNode===o.endContainer&&n.anchorOffset===o.endOffset}},I=(e,o)=>{if(!o)return;let n=d=>d.reduce((p,u)=>p.childNodes[u]??p,e),t=n(o.start),r=n(o.end),i=(d,p)=>Math.min(p,d.nodeType===3?d.textContent?.length??0:d.childNodes.length),s=e.ownerDocument.getSelection();if(!s)return;let a=i(t,o.startOffset),c=i(r,o.endOffset);o.backward?s.setBaseAndExtent(r,c,t,a):s.setBaseAndExtent(t,a,r,c)},v=e=>{let o=M(e);if(!o)return;let n=e.ownerDocument.createRange();return n.selectNodeContents(e),n.setEnd(o.startContainer,o.startOffset),{index:n.toString().length,length:o.toString().length}},A=(e,o,n=0)=>{if(![o,n].every(N=>Number.isInteger(N)&&N>=0))throw new RangeError("Selection offsets must be non-negative integers.");let t=e.ownerDocument.createTreeWalker(e,4),r=[],i;for(;i=t.nextNode();)r.push(i);let s=N=>{for(let h of r){if(N<=h.length)return[h,N];N-=h.length}let f=r.at(-1);return f?[f,f.length]:[e.querySelector("p,h1,h2,h3,h4,h5,h6,li,blockquote,pre")??e,0]},[a,c]=s(o),[d,p]=s(o+n),u=e.ownerDocument.createRange();u.setStart(a,c),u.setEnd(d,p),e.focus({preventScroll:!0});let g=e.ownerDocument.getSelection();g?.removeAllRanges(),g?.addRange(u)},ne=(e,o=!1)=>{let n=e.ownerDocument.createRange();n.selectNodeContents(e),n.collapse(!o);let t=e.ownerDocument.getSelection();t?.removeAllRanges(),t?.addRange(n)},q=(e,o)=>{let n=M(e);if(!n)return;let t=e.ownerDocument.getSelection(),r=!n.collapsed&&t.anchorNode===n.endContainer&&t.anchorOffset===n.endOffset,i=e.ownerDocument.createComment("mw-start"),s=n.collapsed?void 0:e.ownerDocument.createComment("mw-end");if(s){let c=n.cloneRange();c.collapse(!1),c.insertNode(s)}let a=n.cloneRange();a.collapse(!0),a.insertNode(i);try{if(o(),e.contains(i)&&(!s||e.contains(s))){let c=e.ownerDocument.createRange();c.setStartBefore(i),s?c.setEndBefore(s):c.collapse(!0),i.remove(),s?.remove(),e.normalize(),r?t.setBaseAndExtent(c.endContainer,c.endOffset,c.startContainer,c.startOffset):(t.removeAllRanges(),t.addRange(c))}}finally{i.remove(),s?.remove()}};var we="p,h1,h2,h3,h4,h5,h6,blockquote,pre,li",C=e=>!!e&&/^(ul|ol)$/.test(e.localName),Fe=e=>e instanceof Element?e:e.parentElement,G=(e,o,n=!0)=>{let t=Fe(o),r=t?.closest("li"),i=(n&&r&&e.contains(r)?r:void 0)??t?.closest(we);return i&&e.contains(i)?i:void 0},Pe=(e,o)=>{let n=o.ownerDocument.createRange();o.nodeType===3?n.selectNodeContents(o):n.selectNode(o);let t=e.cloneRange();t.collapse(!0);let r=e.cloneRange();r.collapse(!1);let i=n.cloneRange();i.collapse(!0);let s=n.cloneRange();return s.collapse(!1),t.compareBoundaryPoints(Range.START_TO_START,s)<0&&r.compareBoundaryPoints(Range.START_TO_START,i)>0},P=(e,o=M(e),n=!0)=>{if(!o)return[];if(o.collapsed){let s=G(e,o.startContainer,n);return s?[s]:[]}let t=new Set,r=e.ownerDocument.createTreeWalker(e,NodeFilter.SHOW_TEXT|NodeFilter.SHOW_ELEMENT),i;for(;i=r.nextNode();)if(!(!(i.nodeType===3&&i.textContent)&&!(i instanceof Element&&/^(br|img|hr)$/.test(i.localName)))&&Pe(o,i)){let s=G(e,i,n);s&&t.add(s)}return[...e.querySelectorAll(we)].filter(s=>t.has(s))},ke=e=>e.filter(o=>!e.some(n=>n!==o&&n.contains(o))),Me=e=>{let o=ke(P(e));if(!o.length||o.some(r=>r.localName!=="li"||!C(r.parentElement)))return[];let n=o[0].parentElement;if(o.some(r=>r.parentElement!==n))return[];let t=[...n.children];return t.indexOf(o.at(-1))-t.indexOf(o[0])+1!==o.length?[]:o},Le=(e,o)=>{let n=0,t=o.parentElement;for(;t&&t!==e;)C(t)&&n++,t=t.parentElement;return n},He=(e,o)=>!!e&&e.localName===o.localName&&C(e)&&e.getAttribute("style")===o.getAttribute("style"),J=e=>{for(let o of[...e.querySelectorAll("ul,ol")]){if(!e.contains(o))continue;let n=o.previousSibling;n instanceof Element&&He(n,o)&&(n.append(...o.childNodes),o.remove())}},Se=(e,o)=>{let n=e.parentElement,t=n.cloneNode(!1);for(;e.nextSibling;)t.append(e.nextSibling);e.remove(),n.after(...o,...t.childNodes.length?[t]:[]),n.childNodes.length||n.remove()},X=e=>[...e.childNodes].filter(o=>!(o instanceof Element&&C(o))),Ce=(e,o=!1)=>{let n=()=>{let a=document.createElement("p");return e.hasAttribute("style")&&a.setAttribute("style",e.getAttribute("style")),a},t=n(),r=[...e.children].filter(C),i=X(e),s=[];for(let a of i)o&&a instanceof HTMLElement&&/^(p|h[1-6]|blockquote|pre)$/.test(a.localName)?t.append(...a.childNodes):a instanceof HTMLElement&&/^(p|h[1-6]|blockquote|pre)$/.test(a.localName)?(t.childNodes.length&&s.push(t),t=n(),s.push(a)):t.append(a);(t.childNodes.length||!s.length)&&(t.childNodes.length||t.append(document.createElement("br")),s.push(t)),Se(e,[...s,...r])},oe=e=>{let o=e[0].parentElement,n=o.parentElement;if(n?.localName!=="li"||!C(n.parentElement)){for(let r of e)Ce(r);return}let t=o.cloneNode(!1);for(;e.at(-1).nextSibling;)t.append(e.at(-1).nextSibling);t.childNodes.length&&e.at(-1).append(t),n.after(...e),o.childNodes.length||o.remove()},Q=e=>{let o=Me(e),n=!!o.length&&o[0].previousElementSibling?.localName==="li"&&o.every(t=>[t,...t.querySelectorAll("li")].every(r=>Le(e,r)<8));return{listDepth:o.length?Le(e,o[0]):0,canIndent:n,canOutdent:!!o.length}},re=(e,o)=>{if(o!==1&&o!==-1)throw new TypeError("List indentation requires 1 or -1.");let n=Me(e);if(!n.length)throw new RangeError("Select consecutive items in the same list.");o===1&&!Q(e).canIndent||q(e,()=>{if(o===-1)oe(n);else{let t=n[0].parentElement,r=n[0].previousElementSibling,i=r.lastElementChild;He(i,t)||(i=t.cloneNode(!1),r.append(i)),i.append(...n)}J(e)})},Re=(e,o)=>{if(o!==!1&&o!=="bullet"&&o!=="ordered")throw new TypeError("Expected bullet, ordered or false.");let n=ke(P(e));if(n.some(t=>t.localName==="li"&&!C(t.parentElement)))throw new RangeError("A list item must belong to a list.");q(e,()=>{for(let t of n){if(!o){t.localName==="li"&&oe([t]);continue}let r=o==="bullet"?"ul":"ol";if(t.localName==="li"){if(t.parentElement.localName===r)continue;let i=document.createElement(r);t.parentElement.hasAttribute("style")&&i.setAttribute("style",t.parentElement.getAttribute("style")),Se(t,[i]),i.append(t)}else{let i=document.createElement(r),s=document.createElement("li");t.hasAttribute("style")&&s.setAttribute("style",t.getAttribute("style")),s.append(...t.childNodes),i.append(s),t.replaceWith(i)}}J(e)})},Ke=e=>!e.textContent?.trim()&&!e.querySelector("img,hr,ul,ol"),Ne=e=>{X(e).some(t=>t.textContent||t instanceof Element&&(t.matches("br,img,hr")||t.querySelector("br,img,hr")))||([...e.children].some(C)?e.prepend(Object.assign(document.createElement("p"),{innerHTML:"<br>"})):e.append(document.createElement("br")))},$e=(e,o)=>{let n=o.cloneRange();return n.selectNodeContents(e),n.setEnd(o.startContainer,o.startOffset),!n.toString()&&!n.cloneContents().querySelector("img,hr,br")},ce=(e,o)=>{let n=M(e);if(!n)return!1;let t=G(e,n.startContainer);return t?.localName!=="li"||!C(t.parentElement)||G(e,n.endContainer)!==t?!1:["insertParagraph","insertLineBreak"].includes(o)||o==="deleteContentBackward"&&n.collapsed&&$e(t,n)},de=(e,o)=>{let n=M(e),t=G(e,n.startContainer);if(o==="insertParagraph"){if(Ke(t)){q(e,()=>{let c=t.parentElement.parentElement;c?.localName==="li"&&C(c.parentElement)?oe([t]):Ce(t,!0)}),J(e);return}n.deleteContents();let r=n.cloneRange();r.selectNodeContents(t),r.setStart(n.startContainer,n.startOffset);let i=t.cloneNode(!1);i.append(r.extractContents()),t.after(i),Ne(t),Ne(i);let s=document.createTreeWalker(i,NodeFilter.SHOW_TEXT),a;do a=s.nextNode();while(a&&(!a.textContent||a.parentElement?.closest("li")!==i));if(a){let c=document.createRange();c.setStart(a,0),c.collapse(!0);let d=document.getSelection();d?.removeAllRanges(),d?.addRange(c)}else ne(i.querySelector("p,h1,h2,h3,h4,h5,h6,pre")??i)}else if(o==="insertLineBreak"){n.deleteContents();let r=document.createElement("br");n.insertNode(r),r.nextSibling||r.after(document.createElement("br")),n.setStartAfter(r),n.collapse(!0);let i=document.getSelection();i?.removeAllRanges(),i?.addRange(n)}else{let r=t.previousElementSibling;if(r&&r.localName!=="li")return;if(!r){q(e,()=>oe([t])),J(e);return}if(!X(r).some(g=>g.textContent||g instanceof Element&&(g.localName==="img"||g.querySelector("img"))))for(let g of[...r.querySelectorAll("br")])g.closest("li")===r&&g.remove();let i=document.createComment("mw-join"),a=X(r).at(-1),c=a instanceof HTMLElement&&/^(p|h[1-6]|blockquote|pre)$/.test(a.localName)?a:r;c===r?r.insertBefore(i,[...r.children].find(C)??null):c.append(i);let d=X(t);d[0]instanceof HTMLElement&&/^(p|h[1-6])$/.test(d[0].localName)&&d.splice(0,1,...d[0].childNodes),i.after(...d);for(let g of[...t.children].filter(C))r.append(g);t.remove(),J(e);let p=document.createRange();p.setStartBefore(i),p.collapse(!0),i.remove();let u=document.getSelection();u?.removeAllRanges(),u?.addRange(p)}};var K={bold:"strong",italic:"em",underline:"u",strike:"s",code:"code",subscript:"sub",superscript:"sup"},ze=new Set(["p","h1","h2","h3","h4","h5","h6","blockquote","pre","ul","ol","li","table","thead","tbody","tfoot","tr","td","th","caption","colgroup"]),De=(e,o,n,t,r)=>{let i=0,s=(a,c)=>{if(a.type==="text"){let u=i;i+=a.text.length;let g=Math.max(0,Math.min(a.text.length,o-u)),N=Math.max(g,Math.min(a.text.length,n-u));return[[0,g,!1],[g,N,!0],[N,a.text.length,!1]].flatMap(([f,h,E])=>{let y=a.text.slice(f,h);if(!y)return[];let T={type:"text",text:y};return[{node:E&&r&&!c?{type:"element",tag:t,attributes:{},children:[T]}:T,selected:!!E}]})}let d=a.children.flatMap(u=>s(u,c||r&&a.tag===t));if(ze.has(a.tag))return[{node:{...a,children:d.map(u=>u.node)},selected:!1}];if(!d.length)return[{node:a,selected:!1}];let p=[];for(let u of d){let g=p.at(-1);g?.selected===u.selected?g.children.push(u.node):p.push({selected:u.selected,children:[u.node]})}return p.flatMap(u=>a.tag===t&&!r&&u.selected?u.children.map(g=>({node:g,selected:!0})):[{node:{...a,children:u.children},selected:u.selected}])};return{version:1,children:e.children.flatMap(a=>s(a,!1)).map(a=>a.node)}},Oe=e=>e.nodeType===1?e:e.parentElement,ve=(e,o)=>{let n=Oe(o),t={};for(;n&&n!==e;){for(let[r,i]of Object.entries(K))n.localName===i&&(t[r]=!0);/^h[1-6]$/.test(n.localName)&&t.header===void 0&&(t.header=Number(n.localName[1])),n.localName==="blockquote"&&(t.blockquote=!0),n.localName==="pre"&&(t["code-block"]=!0),(n.localName==="ul"||n.localName==="ol")&&t.list===void 0&&(t.list=n.localName==="ul"?"bullet":"ordered"),n.localName==="a"&&t.link===void 0&&(t.link=n.getAttribute("href")),n instanceof HTMLElement&&n.style.textAlign&&t.align===void 0&&(t.align=n.style.textAlign),n=n.parentElement}return t},ue=e=>{let o=M(e);if(!o)return{};let n=ve(e,o.startContainer),t=new Set;if(!o.collapsed){let{index:r,length:i}=v(e),s=e.ownerDocument.createTreeWalker(e,NodeFilter.SHOW_TEXT),a=0,c,d=[];for(;c=s.nextNode();){let g=a+c.textContent.length;g>r&&a<r+i&&d.push(ve(e,c)),a=g}d.length&&(n=d[0]);let p=[...Object.keys(K),"header","list","blockquote","code-block","link","align"],u=(g,N)=>g[N]??(N==="align"?"left":N==="header"?0:!1);for(let g of p)d.some(N=>u(N,g)!==u(d[0],g))&&t.add(g)}return{...n,align:n.align??"left",mixed:[...t],...Q(e)}},me=(e,o,n)=>{let t=M(e);if(!t)return;let r=v(e);if(o==="list"){Re(e,n);return}if(o==="indent"){re(e,n);return}if(o==="clear"){if(n!==!0||!r.length)return;let a=R(e.innerHTML);for(let c of[...Object.values(K),"a","span"])a=De(a,r.index,r.index+r.length,c,!1);e.innerHTML=O(a),A(e,r.index,r.length);return}let i=K[o];if(i){if(t.collapsed)return;e.innerHTML=O(De(R(e.innerHTML),r.index,r.index+r.length,i,!!n)),A(e,r.index,r.length);return}if(o==="link"){if(n){if(typeof n=="string"&&!t.collapsed){let c=R("<a></a>").children[0];c.attributes.href=n;let d=document.createElement("div");d.innerHTML=O(Z({version:1,children:[c]}));let p=R(d.innerHTML).children[0];if(!p.attributes.href)return;let u=document.createElement("a");u.setAttribute("href",p.attributes.href),u.append(t.extractContents()),t.insertNode(u),t.selectNodeContents(u);let g=document.getSelection();g?.removeAllRanges(),g?.addRange(t)}}else{let a=Oe(t.startContainer)?.closest("a");a&&e.contains(a)&&a.replaceWith(...a.childNodes)}return}let s=P(e,t,!1);if(!s.length){let a=document.createElement("p");a.append(t.extractContents()),a.childNodes.length||a.append(document.createElement("br")),t.insertNode(a),s=[a]}q(e,()=>{for(let a of s){if(o==="align"&&["left","center","right","justify",!1].includes(n)){a.style.textAlign=n?String(n):"";continue}let c=o==="header"?Number.isInteger(n)&&Number(n)>=1&&Number(n)<=6?`h${n}`:"p":o==="blockquote"?n?"blockquote":"p":o==="code-block"?n?"pre":"p":void 0;if(c){let d=document.createElement(c);if(a.localName==="li"){let p=[...a.childNodes].filter(u=>!(u instanceof Element&&/^(ul|ol|p|h[1-6]|pre|blockquote)$/.test(u.localName)));d.append(...p),a.prepend(d)}else d.append(...a.childNodes),d.setAttribute("style",a.getAttribute("style")??""),a.replaceWith(d)}}})};var We=[{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}],_e=(e,o,n=We,t={})=>{let r=document.createElement("div");r.className="mw-toolbar",r.setAttribute("role","toolbar"),r.setAttribute("aria-label",t.label??"\u0424\u043E\u0440\u043C\u0430\u0442\u0438\u0440\u043E\u0432\u0430\u043D\u0438\u0435");let i,s=!1,a=0,c=[],d=n.map(f=>{let h=document.createElement("button");h.type="button",h.textContent=f.text,h.title=f.label,h.setAttribute("aria-label",f.label);let E=T=>T.preventDefault(),y=()=>{if(!(s||h.disabled||o.isReadOnly())&&(o.focus(),i&&I(o.surface,i),!(f.enabled&&!f.enabled(o)))){if(f.run)f.run(o);else if(f.format){let T=o.getFormats(),H=T.mixed?.includes(f.format);o.format(f.format,!H&&T[f.format]===(f.value??!0)?!1:f.value??!0)}p()}};return h.addEventListener("mousedown",E),h.addEventListener("click",y),c.push(()=>{h.removeEventListener("mousedown",E),h.removeEventListener("click",y)}),r.append(h),h}),p=()=>{if(s)return;i=U(o.surface)??i;let f=o.getFormats();d.forEach((h,E)=>{let y=n[E];h.disabled=o.isReadOnly()||(y.enabled?!y.enabled(o):!1),y.format&&!["indent","clear"].includes(y.format)&&h.setAttribute("aria-pressed",f.mixed?.includes(y.format)?"mixed":String(f[y.format]===(y.value??!0)))}),(d[a]?.disabled||!d[a])&&(a=d.findIndex(h=>!h.disabled)),d.forEach((h,E)=>{h.tabIndex=E===a?0:-1})},u=f=>{let h=d.filter(H=>!H.disabled);if(!h.length)return;let E=h.indexOf(document.activeElement);if(E<0||f.ctrlKey||f.metaKey||f.altKey)return;if(f.key==="Escape"){f.preventDefault(),o.focus(),i&&I(o.surface,i);return}let y=getComputedStyle(r).direction==="rtl"?-1:1,T=f.key==="Home"?0:f.key==="End"?h.length-1:f.key==="ArrowRight"?(E+y+h.length)%h.length:f.key==="ArrowLeft"?(E-y+h.length)%h.length:-1;T>=0&&(f.preventDefault(),a=d.indexOf(h[T]),p(),h[T].focus())};r.addEventListener("keydown",u);let g=o.subscribe(f=>{f.source==="api"&&(i=void 0),p()}),N=o.onSelectionChange(p);return e.append(r),p(),()=>{if(!s){s=!0,g(),N(),r.removeEventListener("keydown",u);for(let f of c)f();r.remove()}}};var se=e=>{let o=!1;e.childNodes.length||(e.innerHTML="<p><br></p>",o=!0);let n;for(let t of[...e.childNodes])t.nodeType===3||t.nodeType===1&&/^(strong|em|u|s|a|span|code|img|br|sub|sup)$/.test(t.localName)?(n||(n=document.createElement("p"),e.insertBefore(n,t)),n.append(t),o=!0):n=void 0;return e.lastElementChild?.localName==="table"&&e.append(Object.assign(document.createElement("p"),{innerHTML:"<br>"})),e.dataset.empty=String(!e.textContent&&!e.querySelector("table,img,hr")),o},Ue=(e,o)=>{let n=M(e);if(!n)return;let t=ee(R(o));if(!t.childNodes.length)return;n.deleteContents();let i=(n.startContainer.nodeType===1?n.startContainer:n.startContainer.parentElement)?.closest("p,h1,h2,h3,h4,h5,h6,li,blockquote,pre");if(t.childNodes.length===1&&t.firstChild instanceof HTMLParagraphElement&&i){let p=t.firstChild;t.replaceChildren(...p.childNodes)}let s=[...t.childNodes].some(p=>p instanceof HTMLElement&&/^(p|h[1-6]|ul|ol|table|blockquote|pre)$/.test(p.localName)),a=t.lastChild;if(s&&i&&e.contains(i)){let p=document.createRange();p.selectNodeContents(i),p.setStart(n.startContainer,n.startOffset);let u=i.cloneNode(!1);u.append(p.extractContents()),i.after(t),(u.textContent||u.querySelector("img,br"))&&a.after(u),!i.textContent&&!i.querySelector("img")&&i.remove()}else n.insertNode(t);let c=document.createRange();c.setStartAfter(a),c.collapse(!0);let d=document.getSelection();d?.removeAllRanges(),d?.addRange(c)},it=(e,o={})=>{if(e.childNodes.length)throw new Error("Editor host must be empty. Pass initial HTML through value.");let n=o.plugins??[];if(new Set(n.map(l=>l.name)).size!==n.length)throw new Error("Duplicate editor plugin.");let t=o.historyLimit??100;if(!Number.isInteger(t)||t<1||t>1e4)throw new RangeError("historyLimit must be an integer from 1 to 10000.");let r=R(o.value??""),i=document.createElement("div");i.className="mw-editor";let s=document.createElement("div");s.className="mw-content",s.setAttribute("role","textbox"),s.setAttribute("aria-multiline","true"),s.setAttribute("aria-label",o.label??"\u0422\u0435\u043A\u0441\u0442\u043E\u0432\u044B\u0439 \u0440\u0435\u0434\u0430\u043A\u0442\u043E\u0440"),s.dataset.placeholder=o.placeholder??"\u041D\u0430\u0447\u043D\u0438\u0442\u0435 \u043F\u0438\u0441\u0430\u0442\u044C\u2026",i.append(s),e.append(i),s.append(ee(r)),se(s);let a=!1,c=o.readOnly??!1,d=!1,p,u,g=0,N="",f={},h,E=()=>{f={},h=void 0},y=()=>{let l=v(s);return l?.length===0&&l.index===h},T=[],H=[],$=new Set,V=new Set,z=new Map,Y=[];o.onChange&&$.add(o.onChange);let L=()=>{if(a)throw new Error("Editor has been destroyed.")},D=()=>({html:te(s.innerHTML),selection:U(s)}),S=D(),W=S.selection,j=()=>{if(a)return;v(s)&&!y()&&E();let l=U(s);l&&(W=l,S.selection=l);for(let m of V)m()},le=l=>{let m={html:x.getHTML(),text:x.getText(),source:l};for(let b of[...$])b(m);j()},ie=(l,m="")=>{let b=v(s);se(s)&&b&&A(s,b.index,b.length);let w=D();if(w.html===l.html){S=w;return}let k=Date.now();m===N&&["insertText","deleteContentBackward","deleteContentForward"].includes(m)&&k-g<600&&l.selection&&S.selection&&JSON.stringify(l.selection)===JSON.stringify(S.selection)||(T.push(l),T.length>t&&T.shift()),H.length=0,S=w,g=m?k:0,N=m,le("user")},fe=l=>{E(),s.innerHTML=l.html,se(s),s.focus({preventScroll:!0}),I(s,l.selection),S=D(),W=S.selection,g=0,le("user")},_=(l,m="")=>{if(L(),c)return;x.focus();let b=D(),w=[...T],k=[...H];try{l(s),ie(b,m)}catch(ae){throw s.innerHTML=b.html,I(s,b.selection),S=D(),T.splice(0,T.length,...w),H.splice(0,H.length,...k),ae}},x={element:i,surface:s,getHTML:()=>(L(),te(s.innerHTML)),getText:()=>(L(),s.innerText),getJSON:()=>(L(),R(s.innerHTML)),setHTML:l=>{L();let m=O(R(l));m!==x.getHTML()&&(E(),s.innerHTML=m,se(s),T.length=0,H.length=0,g=0,W=void 0,S=D(),le("api"))},setJSON:l=>{L();let m=Z(l);x.setHTML(O(m))},getSelection:()=>(L(),v(s)),setSelection:(l,m=0)=>{L(),A(s,l,m),j()},getFormats:()=>(L(),{...ue(s),...y()?f:{}}),setReadOnly:l=>{L(),c=l,s.contentEditable=String(!l),s.setAttribute("aria-readonly",String(l)),i.dataset.readonly=String(l),j()},isReadOnly:()=>(L(),c),format:(l,m)=>{if(L(),c)return;x.focus();let b=v(s);if(b?.length===0&&Object.hasOwn(K,l)){y()||E(),h=b.index,f[l]=!!m,j();return}E(),x.transact(()=>me(s,l,m))},insertHTML:l=>x.transact(()=>Ue(s,l)),focus:()=>{L(),s.focus({preventScroll:!0}),M(s)||(W?I(s,W):ne(s.firstElementChild??s,!0))},undo:()=>{if(L(),c)return;let l=T.pop();l&&(H.push(D()),fe(l))},redo:()=>{if(L(),c)return;let l=H.pop();l&&(T.push(D()),fe(l))},canUndo:()=>(L(),T.length>0),canRedo:()=>(L(),H.length>0),transact:l=>_(l),providePlugin:(l,m)=>{if(L(),z.has(l))throw new Error(`Plugin API already registered: ${l}`);return z.set(l,m),()=>{z.delete(l)}},getPlugin:l=>(L(),z.get(l)),subscribe:l=>(L(),$.add(l),()=>{$.delete(l)}),onSelectionChange:l=>(L(),V.add(l),()=>{V.delete(l)}),destroy:()=>{if(a)return;a=!0;let l=[];for(let m of Y.reverse())try{m()}catch(b){l.push(b)}if($.clear(),V.clear(),z.clear(),T.length=0,H.length=0,i.remove(),l.length)throw new AggregateError(l,"Editor cleanup failed.")}},B=(l,m)=>{s.addEventListener(l,m),Y.push(()=>s.removeEventListener(l,m))};B("beforeinput",l=>{if(c){l.preventDefault();return}if(l.inputType==="historyUndo"||l.inputType==="historyRedo"){l.preventDefault(),l.inputType==="historyUndo"?x.undo():x.redo();return}if(!d&&!l.isComposing&&ce(s,l.inputType)){l.preventDefault(),E(),u=void 0,_(()=>de(s,l.inputType));return}if(l.inputType==="insertText"&&l.data&&!d&&!l.isComposing&&y()&&Object.keys(f).length){l.preventDefault();let m=v(s).index,b=l.data,w={...f};_(()=>{let k=M(s),F=(k.startContainer instanceof Element?k.startContainer:k.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(),k.selectNodeContents(F),k.collapse(!0)),k.insertNode(document.createTextNode(b)),A(s,m,b.length);for(let[pe,ge]of Object.entries(w))!!ue(s)[pe]!==ge&&me(s,pe,ge);A(s,m+b.length),h=m+b.length},"insertText"),u=void 0;return}u=D()}),B("input",l=>{let m=l;if(c){s.innerHTML=S.html;return}d||m.isComposing||(ie(u??S,m.inputType),u=void 0)}),B("compositionstart",()=>{E(),d=!0,p=D()}),B("compositionend",()=>{d=!1,p&&ie(p),p=void 0,u=void 0}),B("paste",l=>{if(l.preventDefault(),c||!l.clipboardData)return;x.focus();let m=l.clipboardData.getData("text/html");if(m)x.insertHTML(m);else{let b=l.clipboardData.getData("text/plain"),w=document.createElement("div");w.textContent=b,x.insertHTML(w.innerHTML.replace(/\r?\n/g,"<br>"))}}),B("drop",l=>{l.preventDefault()}),B("keydown",l=>{if(!d&&!l.isComposing&&!c&&!l.ctrlKey&&!l.metaKey&&!l.altKey&&(l.key==="Enter"||l.key==="Backspace")){let w=l.key==="Backspace"?"deleteContentBackward":l.shiftKey?"insertLineBreak":"insertParagraph";if(ce(s,w)){l.preventDefault(),E(),u=void 0,_(()=>de(s,w));return}}if(!d&&!l.isComposing&&!c&&l.key==="Tab"&&!l.ctrlKey&&!l.metaKey&&!l.altKey){let w=P(s);if(w.length&&w.every(k=>k.localName==="li"&&!k.closest("td,th"))&&Q(s).canOutdent){l.preventDefault(),E(),_(()=>re(s,l.shiftKey?-1:1));return}}if(d||l.isComposing||c||!(l.ctrlKey||l.metaKey)||l.altKey)return;let m=l.key.toLowerCase();(m==="z"||m==="y")&&(l.preventDefault(),m==="y"||l.shiftKey?x.redo():x.undo());let b={b:"bold",i:"italic",u:"underline"}[m];b&&(l.preventDefault(),x.format(b,x.getFormats().mixed?.includes(b)||!x.getFormats()[b]))}),document.addEventListener("selectionchange",j),Y.push(()=>document.removeEventListener("selectionchange",j));try{x.setReadOnly(c);for(let l of n){let m=l.setup(x);m&&Y.push(m)}return x}catch(l){throw x.destroy(),l}};export{it as createEditor,_e as createToolbar,te 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/model.ts", "../src/selection.ts", "../src/formatting.ts", "../src/index.ts"],
4
- "sourcesContent": ["/** 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', 'table', 'caption', 'colgroup', 'col', 'thead', 'tbody', 'tfoot', 'tr', 'td', 'th'] as const;\nexport type DocumentTag = typeof documentTags[number];\nexport interface TextNode { type: 'text'; text: string; }\nexport interface ElementNode { type: 'element'; tag: DocumentTag; attributes: Record<string, string>; children: DocumentNode[]; }\nexport type DocumentNode = TextNode | ElementNode;\nexport interface EditorDocument { version: 1; children: DocumentNode[]; }\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 = 100_000;\nconst MAX_DEPTH = 100;\n\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};\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};\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 === 'th' && key === 'scope' && ['row', 'col', 'rowgroup', 'colgroup'].includes(value))\n output[key] = value;\n }\n return output;\n};\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};\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};\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};\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};\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", "export interface TextSelection { index: number; length: number; }\nexport interface SelectionBookmark { start: number[]; startOffset: number; end: number[]; endOffset: number; backward: boolean; }\n\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", "import type { DocumentNode, DocumentTag, EditorDocument, ElementNode } from './model.js';\nimport { documentHTML, parseHTML, validateDocument } from './model.js';\nimport { activeRange, readTextSelection, selectText } from './selection.js';\n\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']);\ninterface Piece { node: DocumentNode; selected: boolean; }\n\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};\n\nconst closestElement = (node: Node): Element | null => { return node.nodeType === 1 ? node as Element : node.parentElement; };\nexport const readFormats = (root: HTMLElement): Record<string, unknown> => {\n const range = activeRange(root);\n if (!range)\n return {};\n let element = closestElement(range.startContainer);\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))\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')\n formats.list = element.localName === 'ul' ? 'bullet' : 'ordered';\n if (element.localName === 'a')\n formats.link = element.getAttribute('href');\n element = element.parentElement;\n }\n return formats;\n};\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 const tag = inlineFormats[name];\n if (tag) {\n if (range.collapsed) 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 if (!value) {\n const link = closestElement(range.startContainer)?.closest('a');\n if (link && root.contains(link))\n link.replaceWith(...link.childNodes);\n }\n else if (typeof value === 'string' && !range.collapsed) {\n const template = parseHTML(`<a></a>`);\n const link = template.children[0] as ElementNode;\n link.attributes.href = value;\n // Use the shared validator instead of assigning an unchecked URL to the live document.\n const holder = document.createElement('div');\n holder.innerHTML = documentHTML(validateDocument({ version: 1, children: [link] }));\n const clean = parseHTML(holder.innerHTML).children[0] as ElementNode;\n if (!clean.attributes.href)\n return;\n const element = document.createElement('a');\n element.setAttribute('href', clean.attributes.href);\n element.append(range.extractContents());\n range.insertNode(element);\n range.selectNodeContents(element);\n const native = document.getSelection();\n native?.removeAllRanges();\n native?.addRange(range);\n }\n return;\n }\n const candidates = [...root.querySelectorAll<HTMLElement>('p,h1,h2,h3,h4,h5,h6,blockquote,pre,li')];\n let blocks = candidates.filter((element) => {\n if (element.querySelector('p,h1,h2,h3,h4,h5,h6,blockquote,pre,li'))\n return false;\n if (range.collapsed)\n return element.contains(range.startContainer);\n return range.intersectsNode(element);\n });\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 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 if (name === 'list') {\n if (!value && block.localName === 'li') {\n const list = block.parentElement!;\n const paragraph = document.createElement('p');\n paragraph.append(...block.childNodes);\n const trailing = list.cloneNode(false) as HTMLElement;\n while (block.nextSibling)\n trailing.append(block.nextSibling);\n block.remove();\n list.after(paragraph);\n if (trailing.childNodes.length)\n paragraph.after(trailing);\n if (!list.childNodes.length)\n list.remove();\n }\n else if (value === 'bullet' || value === 'ordered') {\n if (block.localName === 'li') {\n const parent = block.parentElement!;\n const replacement = document.createElement(value === 'bullet' ? 'ul' : 'ol');\n replacement.append(...parent.childNodes);\n parent.replaceWith(replacement);\n }\n else {\n const list = document.createElement(value === 'bullet' ? 'ul' : 'ol');\n const item = document.createElement('li');\n item.append(...block.childNodes);\n list.append(item);\n block.replaceWith(list);\n }\n }\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 replacement.append(...block.childNodes);\n block.replaceWith(replacement);\n }\n }\n selectText(root, selection.index, selection.length);\n};\n", "import { documentHTML, parseHTML, renderDocument, sanitizeHTML, validateDocument } from './model.js';\nimport type { EditorDocument } from './model.js';\nimport { activeRange, bookmark, placeCaret, readTextSelection, restoreBookmark, selectText } from './selection.js';\nimport type { SelectionBookmark, TextSelection } from './selection.js';\nimport { applyFormat, inlineFormats, readFormats } from './formatting.js';\nexport { sanitizeHTML } from './model.js';\nexport type { EditorDocument, DocumentNode, ElementNode, TextNode, DocumentTag } from './model.js';\nexport type { TextSelection, SelectionBookmark } from './selection.js';\n\nexport interface EditorChange { html: string; text: string; source: 'user' | 'api'; }\nexport interface EditorPlugin { name: string; setup(editor: Editor): void | (() => void); }\nexport interface EditorOptions {\n value?: string;\n placeholder?: string;\n readOnly?: boolean;\n label?: string;\n plugins?: EditorPlugin[];\n onChange?: (change: EditorChange) => void;\n historyLimit?: number;\n}\nexport interface Editor {\n readonly element: HTMLElement;\n readonly surface: HTMLElement;\n getHTML(): string;\n getText(): string;\n getJSON(): EditorDocument;\n setHTML(html: string): void;\n setJSON(value: EditorDocument): void;\n getSelection(): TextSelection | undefined;\n setSelection(index: number, length?: number): void;\n getFormats(): Record<string, unknown>;\n setReadOnly(value: boolean): void;\n isReadOnly(): boolean;\n format(name: string, value: unknown): void;\n insertHTML(html: string): void;\n focus(): void;\n undo(): void;\n redo(): void;\n canUndo(): boolean;\n canRedo(): boolean;\n /** Execute a plugin edit as one undoable operation. Read-only mode blocks it. */\n transact(mutate: (surface: HTMLElement) => void): void;\n providePlugin<T>(name: string, api: T): () => void;\n getPlugin<T>(name: string): T | undefined;\n subscribe(listener: (change: EditorChange) => void): () => void;\n onSelectionChange(listener: () => void): () => void;\n destroy(): void;\n}\ninterface Snapshot { html: string; selection: SelectionBookmark | undefined; }\n\nconst ensureDocument = (root: HTMLElement): boolean => {\n let normalized = false;\n if (!root.childNodes.length) { root.innerHTML = '<p><br></p>'; normalized = true; }\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 (root.lastElementChild?.localName === 'table')\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};\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|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};\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, 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 listeners = new Set<(change: EditorChange) => void>();\n const selectionListeners = new Set<() => void>();\n const pluginAPIs = new Map<string, unknown>();\n const disposers: (() => void)[] = [];\n if (options.onChange)\n listeners.add(options.onChange);\n const assertActive = () => {\n if (destroyed)\n throw new Error('Editor has been destroyed.');\n };\n const capture = (): Snapshot => ({ html: sanitizeHTML(surface.innerHTML), selection: bookmark(surface) });\n let current = capture();\n let lastSelection = current.selection;\n const notifySelection = () => {\n if (destroyed)\n return;\n if (readTextSelection(surface) && !typingAtCaret()) clearTyping();\n const saved = bookmark(surface);\n if (saved) {\n lastSelection = saved;\n current.selection = saved;\n }\n for (const listener of selectionListeners)\n listener();\n };\n const emit = (source: EditorChange['source']) => {\n const change: EditorChange = { html: editor.getHTML(), text: editor.getText(), source };\n for (const listener of [...listeners])\n listener(change);\n notifySelection();\n };\n const commit = (before: Snapshot, inputType = '') => {\n const selection = readTextSelection(surface);\n if (ensureDocument(surface) && selection) selectText(surface, selection.index, selection.length);\n const after = capture();\n if (after.html === before.html) {\n current = after;\n return;\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 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 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 editor.focus();\n const before = capture();\n const previousUndo = [...undoStack];\n const previousRedo = [...redoStack];\n try {\n mutate(surface);\n commit(before, inputType);\n }\n catch (error) {\n surface.innerHTML = before.html;\n restoreBookmark(surface, before.selection);\n current = capture();\n undoStack.splice(0, undoStack.length, ...previousUndo);\n redoStack.splice(0, redoStack.length, ...previousRedo);\n throw error;\n }\n };\n const editor: Editor = {\n element: container, surface,\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 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 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 readOnly = value;\n surface.contentEditable = String(!value);\n surface.setAttribute('aria-readonly', String(value));\n container.dataset.readonly = String(value);\n notifySelection();\n },\n isReadOnly: () => { assertActive(); return readOnly; },\n format: (name, value) => {\n assertActive(); if (readOnly) return; editor.focus();\n const selection = readTextSelection(surface);\n if (selection?.length === 0 && Object.hasOwn(inlineFormats, name)) {\n if (!typingAtCaret()) clearTyping();\n typingOffset = selection.index; typingOverrides[name] = Boolean(value); notifySelection();\n return;\n }\n clearTyping(); editor.transact(() => applyFormat(surface, name, value));\n },\n insertHTML: (html) => editor.transact(() => insertFragment(surface, html)),\n focus: () => {\n assertActive(); surface.focus({ preventScroll: true }); 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(); if (readOnly)\n return; const previous = undoStack.pop(); if (previous) {\n redoStack.push(capture());\n restore(previous);\n }\n },\n redo: () => {\n assertActive(); if (readOnly)\n return; const next = redoStack.pop(); 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(); listeners.add(listener); return () => { listeners.delete(listener); }; },\n onSelectionChange: (listener) => { assertActive(); selectionListeners.add(listener); return () => { selectionListeners.delete(listener); }; },\n destroy: () => {\n if (destroyed)\n return;\n destroyed = true;\n const failures: unknown[] = [];\n for (const dispose of disposers.reverse()) {\n try {\n dispose();\n }\n catch (error) {\n failures.push(error);\n }\n }\n listeners.clear();\n selectionListeners.clear();\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 (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(); range.selectNodeContents(block); 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)) if (Boolean(readFormats(surface)[name]) !== enabled) 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; if (readOnly) {\n surface.innerHTML = current.html;\n return;\n } if (composing || event.isComposing)\n return; commit(pendingInput ?? current, event.inputType); pendingInput = undefined;\n });\n listen('compositionstart', () => { clearTyping(); composing = true; compositionStart = capture(); });\n listen('compositionend', () => {\n composing = false; if (compositionStart)\n commit(compositionStart); compositionStart = undefined; pendingInput = undefined;\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)\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()[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\nexport interface ToolbarAction { label: string; text: string; format?: string; value?: unknown; run?: (editor: Editor) => void; }\nconst defaultActions: ToolbarAction[] = [\n { label: '\u041E\u0442\u043C\u0435\u043D\u0438\u0442\u044C', text: '\u21B6', run: (editor) => editor.undo() },\n { label: '\u041F\u043E\u0432\u0442\u043E\u0440\u0438\u0442\u044C', text: '\u21B7', run: (editor) => editor.redo() },\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: '\u0426\u0438\u0442\u0430\u0442\u0430', text: '\u275D', format: 'blockquote' },\n];\nexport const createToolbar = (host: HTMLElement, editor: Editor, actions = defaultActions): () => void => {\n const toolbar = document.createElement('div');\n toolbar.className = 'mw-toolbar';\n toolbar.setAttribute('role', 'toolbar');\n toolbar.setAttribute('aria-label', '\u0424\u043E\u0440\u043C\u0430\u0442\u0438\u0440\u043E\u0432\u0430\u043D\u0438\u0435');\n let savedSelection: TextSelection | undefined;\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 button.addEventListener('mousedown', (event) => event.preventDefault());\n button.addEventListener('click', () => {\n if (editor.isReadOnly())\n return;\n if (savedSelection)\n editor.setSelection(savedSelection.index, savedSelection.length);\n else\n editor.focus();\n if (action.run)\n action.run(editor);\n else if (action.format)\n editor.format(action.format, editor.getFormats()[action.format] === (action.value ?? true) ? false : action.value ?? true);\n update();\n });\n toolbar.append(button);\n return button;\n });\n const update = () => {\n savedSelection = editor.getSelection() ?? savedSelection;\n const formats = editor.getFormats();\n buttons.forEach((button, index) => {\n button.disabled = editor.isReadOnly();\n const action = actions[index];\n if (action.format)\n button.setAttribute('aria-pressed', String(formats[action.format] === (action.value ?? true)));\n });\n };\n const unsubscribe = editor.subscribe(update);\n const unselect = editor.onSelectionChange(update);\n host.append(toolbar);\n update();\n return () => { unsubscribe(); unselect(); toolbar.remove(); };\n};\n"],
5
- "mappings": "AACO,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,QAAS,UAAW,WAAY,MAAO,QAAS,QAAS,QAAS,KAAM,KAAM,IAAI,EAMzQC,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,IAEZC,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,C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TA,EAAO,IAAIhD,CAAM,EACVgD,EAAO,QACdhD,EAAO,OAAOgD,EAAO,OAAQhD,EAAO,WAAW,EAAEgD,EAAO,MAAM,KAAOA,EAAO,OAAS,IAAQ,GAAQA,EAAO,OAAS,EAAI,EAC3HE,EAAO,EACT,CAAC,EACDL,EAAQ,OAAOI,CAAM,EACdA,CACT,CAAC,EACKC,EAAS,IAAM,CACnBJ,EAAiB9C,EAAO,aAAa,GAAK8C,EAC1C,IAAMK,EAAUnD,EAAO,WAAW,EAClC+C,EAAQ,QAAQ,CAACE,EAAQ7B,IAAU,CACjC6B,EAAO,SAAWjD,EAAO,WAAW,EACpC,IAAMgD,EAASJ,EAAQxB,CAAK,EACxB4B,EAAO,QACTC,EAAO,aAAa,eAAgB,OAAOE,EAAQH,EAAO,MAAM,KAAOA,EAAO,OAAS,GAAK,CAAC,CACjG,CAAC,CACH,EACMI,EAAcpD,EAAO,UAAUkD,CAAM,EACrCG,EAAWrD,EAAO,kBAAkBkD,CAAM,EAChD,OAAAxF,EAAK,OAAOmF,CAAO,EACnBK,EAAO,EACA,IAAM,CAAEE,EAAY,EAAGC,EAAS,EAAGR,EAAQ,OAAO,CAAG,CAC9D",
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", "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", "inlineFormats", "blockTags", "inlineDocument", "value", "from", "to", "tag", "enabled", "position", "visit", "node", "inherited", "start", "left", "right", "begin", "end", "selected", "text", "leaf", "children", "child", "piece", "groups", "last", "group", "closestElement", "readFormats", "root", "range", "activeRange", "element", "formats", "name", "applyFormat", "selection", "readTextSelection", "documentHTML", "parseHTML", "selectText", "link", "holder", "validateDocument", "clean", "native", "blocks", "paragraph", "block", "list", "trailing", "parent", "replacement", "item", "nextTag", "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", "pendingInput", "lastInputTime", "lastInputType", "typingOverrides", "typingOffset", "clearTyping", "typingAtCaret", "readTextSelection", "undoStack", "redoStack", "listeners", "selectionListeners", "pluginAPIs", "disposers", "assertActive", "capture", "sanitizeHTML", "bookmark", "current", "lastSelection", "notifySelection", "saved", "listener", "emit", "source", "change", "editor", "commit", "before", "inputType", "selectText", "after", "now", "restore", "snapshot", "restoreBookmark", "runTransaction", "mutate", "previousUndo", "previousRedo", "error", "content", "documentHTML", "value", "validated", "validateDocument", "index", "length", "readFormats", "name", "inlineFormats", "applyFormat", "placeCaret", "previous", "api", "failures", "dispose", "listen", "type", "handler", "event", "start", "text", "overrides", "enabled", "nativeEvent", "holder", "key", "defaultActions", "createToolbar", "actions", "toolbar", "savedSelection", "buttons", "action", "button", "update", "formats", "unsubscribe", "unselect"]
3
+ "sources": ["../src/model.ts", "../src/selection.ts", "../src/lists.ts", "../src/formatting.ts", "../src/toolbar.ts", "../src/index.ts"],
4
+ "sourcesContent": ["/** 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', 'table', 'caption', 'colgroup', 'col', 'thead', 'tbody', 'tfoot', 'tr', 'td', 'th'] as const;\nexport type DocumentTag = typeof documentTags[number];\nexport interface TextNode { type: 'text'; text: string; }\nexport interface ElementNode { type: 'element'; tag: DocumentTag; attributes: Record<string, string>; children: DocumentNode[]; }\nexport type DocumentNode = TextNode | ElementNode;\nexport interface EditorDocument { version: 1; children: DocumentNode[]; }\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 = 100_000;\nconst MAX_DEPTH = 100;\n\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};\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};\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 === 'th' && key === 'scope' && ['row', 'col', 'rowgroup', 'colgroup'].includes(value))\n output[key] = value;\n }\n return output;\n};\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};\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};\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};\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};\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", "export interface TextSelection { index: number; length: number; }\nexport interface SelectionBookmark { start: number[]; startOffset: number; end: number[]; endOffset: number; backward: boolean; }\n\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\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) 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) { const tail = range.cloneRange(); tail.collapse(false); tail.insertNode(end); }\n const head = range.cloneRange(); head.collapse(true); head.insertNode(start);\n try {\n mutate();\n if (root.contains(start) && (!end || root.contains(end))) {\n const next = root.ownerDocument.createRange(); next.setStartBefore(start);\n if (end) next.setEndBefore(end); else next.collapse(true);\n start.remove(); end?.remove(); root.normalize();\n if (backward) native.setBaseAndExtent(next.endContainer, next.endOffset, next.startContainer, next.startOffset);\n else { native.removeAllRanges(); native.addRange(next); }\n }\n } finally { start.remove(); end?.remove(); }\n};\n", "import { activeRange, placeCaret, preserveRange } from './selection.js';\n\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(); if (node.nodeType === 3) content.selectNodeContents(node); else content.selectNode(node);\n const start = range.cloneRange(); start.collapse(true);\n const end = range.cloneRange(); end.collapse(false);\n const first = content.cloneRange(); first.collapse(true);\n const last = content.cloneRange(); 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) return [];\n if (range.collapsed) { const block = blockAt(root, range.startContainer, preferItems); return block ? [block] : []; }\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))) continue;\n if (touches(range, node)) { const block = blockAt(root, node, preferItems); if (block) found.add(block); }\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))) return [];\n const parent = items[0].parentElement;\n if (items.some((item) => item.parentElement !== parent)) return [];\n const siblings = [...parent!.children];\n if (siblings.indexOf(items.at(-1)!) - siblings.indexOf(items[0]) + 1 !== items.length) return [];\n return items as HTMLLIElement[];\n};\nconst depth = (root: HTMLElement, item: HTMLElement): number => { let result = 0; let parent: Element | null = item.parentElement; while (parent && parent !== root) { if (isList(parent)) result++; parent = parent.parentElement; } return result; };\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)) continue;\n const previous = list.previousSibling;\n if (previous instanceof Element && compatible(previous, list)) { previous.append(...list.childNodes); list.remove(); }\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) tail.append(item.nextSibling);\n item.remove(); list.after(...replacement, ...(tail.childNodes.length ? [tail] : []));\n if (!list.childNodes.length) 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 = () => { const node = document.createElement('p'); if (item.hasAttribute('style')) node.setAttribute('style', item.getAttribute('style')!); return node; };\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)) { paragraph.append(...node.childNodes); }\n else if (node instanceof HTMLElement && /^(p|h[1-6]|blockquote|pre)$/.test(node.localName)) {\n if (paragraph.childNodes.length) output.push(paragraph);\n paragraph = paragraphNode(); output.push(node);\n } else paragraph.append(node);\n }\n if (paragraph.childNodes.length || !output.length) { if (!paragraph.childNodes.length) paragraph.append(document.createElement('br')); output.push(paragraph); }\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)) { for (const item of items) unwrapRoot(item); return; }\n const trailing = list.cloneNode(false) as HTMLElement;\n while (items.at(-1)!.nextSibling) trailing.append(items.at(-1)!.nextSibling!);\n if (trailing.childNodes.length) items.at(-1)!.append(trailing);\n owner.after(...items);\n if (!list.childNodes.length) 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) throw new TypeError('List indentation requires 1 or -1.');\n const items = itemRange(root);\n if (!items.length) throw new RangeError('Select consecutive items in the same list.');\n if (direction === 1 && !listState(root).canIndent) return;\n preserveRange(root, () => {\n if (direction === -1) lift(items);\n else {\n const list = items[0].parentElement!; const previous = items[0].previousElementSibling!;\n let nested = previous.lastElementChild;\n if (!compatible(nested, list)) { nested = list.cloneNode(false) as HTMLElement; previous.append(nested); }\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') 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))) throw new RangeError('A list item must belong to a list.');\n preserveRange(root, () => {\n for (const block of selected) {\n if (!value) { if (block.localName === 'li') lift([block as HTMLLIElement]); continue; }\n const tag = value === 'bullet' ? 'ul' : 'ol';\n if (block.localName === 'li') {\n if (block.parentElement!.localName === tag) continue;\n const list = document.createElement(tag);\n if (block.parentElement!.hasAttribute('style')) list.setAttribute('style', block.parentElement!.getAttribute('style')!);\n splitAround(block as HTMLLIElement, [list]); list.append(block);\n } else {\n const list = document.createElement(tag); const item = document.createElement('li');\n if (block.hasAttribute('style')) item.setAttribute('style', block.getAttribute('style')!);\n item.append(...block.childNodes); list.append(item); 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)) item.prepend(Object.assign(document.createElement('p'), { innerHTML: '<br>' }));\n else item.append(document.createElement('br'));\n }\n};\n\nconst atStart = (item: HTMLElement, range: Range) => {\n const prefix = range.cloneRange(); prefix.selectNodeContents(item); 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); if (!range) return false;\n const item = blockAt(root, range.startContainer);\n if (item?.localName !== 'li' || !isList(item.parentElement) || blockAt(root, range.endContainer) !== item) 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)!; const item = blockAt(root, range.startContainer) as HTMLLIElement;\n if (inputType === 'insertParagraph') {\n if (empty(item)) { preserveRange(root, () => { const owner = item.parentElement!.parentElement; if (owner?.localName === 'li' && isList(owner.parentElement)) lift([item]); else unwrapRoot(item, true); }); joinLists(root); return; }\n range.deleteContents();\n const tail = range.cloneRange(); tail.selectNodeContents(item); tail.setStart(range.startContainer, range.startOffset);\n const next = item.cloneNode(false) as HTMLLIElement; next.append(tail.extractContents()); item.after(next);\n placeholder(item); placeholder(next);\n const walker = document.createTreeWalker(next, NodeFilter.SHOW_TEXT); let first: Node | null;\n do { first = walker.nextNode(); } while (first && (!first.textContent || first.parentElement?.closest('li') !== next));\n if (first) { const caret = document.createRange(); caret.setStart(first, 0); caret.collapse(true); const selection = document.getSelection(); selection?.removeAllRanges(); selection?.addRange(caret); }\n else placeCaret(next.querySelector<HTMLElement>('p,h1,h2,h3,h4,h5,h6,pre') ?? next);\n } else if (inputType === 'insertLineBreak') {\n range.deleteContents(); const br = document.createElement('br'); range.insertNode(br);\n if (!br.nextSibling) br.after(document.createElement('br'));\n range.setStartAfter(br); range.collapse(true); const selection = document.getSelection(); selection?.removeAllRanges(); selection?.addRange(range);\n } else {\n const previous = item.previousElementSibling as HTMLLIElement | null;\n if (previous && previous.localName !== 'li') return;\n if (!previous) { preserveRange(root, () => lift([item])); joinLists(root); return; }\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')]) if (br.closest('li') === previous) br.remove();\n }\n const marker = document.createComment('mw-join'); 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) previous.insertBefore(marker, [...previous.children].find(isList) ?? null); else target.append(marker);\n const content = ownContent(item);\n if (content[0] instanceof HTMLElement && /^(p|h[1-6])$/.test(content[0].localName)) content.splice(0, 1, ...content[0].childNodes);\n marker.after(...content);\n for (const nested of [...item.children].filter(isList)) previous.append(nested);\n item.remove(); joinLists(root);\n const caret = document.createRange(); caret.setStartBefore(marker); caret.collapse(true); marker.remove();\n const selection = document.getSelection(); selection?.removeAllRanges(); selection?.addRange(caret);\n }\n};\n", "import type { DocumentNode, DocumentTag, EditorDocument, ElementNode } from './model.js';\nimport { documentHTML, parseHTML, validateDocument } from './model.js';\nimport { activeRange, readTextSelection, selectText, preserveRange } from './selection.js';\n\nimport { applyList, indentList, listState, selectedBlocks } from './lists.js';\n\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']);\ninterface Piece { node: DocumentNode; selected: boolean; }\n\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};\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)) if (element.localName === tag) formats[name] = true;\n if (/^h[1-6]$/.test(element.localName) && formats.header === undefined) formats.header = Number(element.localName[1]);\n if (element.localName === 'blockquote') formats.blockquote = true;\n if (element.localName === 'pre') formats['code-block'] = true;\n if ((element.localName === 'ul' || element.localName === 'ol') && formats.list === undefined) formats.list = element.localName === 'ul' ? 'bullet' : 'ordered';\n if (element.localName === 'a' && formats.link === undefined) formats.link = element.getAttribute('href');\n if (element instanceof HTMLElement && element.style.textAlign && formats.align === undefined) 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); if (!range) 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); let position = 0; 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) samples.push(formatsAt(root, node));\n position = end;\n }\n if (samples.length) formats = samples[0];\n const keys = [...Object.keys(inlineFormats), 'header', 'list', 'blockquote', 'code-block', 'link', '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) if (samples.some((sample) => normalized(sample, key) !== normalized(samples[0], key))) mixed.add(key);\n }\n return { ...formats, align: formats.align ?? 'left', mixed: [...mixed], ...listState(root) };\n};\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') { applyList(root, value); return; }\n if (name === 'indent') { indentList(root, value); return; }\n if (name === 'clear') {\n if (value !== true || !selection.length) return;\n let content = parseHTML(root.innerHTML);\n for (const tag of [...Object.values(inlineFormats), 'a', 'span'] as DocumentTag[]) content = inlineDocument(content, selection.index, selection.index + selection.length, tag, false);\n root.innerHTML = documentHTML(content); selectText(root, selection.index, selection.length); return;\n }\n const tag = inlineFormats[name];\n if (tag) {\n if (range.collapsed) 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 if (!value) {\n const link = closestElement(range.startContainer)?.closest('a');\n if (link && root.contains(link))\n link.replaceWith(...link.childNodes);\n }\n else if (typeof value === 'string' && !range.collapsed) {\n const template = parseHTML(`<a></a>`);\n const link = template.children[0] as ElementNode;\n link.attributes.href = value;\n // Use the shared validator instead of assigning an unchecked URL to the live document.\n const holder = document.createElement('div');\n holder.innerHTML = documentHTML(validateDocument({ version: 1, children: [link] }));\n const clean = parseHTML(holder.innerHTML).children[0] as ElementNode;\n if (!clean.attributes.href)\n return;\n const element = document.createElement('a');\n element.setAttribute('href', clean.attributes.href);\n element.append(range.extractContents());\n range.insertNode(element);\n range.selectNodeContents(element);\n const native = document.getSelection();\n native?.removeAllRanges();\n native?.addRange(range);\n }\n return;\n }\n let blocks = selectedBlocks(root, range, false);\n if (!blocks.length) {\n const paragraph = document.createElement('p'); paragraph.append(range.extractContents());\n if (!paragraph.childNodes.length) paragraph.append(document.createElement('br'));\n range.insertNode(paragraph); 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 } else { replacement.append(...block.childNodes); replacement.setAttribute('style', block.getAttribute('style') ?? ''); block.replaceWith(replacement); }\n\n }\n }\n });\n};\n", "import type { Editor } from './index.js';\nimport { bookmark, restoreBookmark } from './selection.js';\nimport type { SelectionBookmark } from './selection.js';\n\nexport interface ToolbarAction {\n label: string; text: string; format?: string; value?: unknown;\n run?: (editor: Editor) => void;\n enabled?: (editor: Editor) => boolean;\n}\nexport interface ToolbarOptions { label?: string; }\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 const toolbar = document.createElement('div'); toolbar.className = 'mw-toolbar';\n toolbar.setAttribute('role', 'toolbar'); 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; let disposed = false; let tabIndex = 0;\n const cleanups: (() => void)[] = [];\n const buttons = actions.map((action) => {\n const button = document.createElement('button'); button.type = 'button'; button.textContent = action.text;\n button.title = action.label; button.setAttribute('aria-label', action.label);\n const down = (event: MouseEvent) => event.preventDefault();\n const click = () => {\n if (disposed || button.disabled || editor.isReadOnly()) return;\n editor.focus(); if (saved) restoreBookmark(editor.surface, saved);\n if (action.enabled && !action.enabled(editor)) return;\n if (action.run) 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); button.addEventListener('click', click);\n cleanups.push(() => { button.removeEventListener('mousedown', down); button.removeEventListener('click', click); });\n toolbar.append(button); return button;\n });\n const update = () => {\n if (disposed) 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)) 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]) 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) return;\n const index = enabled.indexOf(document.activeElement as HTMLButtonElement);\n if (index < 0 || event.ctrlKey || event.metaKey || event.altKey) return;\n if (event.key === 'Escape') { event.preventDefault(); editor.focus(); if (saved) restoreBookmark(editor.surface, saved); return; }\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) { event.preventDefault(); tabIndex = buttons.indexOf(enabled[next]); update(); enabled[next].focus(); }\n };\n toolbar.addEventListener('keydown', keyboard);\n const unsubscribe = editor.subscribe((change) => { if (change.source === 'api') saved = undefined; update(); });\n const unselect = editor.onSelectionChange(update);\n host.append(toolbar); update();\n return () => { if (disposed) return; disposed = true; unsubscribe(); unselect(); toolbar.removeEventListener('keydown', keyboard); for (const dispose of cleanups) dispose(); toolbar.remove(); };\n};\n", "import { documentHTML, parseHTML, renderDocument, sanitizeHTML, validateDocument } from './model.js';\nimport type { EditorDocument } from './model.js';\nimport { activeRange, bookmark, placeCaret, readTextSelection, restoreBookmark, selectText } from './selection.js';\nimport type { SelectionBookmark, TextSelection } from './selection.js';\nimport { editListInput, handlesListInput, indentList, listState, selectedBlocks } from './lists.js';\nimport { applyFormat, inlineFormats, readFormats } from './formatting.js';\nexport { sanitizeHTML } from './model.js';\nexport type { EditorDocument, DocumentNode, ElementNode, TextNode, DocumentTag } from './model.js';\nexport type { TextSelection, SelectionBookmark } from './selection.js';\n\nexport interface EditorChange { html: string; text: string; source: 'user' | 'api'; }\nexport interface EditorPlugin { name: string; setup(editor: Editor): void | (() => void); }\nexport interface EditorOptions {\n value?: string;\n placeholder?: string;\n readOnly?: boolean;\n label?: string;\n plugins?: EditorPlugin[];\n onChange?: (change: EditorChange) => void;\n historyLimit?: number;\n}\nexport interface Editor {\n readonly element: HTMLElement;\n readonly surface: HTMLElement;\n getHTML(): string;\n getText(): string;\n getJSON(): EditorDocument;\n setHTML(html: string): void;\n setJSON(value: EditorDocument): void;\n getSelection(): TextSelection | undefined;\n setSelection(index: number, length?: number): void;\n getFormats(): Record<string, unknown>;\n setReadOnly(value: boolean): void;\n isReadOnly(): boolean;\n format(name: string, value: unknown): void;\n insertHTML(html: string): void;\n focus(): void;\n undo(): void;\n redo(): void;\n canUndo(): boolean;\n canRedo(): boolean;\n /** Execute a plugin edit as one undoable operation. Read-only mode blocks it. */\n transact(mutate: (surface: HTMLElement) => void): void;\n providePlugin<T>(name: string, api: T): () => void;\n getPlugin<T>(name: string): T | undefined;\n subscribe(listener: (change: EditorChange) => void): () => void;\n onSelectionChange(listener: () => void): () => void;\n destroy(): void;\n}\ninterface Snapshot { html: string; selection: SelectionBookmark | undefined; }\n\nconst ensureDocument = (root: HTMLElement): boolean => {\n let normalized = false;\n if (!root.childNodes.length) { root.innerHTML = '<p><br></p>'; normalized = true; }\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 (root.lastElementChild?.localName === 'table')\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};\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|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};\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, 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 listeners = new Set<(change: EditorChange) => void>();\n const selectionListeners = new Set<() => void>();\n const pluginAPIs = new Map<string, unknown>();\n const disposers: (() => void)[] = [];\n if (options.onChange)\n listeners.add(options.onChange);\n const assertActive = () => {\n if (destroyed)\n throw new Error('Editor has been destroyed.');\n };\n const capture = (): Snapshot => ({ html: sanitizeHTML(surface.innerHTML), selection: bookmark(surface) });\n let current = capture();\n let lastSelection = current.selection;\n const notifySelection = () => {\n if (destroyed)\n return;\n if (readTextSelection(surface) && !typingAtCaret()) clearTyping();\n const saved = bookmark(surface);\n if (saved) {\n lastSelection = saved;\n current.selection = saved;\n }\n for (const listener of selectionListeners)\n listener();\n };\n const emit = (source: EditorChange['source']) => {\n const change: EditorChange = { html: editor.getHTML(), text: editor.getText(), source };\n for (const listener of [...listeners])\n listener(change);\n notifySelection();\n };\n const commit = (before: Snapshot, inputType = '') => {\n const selection = readTextSelection(surface);\n if (ensureDocument(surface) && selection) selectText(surface, selection.index, selection.length);\n const after = capture();\n if (after.html === before.html) {\n current = after;\n return;\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 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 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 editor.focus();\n const before = capture();\n const previousUndo = [...undoStack];\n const previousRedo = [...redoStack];\n try {\n mutate(surface);\n commit(before, inputType);\n }\n catch (error) {\n surface.innerHTML = before.html;\n restoreBookmark(surface, before.selection);\n current = capture();\n undoStack.splice(0, undoStack.length, ...previousUndo);\n redoStack.splice(0, redoStack.length, ...previousRedo);\n throw error;\n }\n };\n const editor: Editor = {\n element: container, surface,\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 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 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 readOnly = value;\n surface.contentEditable = String(!value);\n surface.setAttribute('aria-readonly', String(value));\n container.dataset.readonly = String(value);\n notifySelection();\n },\n isReadOnly: () => { assertActive(); return readOnly; },\n format: (name, value) => {\n assertActive(); if (readOnly) return; editor.focus();\n const selection = readTextSelection(surface);\n if (selection?.length === 0 && Object.hasOwn(inlineFormats, name)) {\n if (!typingAtCaret()) clearTyping();\n typingOffset = selection.index; typingOverrides[name] = Boolean(value); notifySelection();\n return;\n }\n clearTyping(); editor.transact(() => applyFormat(surface, name, value));\n },\n insertHTML: (html) => editor.transact(() => insertFragment(surface, html)),\n focus: () => {\n assertActive(); surface.focus({ preventScroll: true }); 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(); if (readOnly)\n return; const previous = undoStack.pop(); if (previous) {\n redoStack.push(capture());\n restore(previous);\n }\n },\n redo: () => {\n assertActive(); if (readOnly)\n return; const next = redoStack.pop(); 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(); listeners.add(listener); return () => { listeners.delete(listener); }; },\n onSelectionChange: (listener) => { assertActive(); selectionListeners.add(listener); return () => { selectionListeners.delete(listener); }; },\n destroy: () => {\n if (destroyed)\n return;\n destroyed = true;\n const failures: unknown[] = [];\n for (const dispose of disposers.reverse()) {\n try {\n dispose();\n }\n catch (error) {\n failures.push(error);\n }\n }\n listeners.clear();\n selectionListeners.clear();\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(); clearTyping(); pendingInput = undefined;\n runTransaction(() => editListInput(surface, event.inputType)); 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(); range.selectNodeContents(block); 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)) if (Boolean(readFormats(surface)[name]) !== enabled) 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; if (readOnly) {\n surface.innerHTML = current.html;\n return;\n } if (composing || event.isComposing)\n return; commit(pendingInput ?? current, event.inputType); pendingInput = undefined;\n });\n listen('compositionstart', () => { clearTyping(); composing = true; compositionStart = capture(); });\n listen('compositionend', () => {\n composing = false; if (compositionStart)\n commit(compositionStart); compositionStart = undefined; pendingInput = undefined;\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)) { event.preventDefault(); clearTyping(); pendingInput = undefined; runTransaction(() => editListInput(surface, type)); return; }\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(); clearTyping(); runTransaction(() => indentList(surface, event.shiftKey ? -1 : 1)); 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\nexport { createToolbar } from './toolbar.js';\nexport type { ToolbarAction, ToolbarOptions } from './toolbar.js';\n"],
5
+ "mappings": "AACO,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,QAAS,UAAW,WAAY,MAAO,QAAS,QAAS,QAAS,KAAM,KAAM,IAAI,EAMzQC,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,IAEZC,GAAU,CAACC,EAAeC,IAAuC,CACrE,IAAMC,EAAUF,EAAM,KAAK,EAC3B,GAAI,CAACE,GA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FxB,IACFW,EAAM,eAAe,EACrBlC,EAAO,OAAOuB,EAAOvB,EAAO,WAAW,EAAE,OAAgC,SAASuB,CAAI,GAAK,CAACvB,EAAO,WAAW,EAAEuB,CAAI,CAAC,EAEzH,CAAC,EACD,SAAS,iBAAiB,kBAAmB7B,CAAe,EAC5DP,EAAU,KAAK,IAAM,SAAS,oBAAoB,kBAAmBO,CAAe,CAAC,EACrF,GAAI,CACFM,EAAO,YAAY7B,CAAQ,EAC3B,QAAWN,KAAUD,EAAS,CAC5B,IAAMkE,EAAUjE,EAAO,MAAMmC,CAAM,EAC/B8B,GACF3C,EAAU,KAAK2C,CAAO,CAC1B,CACA,OAAO9B,CACT,OACOc,EAAO,CACZ,MAAAd,EAAO,QAAQ,EACTc,CACR,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", "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", "inlineFormats", "blockTags", "inlineDocument", "value", "from", "to", "tag", "enabled", "position", "visit", "node", "inherited", "start", "left", "right", "begin", "end", "selected", "text", "leaf", "children", "child", "piece", "groups", "last", "group", "closestElement", "formatsAt", "root", "element", "formats", "name", "readFormats", "range", "activeRange", "mixed", "index", "length", "readTextSelection", "walker", "samples", "keys", "normalized", "sample", "key", "listState", "applyFormat", "selection", "applyList", "indentList", "content", "parseHTML", "documentHTML", "selectText", "link", "holder", "validateDocument", "clean", "native", "blocks", "selectedBlocks", "paragraph", "preserveRange", "block", "nextTag", "replacement", "defaultActions", "editor", "createToolbar", "host", "actions", "options", "toolbar", "saved", "disposed", "tabIndex", "cleanups", "buttons", "action", "button", "down", "event", "click", "restoreBookmark", "formats", "mixed", "update", "bookmark", "index", "keyboard", "enabled", "direction", "next", "unsubscribe", "change", "unselect", "dispose", "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", "pendingInput", "lastInputTime", "lastInputType", "typingOverrides", "typingOffset", "clearTyping", "typingAtCaret", "readTextSelection", "undoStack", "redoStack", "listeners", "selectionListeners", "pluginAPIs", "disposers", "assertActive", "capture", "sanitizeHTML", "bookmark", "current", "lastSelection", "notifySelection", "saved", "listener", "emit", "source", "change", "editor", "commit", "before", "inputType", "selectText", "after", "now", "restore", "snapshot", "restoreBookmark", "runTransaction", "mutate", "previousUndo", "previousRedo", "error", "content", "documentHTML", "value", "validated", "validateDocument", "index", "length", "readFormats", "name", "inlineFormats", "applyFormat", "placeCaret", "previous", "api", "failures", "dispose", "listen", "type", "handler", "event", "handlesListInput", "editListInput", "start", "text", "overrides", "enabled", "nativeEvent", "holder", "blocks", "selectedBlocks", "listState", "indentList", "key"]
7
7
  }
@@ -0,0 +1,10 @@
1
+ export declare const selectedBlocks: (root: HTMLElement, range?: Range | undefined, preferItems?: boolean) => HTMLElement[];
2
+ export declare const listState: (root: HTMLElement) => {
3
+ listDepth: number;
4
+ canIndent: boolean;
5
+ canOutdent: boolean;
6
+ };
7
+ export declare const indentList: (root: HTMLElement, direction: unknown) => void;
8
+ export declare const applyList: (root: HTMLElement, value: unknown) => void;
9
+ export declare const handlesListInput: (root: HTMLElement, inputType: string) => boolean;
10
+ export declare const editListInput: (root: HTMLElement, inputType: string) => void;
@@ -15,3 +15,5 @@ export declare const restoreBookmark: (root: HTMLElement, saved: SelectionBookma
15
15
  export declare const readTextSelection: (root: HTMLElement) => TextSelection | undefined;
16
16
  export declare const selectText: (root: HTMLElement, index: number, length?: number) => void;
17
17
  export declare const placeCaret: (element: HTMLElement, end?: boolean) => void;
18
+ /** Keep actual DOM positions while moving blocks, including empty list items. */
19
+ export declare const preserveRange: (root: HTMLElement, mutate: () => void) => void;
package/dist/style.css CHANGED
@@ -1 +1 @@
1
- :root{--mw-font: Inter, ui-sans-serif, system-ui, sans-serif;--mw-font-size: 16px;--mw-line-height: 1.75;--mw-text: #263043;--mw-muted: #8490a1;--mw-surface: #ffffff;--mw-toolbar-bg: #fafbfc;--mw-border: #e4e8ef;--mw-accent: #6658e8;--mw-accent-soft: #eeebff;--mw-hover: #f0f2f7;--mw-radius: 12px;--mw-padding: 32px;--mw-min-height: 320px;--mw-button-size: 34px;--mw-focus-ring: 0 0 0 3px #6658e82b}.mw-editor{position:relative;font-family:var(--mw-font);color:var(--mw-text);background:var(--mw-surface);border:1px solid var(--mw-border);border-radius:var(--mw-radius);font-size:var(--mw-font-size)}.mw-editor:focus-within{border-color:var(--mw-accent);box-shadow:var(--mw-focus-ring)}.mw-content{position:relative;box-sizing:border-box;min-height:var(--mw-min-height);padding:var(--mw-padding);line-height:var(--mw-line-height);overflow-wrap:anywhere;white-space:pre-wrap;outline:none}.mw-content[data-empty=true]:before{position:absolute;left:var(--mw-padding);right:var(--mw-padding);pointer-events:none;content:attr(data-placeholder);color:var(--mw-muted)}.mw-content>*:first-child{margin-top:0}.mw-content p{margin:0 0 .65em}.mw-content h1,.mw-content h2,.mw-content h3{letter-spacing:-.025em;line-height:1.3;margin:.8em 0 .6em}.mw-content h1{font-size:2em}.mw-content h2{font-size:1.5em}.mw-content h3{font-size:1.25em}.mw-content a{color:var(--mw-accent);text-decoration:underline}.mw-content ul,.mw-content ol{margin:.65em 0;padding-left:1.5em}.mw-content ul{list-style:disc}.mw-content ol{list-style:decimal}.mw-content blockquote{margin:.65em 0;border-left:3px solid var(--mw-accent);padding-left:1em;color:var(--mw-muted)}.mw-content pre{white-space:pre-wrap}.mw-content pre,.mw-content code{background:var(--mw-hover);color:var(--mw-text);border-radius:6px;font-family:ui-monospace,monospace}.mw-content pre{padding:12px}.mw-content img{max-width:100%;height:auto}.mw-toolbar{display:flex;flex-wrap:wrap;gap:4px;padding:10px;border:1px solid var(--mw-border);border-radius:var(--mw-radius);background:var(--mw-toolbar-bg);margin-bottom:10px}.mw-toolbar button{display:inline-grid;place-items:center;min-width:var(--mw-button-size);height:var(--mw-button-size);border:0;border-radius:6px;background:transparent;color:var(--mw-text);font:600 15px var(--mw-font);cursor:pointer}.mw-toolbar button:hover{background:var(--mw-hover)}.mw-toolbar button[aria-pressed=true]{background:var(--mw-accent-soft);color:var(--mw-accent)}.mw-toolbar button:focus-visible{outline:2px solid var(--mw-accent);outline-offset:2px}.mw-toolbar button:disabled{opacity:.4;cursor:default}@media(prefers-reduced-motion:no-preference){.mw-toolbar button{transition:background .12s}}
1
+ :root{--mw-font: Inter, ui-sans-serif, system-ui, sans-serif;--mw-font-size: 16px;--mw-line-height: 1.75;--mw-text: #263043;--mw-muted: #8490a1;--mw-surface: #ffffff;--mw-toolbar-bg: #fafbfc;--mw-border: #e4e8ef;--mw-accent: #6658e8;--mw-accent-soft: #eeebff;--mw-hover: #f0f2f7;--mw-radius: 12px;--mw-padding: 32px;--mw-min-height: 320px;--mw-button-size: 34px;--mw-focus-ring: 0 0 0 3px #6658e82b}.mw-editor{position:relative;font-family:var(--mw-font);color:var(--mw-text);background:var(--mw-surface);border:1px solid var(--mw-border);border-radius:var(--mw-radius);font-size:var(--mw-font-size)}.mw-editor:focus-within{border-color:var(--mw-accent);box-shadow:var(--mw-focus-ring)}.mw-content{position:relative;box-sizing:border-box;min-height:var(--mw-min-height);padding:var(--mw-padding);line-height:var(--mw-line-height);overflow-wrap:anywhere;white-space:pre-wrap;outline:none}.mw-content[data-empty=true]:before{position:absolute;left:var(--mw-padding);right:var(--mw-padding);pointer-events:none;content:attr(data-placeholder);color:var(--mw-muted)}.mw-content>*:first-child{margin-top:0}.mw-content p{margin:0 0 .65em}.mw-content h1,.mw-content h2,.mw-content h3{letter-spacing:-.025em;line-height:1.3;margin:.8em 0 .6em}.mw-content h1{font-size:2em}.mw-content h2{font-size:1.5em}.mw-content h3{font-size:1.25em}.mw-content a{color:var(--mw-accent);text-decoration:underline}.mw-content ul,.mw-content ol{margin:.65em 0;padding-left:1.5em}.mw-content ul{list-style:disc}.mw-content ol{list-style:decimal}.mw-content blockquote{margin:.65em 0;border-left:3px solid var(--mw-accent);padding-left:1em;color:var(--mw-muted)}.mw-content pre{white-space:pre-wrap}.mw-content pre,.mw-content code{background:var(--mw-hover);color:var(--mw-text);border-radius:6px;font-family:ui-monospace,monospace}.mw-content pre{padding:12px}.mw-content img{max-width:100%;height:auto}.mw-toolbar{display:flex;flex-wrap:wrap;gap:4px;padding:10px;border:1px solid var(--mw-border);border-radius:var(--mw-radius);background:var(--mw-toolbar-bg);margin-bottom:10px}.mw-toolbar button{display:inline-grid;place-items:center;min-width:var(--mw-button-size);height:var(--mw-button-size);border:0;border-radius:6px;background:transparent;color:var(--mw-text);font:600 15px var(--mw-font);cursor:pointer}.mw-toolbar button:hover{background:var(--mw-hover)}.mw-toolbar button[aria-pressed=true]{background:var(--mw-accent-soft);color:var(--mw-accent)}.mw-toolbar button:focus-visible{outline:2px solid var(--mw-accent);outline-offset:2px}.mw-toolbar button:disabled{opacity:.4;cursor:default}@media(prefers-reduced-motion:no-preference){.mw-toolbar button{transition:background .12s}}.mw-toolbar button[aria-pressed=mixed]{background:var(--mw-accent-soft);box-shadow:inset 0 -2px var(--mw-accent)}.mw-content ul ul{list-style-type:circle}.mw-content ul ul ul{list-style-type:square}
@@ -0,0 +1,13 @@
1
+ import type { Editor } from './index.js';
2
+ export interface ToolbarAction {
3
+ label: string;
4
+ text: string;
5
+ format?: string;
6
+ value?: unknown;
7
+ run?: (editor: Editor) => void;
8
+ enabled?: (editor: Editor) => boolean;
9
+ }
10
+ export interface ToolbarOptions {
11
+ label?: string;
12
+ }
13
+ export declare const createToolbar: (host: HTMLElement, editor: Editor, actions?: ToolbarAction[], options?: ToolbarOptions) => () => void;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@morfira-dev/wysiwyg-core",
3
- "version": "0.2.0",
3
+ "version": "1.1.0",
4
4
  "type": "module",
5
5
  "files": [
6
6
  "dist"
@@ -27,5 +27,6 @@
27
27
  "homepage": "https://github.com/morfira-dev/morfira-wysiwyg#readme",
28
28
  "bugs": {
29
29
  "url": "https://github.com/morfira-dev/morfira-wysiwyg/issues"
30
- }
31
- }
30
+ },
31
+ "description": "Lightweight TypeScript rich text editor with a versioned document schema."
32
+ }