@morfira-dev/wysiwyg-core 1.0.1 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import type { EditorDocument } from './model.js';
2
2
  import type { TextSelection } from './selection.js';
3
+ export type { LinkFormat } from './inline-attributes.js';
3
4
  export { sanitizeHTML } from './model.js';
4
5
  export type { EditorDocument, DocumentNode, ElementNode, TextNode, DocumentTag } from './model.js';
5
6
  export type { TextSelection, SelectionBookmark } from './selection.js';
@@ -50,11 +51,5 @@ export interface Editor {
50
51
  destroy(): void;
51
52
  }
52
53
  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;
54
+ export { createToolbar } from './toolbar.js';
55
+ 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 Ke=["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"],ke=new Set(Ke),Ue=new Set(["script","style","iframe","object","embed","svg","math","template","form","input","button","textarea","select","noscript","link","meta","base"]),We={b:"strong",i:"em",strike:"s",div:"p"},Le=1e5,Ne=100,Je=(e,r)=>{let t=e.trim();if(!t||/[\u0000-\u0020\u007f]/.test(t))return;let n=/^([a-z][a-z\d+.-]*):/i.exec(t)?.[1].toLowerCase();if(!(n&&!(r?["http","https"]:["http","https","mailto","tel"]).includes(n))&&!(t.startsWith("\\")||t.startsWith("//")))return t},Xe=e=>{let r=[];for(let t of e.split(";")){let n=t.indexOf(":");if(n<0)continue;let o=t.slice(0,n).trim().toLowerCase(),i=t.slice(n+1).trim().toLowerCase(),s=/^(#[a-f\d]{3,8}|[a-z]{1,24}|(?:rgb|rgba|hsl|hsla)\([\d\s.,%+-]+\))$/,l=/^(?:\d{1,4}(?:\.\d{1,3})?)(?:px|%|em|rem)$/;(["color","background-color","border-color"].includes(o)?s.test(i):["width","height","font-size"].includes(o)?l.test(i):o==="text-align"?["left","center","right","justify"].includes(i):o==="font-weight"?/^(bold|normal|[1-9]00)$/.test(i):o==="font-style"?["italic","normal"].includes(i):o==="text-decoration"?/^(underline|line-through|none)$/.test(i):!1)&&r.push(`${o}: ${i}`)}return r.join("; ")},we=(e,r)=>{let t={};for(let[n,o]of Object.entries(r))if(!(typeof o!="string"||o.length>2e4))if(n==="style"){let i=Xe(o);i&&(t.style=i)}else if(n==="title"||e==="img"&&n==="alt")t[n]=o;else if(e==="a"&&n==="href"||e==="img"&&n==="src"){let i=Je(o,e==="img");i&&(t[n]=i)}else if(["td","th"].includes(e)&&["rowspan","colspan"].includes(n)||["img","col","table"].includes(e)&&["width","height","span"].includes(n))/^\d{1,4}$/.test(o)&&Number(o)>0&&Number(o)<=1e3&&(t[n]=o);else if(e==="a"&&n==="target"&&["_self","_blank"].includes(o))t.target=o;else if(e==="a"&&n==="rel"){let i=[...new Set(o.toLowerCase().split(/\s+/).filter(s=>["noopener","noreferrer"].includes(s)))];i.length&&(t.rel=i.join(" "))}else e==="th"&&n==="scope"&&["row","col","rowgroup","colgroup"].includes(o)&&(t[n]=o);return e==="a"&&t.target==="_blank"&&(t.rel="noopener noreferrer"),t},Me=(e,r,t)=>{if(++t.count>Le||r>Ne)throw new RangeError("Document exceeds structural limits.");if(e.nodeType===3)return[{type:"text",text:e.textContent??""}];if(e.nodeType!==1)return[];let n=e,o=n.localName.toLowerCase();if(n.namespaceURI!=="http://www.w3.org/1999/xhtml"||Ue.has(o))return[];let i=[...n.childNodes].flatMap(c=>Me(c,r+1,t)),s=We[o]??o;if(!ke.has(s))return i;let l=we(s,Object.fromEntries([...n.attributes].map(c=>[c.name,c.value])));return s==="img"&&!l.src?[]:[{type:"element",tag:s,attributes:l,children:i}]},C=e=>{if(e.length>5e6)throw new RangeError("HTML exceeds the document size limit.");let r=document.createElement("template");r.innerHTML=e;let t={count:0};return{version:1,children:[...r.content.childNodes].flatMap(n=>Me(n,0,t))}},ne=e=>{if(!e||typeof e!="object"||!("version"in e)||e.version!==1||!("children"in e)||!Array.isArray(e.children))throw new TypeError("Expected a version 1 document.");let r=0,t=0,n=(o,i)=>{if(++r>Le||i>Ne)throw new RangeError("Document exceeds structural limits.");if(!o||typeof o!="object"||!("type"in o))throw new TypeError("Invalid document node.");if(o.type==="text"&&"text"in o&&typeof o.text=="string"){if(t+=o.text.length,t>5e6)throw new RangeError("Document text exceeds size limit.");return{type:"text",text:o.text}}if(o.type!=="element"||!("tag"in o)||typeof o.tag!="string"||!ke.has(o.tag)||!("children"in o)||!Array.isArray(o.children))throw new TypeError("Invalid document element.");let s="attributes"in o&&o.attributes&&typeof o.attributes=="object"&&!Array.isArray(o.attributes)?o.attributes:{};return{type:"element",tag:o.tag,attributes:we(o.tag,s),children:o.children.map(l=>n(l,i+1))}};return{version:1,children:e.children.map(o=>n(o,0))}},re=e=>{let r=document.createDocumentFragment(),t=(n,o)=>{if(o.type==="text"){n.appendChild(document.createTextNode(o.text));return}let i=document.createElement(o.tag);for(let[s,l]of Object.entries(o.attributes))i.setAttribute(s,l);for(let s of o.children)t(i,s);n.appendChild(i)};for(let n of e.children)t(r,n);return r},j=e=>{let r=document.createElement("div");return r.append(re(e)),r.innerHTML},oe=e=>j(C(e));var w=e=>{let r=e.ownerDocument.getSelection();if(!r?.rangeCount)return;let t=r.getRangeAt(0);if(!(!e.contains(t.startContainer)||!e.contains(t.endContainer)))return t.cloneRange()},Se=(e,r)=>{let t=[],n=r;for(;n!==e&&n.parentNode;)t.unshift([...n.parentNode.childNodes].indexOf(n)),n=n.parentNode;return t},X=e=>{let r=w(e);if(!r)return;let t=e.ownerDocument.getSelection();return{start:Se(e,r.startContainer),startOffset:r.startOffset,end:Se(e,r.endContainer),endOffset:r.endOffset,backward:!r.collapsed&&t.anchorNode===r.endContainer&&t.anchorOffset===r.endOffset}},q=(e,r)=>{if(!r)return;let t=d=>d.reduce((p,u)=>p.childNodes[u]??p,e),n=t(r.start),o=t(r.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 l=i(n,r.startOffset),c=i(o,r.endOffset);r.backward?s.setBaseAndExtent(o,c,n,l):s.setBaseAndExtent(n,l,o,c)},A=e=>{let r=w(e);if(!r)return;let t=e.ownerDocument.createRange();return t.selectNodeContents(e),t.setEnd(r.startContainer,r.startOffset),{index:t.toString().length,length:r.toString().length}},R=(e,r,t=0)=>{if(![r,t].every(b=>Number.isInteger(b)&&b>=0))throw new RangeError("Selection offsets must be non-negative integers.");let n=e.ownerDocument.createTreeWalker(e,4),o=[],i;for(;i=n.nextNode();)o.push(i);let s=b=>{for(let h of o){if(b<=h.length)return[h,b];b-=h.length}let m=o.at(-1);return m?[m,m.length]:[e.querySelector("p,h1,h2,h3,h4,h5,h6,li,blockquote,pre")??e,0]},[l,c]=s(r),[d,p]=s(r+t),u=e.ownerDocument.createRange();u.setStart(l,c),u.setEnd(d,p),e.focus({preventScroll:!0});let f=e.ownerDocument.getSelection();f?.removeAllRanges(),f?.addRange(u)},se=(e,r=!1)=>{let t=e.ownerDocument.createRange();t.selectNodeContents(e),t.collapse(!r);let n=e.ownerDocument.getSelection();n?.removeAllRanges(),n?.addRange(t)},B=(e,r)=>{let t=w(e);if(!t)return;let n=e.ownerDocument.getSelection(),o=!t.collapsed&&n.anchorNode===t.endContainer&&n.anchorOffset===t.endOffset,i=e.ownerDocument.createComment("mw-start"),s=t.collapsed?void 0:e.ownerDocument.createComment("mw-end");if(s){let c=t.cloneRange();c.collapse(!1),c.insertNode(s)}let l=t.cloneRange();l.collapse(!0),l.insertNode(i);try{if(r(),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(),o?n.setBaseAndExtent(c.endContainer,c.endOffset,c.startContainer,c.startOffset):(n.removeAllRanges(),n.addRange(c))}}finally{i.remove(),s?.remove()}};var Ae="p,h1,h2,h3,h4,h5,h6,blockquote,pre,li",D=e=>!!e&&/^(ul|ol)$/.test(e.localName),Ve=e=>e instanceof Element?e:e.parentElement,Q=(e,r,t=!0)=>{let n=Ve(r),o=n?.closest("li"),i=(t&&o&&e.contains(o)?o:void 0)??n?.closest(Ae);return i&&e.contains(i)?i:void 0},Ge=(e,r)=>{let t=r.ownerDocument.createRange();r.nodeType===3?t.selectNodeContents(r):t.selectNode(r);let n=e.cloneRange();n.collapse(!0);let o=e.cloneRange();o.collapse(!1);let i=t.cloneRange();i.collapse(!0);let s=t.cloneRange();return s.collapse(!1),n.compareBoundaryPoints(Range.START_TO_START,s)<0&&o.compareBoundaryPoints(Range.START_TO_START,i)>0},$=(e,r=w(e),t=!0)=>{if(!r)return[];if(r.collapsed){let s=Q(e,r.startContainer,t);return s?[s]:[]}let n=new Set,o=e.ownerDocument.createTreeWalker(e,NodeFilter.SHOW_TEXT|NodeFilter.SHOW_ELEMENT),i;for(;i=o.nextNode();)if(!(!(i.nodeType===3&&i.textContent)&&!(i instanceof Element&&/^(br|img|hr)$/.test(i.localName)))&&Ge(r,i)){let s=Q(e,i,t);s&&n.add(s)}return[...e.querySelectorAll(Ae)].filter(s=>n.has(s))},De=e=>e.filter(r=>!e.some(t=>t!==r&&t.contains(r))),Re=e=>{let r=De($(e));if(!r.length||r.some(o=>o.localName!=="li"||!D(o.parentElement)))return[];let t=r[0].parentElement;if(r.some(o=>o.parentElement!==t))return[];let n=[...t.children];return n.indexOf(r.at(-1))-n.indexOf(r[0])+1!==r.length?[]:r},He=(e,r)=>{let t=0,n=r.parentElement;for(;n&&n!==e;)D(n)&&t++,n=n.parentElement;return t},Oe=(e,r)=>!!e&&e.localName===r.localName&&D(e)&&e.getAttribute("style")===r.getAttribute("style"),V=e=>{for(let r of[...e.querySelectorAll("ul,ol")]){if(!e.contains(r))continue;let t=r.previousSibling;t instanceof Element&&Oe(t,r)&&(t.append(...r.childNodes),r.remove())}},ve=(e,r)=>{let t=e.parentElement,n=t.cloneNode(!1);for(;e.nextSibling;)n.append(e.nextSibling);e.remove(),t.after(...r,...n.childNodes.length?[n]:[]),t.childNodes.length||t.remove()},G=e=>[...e.childNodes].filter(r=>!(r instanceof Element&&D(r))),je=(e,r=!1)=>{let t=()=>{let l=document.createElement("p");return e.hasAttribute("style")&&l.setAttribute("style",e.getAttribute("style")),l},n=t(),o=[...e.children].filter(D),i=G(e),s=[];for(let l of i)r&&l instanceof HTMLElement&&/^(p|h[1-6]|blockquote|pre)$/.test(l.localName)?n.append(...l.childNodes):l instanceof HTMLElement&&/^(p|h[1-6]|blockquote|pre)$/.test(l.localName)?(n.childNodes.length&&s.push(n),n=t(),s.push(l)):n.append(l);(n.childNodes.length||!s.length)&&(n.childNodes.length||n.append(document.createElement("br")),s.push(n)),ve(e,[...s,...o])},ie=e=>{let r=e[0].parentElement,t=r.parentElement;if(t?.localName!=="li"||!D(t.parentElement)){for(let o of e)je(o);return}let n=r.cloneNode(!1);for(;e.at(-1).nextSibling;)n.append(e.at(-1).nextSibling);n.childNodes.length&&e.at(-1).append(n),t.after(...e),r.childNodes.length||r.remove()},Y=e=>{let r=Re(e),t=!!r.length&&r[0].previousElementSibling?.localName==="li"&&r.every(n=>[n,...n.querySelectorAll("li")].every(o=>He(e,o)<8));return{listDepth:r.length?He(e,r[0]):0,canIndent:t,canOutdent:!!r.length}},le=(e,r)=>{if(r!==1&&r!==-1)throw new TypeError("List indentation requires 1 or -1.");let t=Re(e);if(!t.length)throw new RangeError("Select consecutive items in the same list.");r===1&&!Y(e).canIndent||B(e,()=>{if(r===-1)ie(t);else{let n=t[0].parentElement,o=t[0].previousElementSibling,i=o.lastElementChild;Oe(i,n)||(i=n.cloneNode(!1),o.append(i)),i.append(...t)}V(e)})},Be=(e,r)=>{if(r!==!1&&r!=="bullet"&&r!=="ordered")throw new TypeError("Expected bullet, ordered or false.");let t=De($(e));if(t.some(n=>n.localName==="li"&&!D(n.parentElement)))throw new RangeError("A list item must belong to a list.");B(e,()=>{for(let n of t){if(!r){n.localName==="li"&&ie([n]);continue}let o=r==="bullet"?"ul":"ol";if(n.localName==="li"){if(n.parentElement.localName===o)continue;let i=document.createElement(o);n.parentElement.hasAttribute("style")&&i.setAttribute("style",n.parentElement.getAttribute("style")),ve(n,[i]),i.append(n)}else{let i=document.createElement(o),s=document.createElement("li");n.hasAttribute("style")&&s.setAttribute("style",n.getAttribute("style")),s.append(...n.childNodes),i.append(s),n.replaceWith(i)}}V(e)})},Qe=e=>!e.textContent?.trim()&&!e.querySelector("img,hr,ul,ol"),Ce=e=>{G(e).some(n=>n.textContent||n instanceof Element&&(n.matches("br,img,hr")||n.querySelector("br,img,hr")))||([...e.children].some(D)?e.prepend(Object.assign(document.createElement("p"),{innerHTML:"<br>"})):e.append(document.createElement("br")))},Ye=(e,r)=>{let t=r.cloneRange();return t.selectNodeContents(e),t.setEnd(r.startContainer,r.startOffset),!t.toString()&&!t.cloneContents().querySelector("img,hr,br")},pe=(e,r)=>{let t=w(e);if(!t)return!1;let n=Q(e,t.startContainer);return n?.localName!=="li"||!D(n.parentElement)||Q(e,t.endContainer)!==n?!1:["insertParagraph","insertLineBreak"].includes(r)||r==="deleteContentBackward"&&t.collapsed&&Ye(n,t)},ge=(e,r)=>{let t=w(e),n=Q(e,t.startContainer);if(r==="insertParagraph"){if(Qe(n)){B(e,()=>{let c=n.parentElement.parentElement;c?.localName==="li"&&D(c.parentElement)?ie([n]):je(n,!0)}),V(e);return}t.deleteContents();let o=t.cloneRange();o.selectNodeContents(n),o.setStart(t.startContainer,t.startOffset);let i=n.cloneNode(!1);i.append(o.extractContents()),n.after(i),Ce(n),Ce(i);let s=document.createTreeWalker(i,NodeFilter.SHOW_TEXT),l;do l=s.nextNode();while(l&&(!l.textContent||l.parentElement?.closest("li")!==i));if(l){let c=document.createRange();c.setStart(l,0),c.collapse(!0);let d=document.getSelection();d?.removeAllRanges(),d?.addRange(c)}else se(i.querySelector("p,h1,h2,h3,h4,h5,h6,pre")??i)}else if(r==="insertLineBreak"){t.deleteContents();let o=document.createElement("br");t.insertNode(o),o.nextSibling||o.after(document.createElement("br")),t.setStartAfter(o),t.collapse(!0);let i=document.getSelection();i?.removeAllRanges(),i?.addRange(t)}else{let o=n.previousElementSibling;if(o&&o.localName!=="li")return;if(!o){B(e,()=>ie([n])),V(e);return}if(!G(o).some(f=>f.textContent||f instanceof Element&&(f.localName==="img"||f.querySelector("img"))))for(let f of[...o.querySelectorAll("br")])f.closest("li")===o&&f.remove();let i=document.createComment("mw-join"),l=G(o).at(-1),c=l instanceof HTMLElement&&/^(p|h[1-6]|blockquote|pre)$/.test(l.localName)?l:o;c===o?o.insertBefore(i,[...o.children].find(D)??null):c.append(i);let d=G(n);d[0]instanceof HTMLElement&&/^(p|h[1-6])$/.test(d[0].localName)&&d.splice(0,1,...d[0].childNodes),i.after(...d);for(let f of[...n.children].filter(D))o.append(f);n.remove(),V(e);let p=document.createRange();p.setStartBefore(i),p.collapse(!0),i.remove();let u=document.getSelection();u?.removeAllRanges(),u?.addRange(p)}};var O={color:"color",background:"background-color"},qe=new Set(["p","h1","h2","h3","h4","h5","h6","blockquote","pre","ul","ol","li","table","thead","tbody","tfoot","tr","td","th","caption","colgroup"]),be=(e,r)=>ne({version:1,children:[{type:"element",tag:e,attributes:r,children:[]}]}).children[0].attributes,_=(e,r)=>{if(r===!1)return!1;if(typeof r!="string"||!r.trim()||r.length>128||/[;{}]/.test(r))throw new TypeError("Expected a CSS color or false.");let t=O[e],n=be("span",{style:`${t}: ${r}`}),o=document.createElement("span");o.setAttribute("style",n.style??"");let i=o.style.getPropertyValue(t);if(!i)throw new TypeError("Unsupported or invalid CSS color.");return i},Pe=e=>{if(e===!1)return!1;let r=typeof e=="string"?{href:e}:e;if(!r||typeof r!="object"||Array.isArray(r)||!("href"in r)||typeof r.href!="string")throw new TypeError("Expected a link URL, LinkFormat or false.");let t=r,n={href:r.href};if(t.title!==void 0){if(typeof t.title!="string"||t.title.length>1024)throw new TypeError("Link title must be a string up to 1024 characters.");n.title=t.title}if(t.target!==void 0){if(t.target!=="_self"&&t.target!=="_blank")throw new TypeError("Link target must be _self or _blank.");n.target=t.target}if(t.text!==void 0&&(typeof t.text!="string"||!t.text.length||t.text.length>2e4))throw new TypeError("New link text must contain 1\u201320000 characters.");let o=be("a",n);if(!o.href)throw new TypeError("Unsupported or unsafe link URL.");return{attributes:o,...typeof t.text=="string"?{text:t.text}:{}}},Ee=(e,r)=>{let t={...e,...r};return t.title||delete t.title,r.target==="_self"&&delete t.rel,be("a",t)},Fe=(e,r)=>JSON.stringify(Object.entries(e??{}).sort())===JSON.stringify(Object.entries(r??{}).sort()),Ze=(e,r)=>{let t={...e},n=(t.style??"").split(";").map(o=>o.trim()).filter(o=>o&&o.slice(0,o.indexOf(":")).trim()!==r).join("; ");return n?t.style=n:delete t.style,t},Ie=e=>{let r=[];for(let t of e){let n=r.at(-1);n&&n.selected===t.selected&&Fe(n.link,t.link)?n.pieces.push(t):r.push({pieces:[t],selected:t.selected,link:t.link})}return r},he=e=>{let r=[];for(let t of e){let n=t.type==="element"?{...t,children:he(t.children)}:t,o=r.at(-1);n.type==="text"&&o?.type==="text"?o.text+=n.text:n.type==="element"&&o?.type==="element"&&!qe.has(n.tag)&&!["img","br","hr"].includes(n.tag)&&o.tag===n.tag&&Fe(o.attributes,n.attributes)?o.children=he([...o.children,...n.children]):r.push(n)}return r},ae=(e,r,t,n)=>{let o=0,i=l=>Ie(l).flatMap(c=>{let d=c.pieces.map(u=>u.node);if(n.kind==="style")return c.selected&&n.value!==!1?[{type:"element",tag:"span",attributes:{style:`${n.property}: ${n.value}`},children:d}]:d;let p=c.selected?n.attributes===!1?void 0:Ee(c.link??{},n.attributes):c.link;return p?[{type:"element",tag:"a",attributes:p,children:d}]:d}),s=(l,c)=>{if(l.type==="text"){let u=o;o+=l.text.length;let f=Math.max(0,Math.min(l.text.length,r-u)),b=Math.max(f,Math.min(l.text.length,t-u));return[[0,f,!1],[f,b,!0],[b,l.text.length,!1]].flatMap(([m,h,y])=>{let x=l.text.slice(m,h);return x?[{node:{type:"text",text:x},selected:!!y,link:c}]:[]})}let d=n.kind==="link"&&l.tag==="a"?l.attributes:c;if(!l.children.length)return[{node:l,selected:o>=r&&o<t,link:d}];let p=l.children.flatMap(u=>s(u,d));return n.kind==="link"&&l.tag==="a"?p:qe.has(l.tag)?[{node:{...l,children:i(p)},selected:!1}]:Ie(p).flatMap(u=>{let f=n.kind==="style"&&u.selected?Ze(l.attributes,n.property):l.attributes,b=u.pieces.map(m=>m.node);return l.tag==="span"&&!Object.keys(f).length?u.pieces:[{node:{...l,attributes:f,children:b},selected:u.selected,link:u.link}]})};return{version:1,children:he(i(e.children.flatMap(l=>s(l))))}};var $e=(e,r)=>{let t=Pe(r),n=w(e);if(!n)return;let o=A(e),i=n.startContainer.nodeType===1?n.startContainer:n.startContainer.parentElement,s=i?.closest("a"),l=s&&e.contains(s)?s:void 0;if(t&&t.text!==void 0&&(!n.collapsed||l))throw new TypeError("Link text is only supported for insertion at a caret outside links.");if(!n.collapsed){e.innerHTML=j(ae(C(e.innerHTML),o.index,o.index+o.length,{kind:"link",attributes:t&&t.attributes})),R(e,o.index,o.length);return}if(l){let f=t&&Ee(Object.fromEntries([...l.attributes].map(b=>[b.name,b.value])),t.attributes);B(e,()=>{if(!f)l.replaceWith(...l.childNodes);else{for(let b of[...l.attributes])l.removeAttribute(b.name);for(let[b,m]of Object.entries(f))l.setAttribute(b,m)}});return}if(!t||t.text===void 0)return;let c=e.ownerDocument.createElement("a");for(let[f,b]of Object.entries(t.attributes))c.setAttribute(f,b);c.textContent=t.text;let d=i?.closest("p,li,h1,h2,h3,h4,h5,h6,blockquote,pre,td,th");d?.childNodes.length===1&&d.firstChild instanceof HTMLBRElement&&(d.firstChild.remove(),n.setStart(d,0)),n.insertNode(c);let p=e.ownerDocument.createTextNode("");c.after(p),n.setStart(p,0),n.collapse(!0);let u=e.ownerDocument.getSelection();u?.removeAllRanges(),u?.addRange(n)};var z={bold:"strong",italic:"em",underline:"u",strike:"s",code:"code",subscript:"sub",superscript:"sup"},et=new Set(["p","h1","h2","h3","h4","h5","h6","blockquote","pre","ul","ol","li","table","thead","tbody","tfoot","tr","td","th","caption","colgroup"]),_e=(e,r,t,n,o)=>{let i=0,s=(l,c)=>{if(l.type==="text"){let u=i;i+=l.text.length;let f=Math.max(0,Math.min(l.text.length,r-u)),b=Math.max(f,Math.min(l.text.length,t-u));return[[0,f,!1],[f,b,!0],[b,l.text.length,!1]].flatMap(([m,h,y])=>{let x=l.text.slice(m,h);if(!x)return[];let T={type:"text",text:x};return[{node:y&&o&&!c?{type:"element",tag:n,attributes:{},children:[T]}:T,selected:!!y}]})}let d=l.children.flatMap(u=>s(u,c||o&&l.tag===n));if(et.has(l.tag))return[{node:{...l,children:d.map(u=>u.node)},selected:!1}];if(!d.length)return[{node:l,selected:!1}];let p=[];for(let u of d){let f=p.at(-1);f?.selected===u.selected?f.children.push(u.node):p.push({selected:u.selected,children:[u.node]})}return p.flatMap(u=>l.tag===n&&!o&&u.selected?u.children.map(f=>({node:f,selected:!0})):[{node:{...l,children:u.children},selected:u.selected}])};return{version:1,children:e.children.flatMap(l=>s(l,!1)).map(l=>l.node)}},tt=e=>e.nodeType===1?e:e.parentElement,ze=(e,r)=>{let t=tt(r),n={};for(;t&&t!==e;){for(let[o,i]of Object.entries(z))t.localName===i&&(n[o]=!0);if(/^h[1-6]$/.test(t.localName)&&n.header===void 0&&(n.header=Number(t.localName[1])),t.localName==="blockquote"&&(n.blockquote=!0),t.localName==="pre"&&(n["code-block"]=!0),(t.localName==="ul"||t.localName==="ol")&&n.list===void 0&&(n.list=t.localName==="ul"?"bullet":"ordered"),t.localName==="a"&&n.link===void 0&&(n.link=t.getAttribute("href"),n.linkTitle=t.getAttribute("title")??"",n.linkTarget=t.getAttribute("target")??"_self"),t instanceof HTMLElement)for(let[o,i]of Object.entries(O))n[o]===void 0&&t.style.getPropertyValue(i)&&(n[o]=t.style.getPropertyValue(i));t instanceof HTMLElement&&t.style.textAlign&&n.align===void 0&&(n.align=t.style.textAlign),t=t.parentElement}return n},ce=e=>{let r=w(e);if(!r)return{};let t=ze(e,r.startContainer),n=new Set;if(!r.collapsed){let{index:o,length:i}=A(e),s=e.ownerDocument.createTreeWalker(e,NodeFilter.SHOW_TEXT),l=0,c,d=[];for(;c=s.nextNode();){let f=l+c.textContent.length;f>o&&l<o+i&&d.push(ze(e,c)),l=f}d.length&&(t=d[0]);let p=[...Object.keys(z),"header","list","blockquote","code-block","link","linkTitle","linkTarget","color","background","align"],u=(f,b)=>f[b]??(b==="align"?"left":b==="header"?0:!1);for(let f of p)d.some(b=>u(b,f)!==u(d[0],f))&&n.add(f)}return{...t,align:t.align??"left",mixed:[...n],...Y(e)}},ye=(e,r,t)=>{let n=w(e);if(!n)return;let o=A(e);if(r==="list"){Be(e,t);return}if(r==="indent"){le(e,t);return}if(r==="clear"){if(t!==!0||!o.length)return;let l=C(e.innerHTML);for(let c of[...Object.values(z),"a","span"])l=_e(l,o.index,o.index+o.length,c,!1);e.innerHTML=j(l),R(e,o.index,o.length);return}let i=z[r];if(i){if(n.collapsed)return;e.innerHTML=j(_e(C(e.innerHTML),o.index,o.index+o.length,i,!!t)),R(e,o.index,o.length);return}if(r==="link"){$e(e,t);return}if(Object.hasOwn(O,r)){let l=_(r,t);if(!o.length)return;e.innerHTML=j(ae(C(e.innerHTML),o.index,o.index+o.length,{kind:"style",property:O[r],value:l})),R(e,o.index,o.length);return}let s=$(e,n,!1);if(!s.length){let l=document.createElement("p");l.append(n.extractContents()),l.childNodes.length||l.append(document.createElement("br")),n.insertNode(l),s=[l]}B(e,()=>{for(let l of s){if(r==="align"&&["left","center","right","justify",!1].includes(t)){l.style.textAlign=t?String(t):"";continue}let c=r==="header"?Number.isInteger(t)&&Number(t)>=1&&Number(t)<=6?`h${t}`:"p":r==="blockquote"?t?"blockquote":"p":r==="code-block"?t?"pre":"p":void 0;if(c){let d=document.createElement(c);if(l.localName==="li"){let p=[...l.childNodes].filter(u=>!(u instanceof Element&&/^(ul|ol|p|h[1-6]|pre|blockquote)$/.test(u.localName)));d.append(...p),l.prepend(d)}else d.append(...l.childNodes),d.setAttribute("style",l.getAttribute("style")??""),l.replaceWith(d)}}})};var nt=[{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}],rt=(e,r,t=nt,n={})=>{t=t.map(m=>m.format&&Object.hasOwn(O,m.format)?{...m,value:_(m.format,m.value)}:m);let o=document.createElement("div");o.className="mw-toolbar",o.setAttribute("role","toolbar"),o.setAttribute("aria-label",n.label??"\u0424\u043E\u0440\u043C\u0430\u0442\u0438\u0440\u043E\u0432\u0430\u043D\u0438\u0435");let i,s=!1,l=0,c=[],d=t.map(m=>{let h=document.createElement("button");h.type="button",h.textContent=m.text,h.title=m.label,h.setAttribute("aria-label",m.label);let y=T=>T.preventDefault(),x=()=>{if(!(s||h.disabled||r.isReadOnly())&&(r.focus(),i&&q(r.surface,i),!(m.enabled&&!m.enabled(r)))){if(m.run)m.run(r);else if(m.format){let T=r.getFormats(),S=T.mixed?.includes(m.format);r.format(m.format,!S&&T[m.format]===(m.value??!0)?!1:m.value??!0)}p()}};return h.addEventListener("mousedown",y),h.addEventListener("click",x),c.push(()=>{h.removeEventListener("mousedown",y),h.removeEventListener("click",x)}),o.append(h),h}),p=()=>{if(s)return;i=X(r.surface)??i;let m=r.getFormats();d.forEach((h,y)=>{let x=t[y];h.disabled=r.isReadOnly()||(x.enabled?!x.enabled(r):!1),x.format&&!["indent","clear"].includes(x.format)&&h.setAttribute("aria-pressed",m.mixed?.includes(x.format)?"mixed":String(m[x.format]===(x.value??!0)))}),(d[l]?.disabled||!d[l])&&(l=d.findIndex(h=>!h.disabled)),d.forEach((h,y)=>{h.tabIndex=y===l?0:-1})},u=m=>{let h=d.filter(S=>!S.disabled);if(!h.length)return;let y=h.indexOf(document.activeElement);if(y<0||m.ctrlKey||m.metaKey||m.altKey)return;if(m.key==="Escape"){m.preventDefault(),r.focus(),i&&q(r.surface,i);return}let x=getComputedStyle(o).direction==="rtl"?-1:1,T=m.key==="Home"?0:m.key==="End"?h.length-1:m.key==="ArrowRight"?(y+x+h.length)%h.length:m.key==="ArrowLeft"?(y-x+h.length)%h.length:-1;T>=0&&(m.preventDefault(),l=d.indexOf(h[T]),p(),h[T].focus())};o.addEventListener("keydown",u);let f=r.subscribe(m=>{m.source==="api"&&(i=void 0),p()}),b=r.onSelectionChange(p);return e.append(o),p(),()=>{if(!s){s=!0,f(),b(),o.removeEventListener("keydown",u);for(let m of c)m();o.remove()}}};var de=e=>{let r=!1;e.childNodes.length||(e.innerHTML="<p><br></p>",r=!0);let t;for(let n of[...e.childNodes])n.nodeType===3||n.nodeType===1&&/^(strong|em|u|s|a|span|code|img|br|sub|sup)$/.test(n.localName)?(t||(t=document.createElement("p"),e.insertBefore(t,n)),t.append(n),r=!0):t=void 0;return e.lastElementChild?.localName==="table"&&e.append(Object.assign(document.createElement("p"),{innerHTML:"<br>"})),e.dataset.empty=String(!e.textContent&&!e.querySelector("table,img,hr")),r},ot=(e,r)=>{let t=w(e);if(!t)return;let n=re(C(r));if(!n.childNodes.length)return;t.deleteContents();let i=(t.startContainer.nodeType===1?t.startContainer:t.startContainer.parentElement)?.closest("p,h1,h2,h3,h4,h5,h6,li,blockquote,pre");if(n.childNodes.length===1&&n.firstChild instanceof HTMLParagraphElement&&i){let p=n.firstChild;n.replaceChildren(...p.childNodes)}let s=[...n.childNodes].some(p=>p instanceof HTMLElement&&/^(p|h[1-6]|ul|ol|table|blockquote|pre)$/.test(p.localName)),l=n.lastChild;if(s&&i&&e.contains(i)){let p=document.createRange();p.selectNodeContents(i),p.setStart(t.startContainer,t.startOffset);let u=i.cloneNode(!1);u.append(p.extractContents()),i.after(n),(u.textContent||u.querySelector("img,br"))&&l.after(u),!i.textContent&&!i.querySelector("img")&&i.remove()}else t.insertNode(n);let c=document.createRange();c.setStartAfter(l),c.collapse(!0);let d=document.getSelection();d?.removeAllRanges(),d?.addRange(c)},Ct=(e,r={})=>{if(e.childNodes.length)throw new Error("Editor host must be empty. Pass initial HTML through value.");let t=r.plugins??[];if(new Set(t.map(a=>a.name)).size!==t.length)throw new Error("Duplicate editor plugin.");let n=r.historyLimit??100;if(!Number.isInteger(n)||n<1||n>1e4)throw new RangeError("historyLimit must be an integer from 1 to 10000.");let o=C(r.value??""),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",r.label??"\u0422\u0435\u043A\u0441\u0442\u043E\u0432\u044B\u0439 \u0440\u0435\u0434\u0430\u043A\u0442\u043E\u0440"),s.dataset.placeholder=r.placeholder??"\u041D\u0430\u0447\u043D\u0438\u0442\u0435 \u043F\u0438\u0441\u0430\u0442\u044C\u2026",i.append(s),e.append(i),s.append(re(o)),de(s);let l=!1,c=r.readOnly??!1,d=!1,p,u,f=0,b="",m={},h,y=()=>{m={},h=void 0},x=()=>{let a=A(s);return a?.length===0&&a.index===h},T=[],S=[],K=new Set,Z=new Set,U=new Map,ee=[];r.onChange&&K.add(r.onChange);let L=()=>{if(l)throw new Error("Editor has been destroyed.")},v=()=>({html:oe(s.innerHTML),selection:X(s)}),H=v(),W=H.selection,P=()=>{if(l)return;A(s)&&!x()&&y();let a=X(s);a&&(W=a,H.selection=a);for(let g of Z)g()},ue=a=>{let g={html:k.getHTML(),text:k.getText(),source:a};for(let E of[...K])E(g);P()},me=(a,g="")=>{let E=A(s);de(s)&&E&&R(s,E.index,E.length);let N=v();if(N.html===a.html){H=N;return}let M=Date.now();g===b&&["insertText","deleteContentBackward","deleteContentForward"].includes(g)&&M-f<600&&a.selection&&H.selection&&JSON.stringify(a.selection)===JSON.stringify(H.selection)||(T.push(a),T.length>n&&T.shift()),S.length=0,H=N,f=g?M:0,b=g,ue("user")},xe=a=>{y(),s.innerHTML=a.html,de(s),s.focus({preventScroll:!0}),q(s,a.selection),H=v(),W=H.selection,f=0,ue("user")},J=(a,g="")=>{if(L(),c)return;k.focus();let E=v(),N=[...T],M=[...S];try{a(s),me(E,g)}catch(fe){throw s.innerHTML=E.html,q(s,E.selection),H=v(),T.splice(0,T.length,...N),S.splice(0,S.length,...M),fe}},k={element:i,surface:s,getHTML:()=>(L(),oe(s.innerHTML)),getText:()=>(L(),s.innerText),getJSON:()=>(L(),C(s.innerHTML)),setHTML:a=>{L();let g=j(C(a));g!==k.getHTML()&&(y(),s.innerHTML=g,de(s),T.length=0,S.length=0,f=0,W=void 0,H=v(),ue("api"))},setJSON:a=>{L();let g=ne(a);k.setHTML(j(g))},getSelection:()=>(L(),A(s)),setSelection:(a,g=0)=>{L(),R(s,a,g),P()},getFormats:()=>(L(),{...ce(s),...x()?m:{}}),setReadOnly:a=>{L(),c=a,s.contentEditable=String(!a),s.setAttribute("aria-readonly",String(a)),i.dataset.readonly=String(a),P()},isReadOnly:()=>(L(),c),format:(a,g)=>{if(L(),c)return;k.focus();let E=A(s);if(E?.length===0&&(Object.hasOwn(z,a)||Object.hasOwn(O,a))){x()||y(),h=E.index,m[a]=Object.hasOwn(O,a)?_(a,g):!!g,P();return}y(),k.transact(()=>ye(s,a,g))},insertHTML:a=>k.transact(()=>ot(s,a)),focus:()=>{L(),s.focus({preventScroll:!0}),w(s)||(W?q(s,W):se(s.firstElementChild??s,!0))},undo:()=>{if(L(),c)return;let a=T.pop();a&&(S.push(v()),xe(a))},redo:()=>{if(L(),c)return;let a=S.pop();a&&(T.push(v()),xe(a))},canUndo:()=>(L(),T.length>0),canRedo:()=>(L(),S.length>0),transact:a=>J(a),providePlugin:(a,g)=>{if(L(),U.has(a))throw new Error(`Plugin API already registered: ${a}`);return U.set(a,g),()=>{U.delete(a)}},getPlugin:a=>(L(),U.get(a)),subscribe:a=>(L(),K.add(a),()=>{K.delete(a)}),onSelectionChange:a=>(L(),Z.add(a),()=>{Z.delete(a)}),destroy:()=>{if(l)return;l=!0;let a=[];for(let g of ee.reverse())try{g()}catch(E){a.push(E)}if(K.clear(),Z.clear(),U.clear(),T.length=0,S.length=0,i.remove(),a.length)throw new AggregateError(a,"Editor cleanup failed.")}},I=(a,g)=>{s.addEventListener(a,g),ee.push(()=>s.removeEventListener(a,g))};I("beforeinput",a=>{if(c){a.preventDefault();return}if(a.inputType==="historyUndo"||a.inputType==="historyRedo"){a.preventDefault(),a.inputType==="historyUndo"?k.undo():k.redo();return}if(!d&&!a.isComposing&&pe(s,a.inputType)){a.preventDefault(),y(),u=void 0,J(()=>ge(s,a.inputType));return}if(a.inputType==="insertText"&&a.data&&!d&&!a.isComposing&&x()&&Object.keys(m).length){a.preventDefault();let g=A(s).index,E=a.data,N={...m};J(()=>{let M=w(s),F=(M.startContainer instanceof Element?M.startContainer:M.startContainer.parentElement)?.closest("p,h1,h2,h3,h4,h5,h6,li,blockquote,pre");F&&!F.textContent&&F.childNodes.length===1&&F.firstChild instanceof HTMLBRElement&&(F.replaceChildren(),M.selectNodeContents(F),M.collapse(!0)),M.insertNode(document.createTextNode(E)),R(s,g,E.length);for(let[te,Te]of Object.entries(N))(Object.hasOwn(O,te)?ce(s)[te]??!1:!!ce(s)[te])!==Te&&ye(s,te,Te);R(s,g+E.length),h=g+E.length},"insertText"),u=void 0;return}u=v()}),I("input",a=>{let g=a;if(c){s.innerHTML=H.html;return}d||g.isComposing||(me(u??H,g.inputType),u=void 0)}),I("compositionstart",()=>{y(),d=!0,p=v()}),I("compositionend",()=>{d=!1,p&&me(p),p=void 0,u=void 0}),I("paste",a=>{if(a.preventDefault(),c||!a.clipboardData)return;k.focus();let g=a.clipboardData.getData("text/html");if(g)k.insertHTML(g);else{let E=a.clipboardData.getData("text/plain"),N=document.createElement("div");N.textContent=E,k.insertHTML(N.innerHTML.replace(/\r?\n/g,"<br>"))}}),I("drop",a=>{a.preventDefault()}),I("keydown",a=>{if(!d&&!a.isComposing&&!c&&!a.ctrlKey&&!a.metaKey&&!a.altKey&&(a.key==="Enter"||a.key==="Backspace")){let N=a.key==="Backspace"?"deleteContentBackward":a.shiftKey?"insertLineBreak":"insertParagraph";if(pe(s,N)){a.preventDefault(),y(),u=void 0,J(()=>ge(s,N));return}}if(!d&&!a.isComposing&&!c&&a.key==="Tab"&&!a.ctrlKey&&!a.metaKey&&!a.altKey){let N=$(s);if(N.length&&N.every(M=>M.localName==="li"&&!M.closest("td,th"))&&Y(s).canOutdent){a.preventDefault(),y(),J(()=>le(s,a.shiftKey?-1:1));return}}if(d||a.isComposing||c||!(a.ctrlKey||a.metaKey)||a.altKey)return;let g=a.key.toLowerCase();(g==="z"||g==="y")&&(a.preventDefault(),g==="y"||a.shiftKey?k.redo():k.undo());let E={b:"bold",i:"italic",u:"underline"}[g];E&&(a.preventDefault(),k.format(E,k.getFormats().mixed?.includes(E)||!k.getFormats()[E]))}),document.addEventListener("selectionchange",P),ee.push(()=>document.removeEventListener("selectionchange",P));try{k.setReadOnly(c);for(let a of t){let g=a.setup(k);g&&ee.push(g)}return k}catch(a){throw k.destroy(),a}};export{Ct as createEditor,rt as createToolbar,oe 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,CAAC,OAAQ,OAAO,EAAI,CAAC,OAAQ,QAAS,SAAU,KAAK,GAAG,SAASE,CAAQ,IAE/F,EAAAD,EA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D,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/inline-attributes.ts", "../src/links.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 === 'a' && key === 'target' && ['_self', '_blank'].includes(value)) output.target = value;\n else if (tag === 'a' && key === 'rel') {\n const tokens = [...new Set(value.toLowerCase().split(/\\s+/).filter((token) => ['noopener', 'noreferrer'].includes(token)))];\n if (tokens.length) output.rel = tokens.join(' ');\n }\n else if (tag === 'th' && key === 'scope' && ['row', 'col', 'rowgroup', 'colgroup'].includes(value))\n output[key] = value;\n }\n if (tag === 'a' && output.target === '_blank') output.rel = 'noopener noreferrer';\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 { validateDocument } from './model.js';\nimport type { DocumentNode, EditorDocument, ElementNode } from './model.js';\n\nexport interface LinkFormat { href: string; title?: string; target?: '_self' | '_blank'; text?: string; }\nexport const inlineStyles: Record<string, string> = { color: 'color', background: 'background-color' };\nconst blocks = new Set(['p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'blockquote', 'pre', 'ul', 'ol', 'li', 'table', 'thead', 'tbody', 'tfoot', 'tr', 'td', 'th', 'caption', 'colgroup']);\ntype Attributes = Record<string, string>;\nconst checkedAttributes = (tag: 'span' | 'a', attributes: Attributes): Attributes => (validateDocument({ version: 1, children: [{ type: 'element', tag, attributes, children: [] }] }).children[0] as ElementNode).attributes;\nexport const normalizeInlineStyle = (name: string, value: unknown): string | false => {\n if (value === false) return false;\n if (typeof value !== 'string' || !value.trim() || value.length > 128 || /[;{}]/.test(value)) throw new TypeError('Expected a CSS color or false.');\n const property = inlineStyles[name];\n const attrs = checkedAttributes('span', { style: `${property}: ${value}` });\n const probe = document.createElement('span'); probe.setAttribute('style', attrs.style ?? '');\n const color = probe.style.getPropertyValue(property);\n if (!color) throw new TypeError('Unsupported or invalid CSS color.');\n return color;\n};\nexport const normalizeLink = (value: unknown): { attributes: Attributes; text?: string } | false => {\n if (value === false) return false;\n const input = typeof value === 'string' ? { href: value } : value;\n if (!input || typeof input !== 'object' || Array.isArray(input) || !('href' in input) || typeof input.href !== 'string') throw new TypeError('Expected a link URL, LinkFormat or false.');\n const link = input as Record<string, unknown>;\n const attributes: Attributes = { href: input.href };\n if (link.title !== undefined) {\n if (typeof link.title !== 'string' || link.title.length > 1024) throw new TypeError('Link title must be a string up to 1024 characters.');\n attributes.title = link.title;\n }\n if (link.target !== undefined) {\n if (link.target !== '_self' && link.target !== '_blank') throw new TypeError('Link target must be _self or _blank.');\n attributes.target = link.target;\n }\n if (link.text !== undefined && (typeof link.text !== 'string' || !link.text.length || link.text.length > 20000)) throw new TypeError('New link text must contain 1\u201320000 characters.');\n const clean = checkedAttributes('a', attributes);\n if (!clean.href) throw new TypeError('Unsupported or unsafe link URL.');\n return { attributes: clean, ...(typeof link.text === 'string' ? { text: link.text } : {}) };\n};\nexport const mergeLinkAttributes = (previous: Attributes, patch: Attributes): Attributes => {\n const attrs = { ...previous, ...patch };\n if (!attrs.title) delete attrs.title;\n if (patch.target === '_self') delete attrs.rel;\n return checkedAttributes('a', attrs);\n};\ntype Operation = { kind: 'style'; property: string; value: string | false } | { kind: 'link'; attributes: Attributes | false };\ninterface Piece { node: DocumentNode; selected: boolean; link?: Attributes; }\nconst equalAttributes = (a?: Attributes, b?: Attributes) => JSON.stringify(Object.entries(a ?? {}).sort()) === JSON.stringify(Object.entries(b ?? {}).sort());\nconst withoutProperty = (attributes: Attributes, property: string): Attributes => {\n const attrs = { ...attributes };\n const style = (attrs.style ?? '').split(';').map((part) => part.trim()).filter((part) => part && part.slice(0, part.indexOf(':')).trim() !== property).join('; ');\n if (style) attrs.style = style; else delete attrs.style;\n return attrs;\n};\nconst groupPieces = (pieces: Piece[]): { pieces: Piece[]; selected: boolean; link?: Attributes }[] => {\n const result: { pieces: Piece[]; selected: boolean; link?: Attributes }[] = [];\n for (const piece of pieces) {\n const last = result.at(-1);\n if (last && last.selected === piece.selected && equalAttributes(last.link, piece.link)) last.pieces.push(piece);\n else result.push({ pieces: [piece], selected: piece.selected, link: piece.link });\n }\n return result;\n};\nconst compact = (nodes: DocumentNode[]): DocumentNode[] => {\n const result: DocumentNode[] = [];\n for (const node of nodes) {\n const next = node.type === 'element' ? { ...node, children: compact(node.children) } : node;\n const previous = result.at(-1);\n if (next.type === 'text' && previous?.type === 'text') previous.text += next.text;\n else if (next.type === 'element' && previous?.type === 'element' && !blocks.has(next.tag) && !['img', 'br', 'hr'].includes(next.tag) && previous.tag === next.tag && equalAttributes(previous.attributes, next.attributes)) previous.children = compact([...previous.children, ...next.children]);\n else result.push(next);\n }\n return result;\n};\nexport const transformInlineAttributes = (document: EditorDocument, from: number, to: number, operation: Operation): EditorDocument => {\n let position = 0;\n const wrap = (pieces: Piece[]): DocumentNode[] => groupPieces(pieces).flatMap((group) => {\n const children = group.pieces.map((piece) => piece.node);\n if (operation.kind === 'style') return group.selected && operation.value !== false ? [{ type: 'element', tag: 'span', attributes: { style: `${operation.property}: ${operation.value}` }, children } as ElementNode] : children;\n const attrs = group.selected ? operation.attributes === false ? undefined : mergeLinkAttributes(group.link ?? {}, operation.attributes) : group.link;\n return attrs ? [{ type: 'element', tag: 'a', attributes: attrs, children } as ElementNode] : children;\n });\n const visit = (node: DocumentNode, inheritedLink?: Attributes): Piece[] => {\n if (node.type === 'text') {\n const start = position; position += node.text.length;\n const left = Math.max(0, Math.min(node.text.length, from - start)); const right = Math.max(left, Math.min(node.text.length, to - start));\n return [[0, left, false], [left, right, true], [right, node.text.length, false]].flatMap(([begin, end, selected]) => {\n const text = node.text.slice(begin as number, end as number);\n return text ? [{ node: { type: 'text', text } as DocumentNode, selected: Boolean(selected), link: inheritedLink }] : [];\n });\n }\n const link = operation.kind === 'link' && node.tag === 'a' ? node.attributes : inheritedLink;\n if (!node.children.length) return [{ node, selected: position >= from && position < to, link }];\n const children = node.children.flatMap((child) => visit(child, link));\n if (operation.kind === 'link' && node.tag === 'a') return children;\n if (blocks.has(node.tag)) return [{ node: { ...node, children: wrap(children) }, selected: false }];\n return groupPieces(children).flatMap<Piece>((group) => {\n const attrs = operation.kind === 'style' && group.selected ? withoutProperty(node.attributes, operation.property) : node.attributes;\n const content = group.pieces.map((piece) => piece.node);\n if (node.tag === 'span' && !Object.keys(attrs).length) return group.pieces;\n return [{ node: { ...node, attributes: attrs, children: content }, selected: group.selected, link: group.link }];\n });\n };\n return { version: 1, children: compact(wrap(document.children.flatMap((node) => visit(node)))) };\n};\n", "import { documentHTML, parseHTML } from './model.js';\nimport { normalizeLink, mergeLinkAttributes, transformInlineAttributes } from './inline-attributes.js';\nimport { activeRange, readTextSelection, selectText, preserveRange } from './selection.js';\n\nexport const applyLink = (root: HTMLElement, value: unknown): void => {\n const link = normalizeLink(value);\n const range = activeRange(root); if (!range) return;\n const selection = readTextSelection(root)!;\n const element = range.startContainer.nodeType === 1 ? range.startContainer as Element : range.startContainer.parentElement;\n const anchor = element?.closest('a');\n const existing = anchor && root.contains(anchor) ? anchor : undefined;\n if (link && link.text !== undefined && (!range.collapsed || existing)) throw new TypeError('Link text is only supported for insertion at a caret outside links.');\n if (!range.collapsed) {\n root.innerHTML = documentHTML(transformInlineAttributes(parseHTML(root.innerHTML), selection.index, selection.index + selection.length, { kind: 'link', attributes: link && link.attributes }));\n selectText(root, selection.index, selection.length); return;\n }\n if (existing) {\n const attrs = link && mergeLinkAttributes(Object.fromEntries([...existing.attributes].map((attr) => [attr.name, attr.value])), link.attributes);\n preserveRange(root, () => {\n if (!attrs) existing.replaceWith(...existing.childNodes);\n else { for (const attr of [...existing.attributes]) existing.removeAttribute(attr.name); for (const [key, val] of Object.entries(attrs)) existing.setAttribute(key, val); }\n });\n return;\n }\n if (!link || link.text === undefined) return;\n const created = root.ownerDocument.createElement('a');\n for (const [key, val] of Object.entries(link.attributes)) created.setAttribute(key, val);\n created.textContent = link.text;\n const parent = element?.closest('p,li,h1,h2,h3,h4,h5,h6,blockquote,pre,td,th');\n if (parent?.childNodes.length === 1 && parent.firstChild instanceof HTMLBRElement) { parent.firstChild.remove(); range.setStart(parent, 0); }\n range.insertNode(created);\n const tail = root.ownerDocument.createTextNode(''); created.after(tail);\n range.setStart(tail, 0); range.collapse(true);\n const native = root.ownerDocument.getSelection(); native?.removeAllRanges(); native?.addRange(range);\n};\n", "import type { DocumentNode, DocumentTag, EditorDocument, ElementNode } from './model.js';\nimport { documentHTML, parseHTML } from './model.js';\nimport { activeRange, readTextSelection, selectText, preserveRange } from './selection.js';\n\nimport { inlineStyles, normalizeInlineStyle, transformInlineAttributes } from './inline-attributes.js';\nimport { applyLink } from './links.js';\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'); formats.linkTitle = element.getAttribute('title') ?? ''; formats.linkTarget = element.getAttribute('target') ?? '_self'; }\n if (element instanceof HTMLElement) for (const [name, property] of Object.entries(inlineStyles)) if (formats[name] === undefined && element.style.getPropertyValue(property)) formats[name] = element.style.getPropertyValue(property);\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', 'linkTitle', 'linkTarget', 'color', 'background', 'align'];\n const normalized = (sample: Record<string, unknown>, key: string) => sample[key] ?? (key === 'align' ? 'left' : key === 'header' ? 0 : false);\n for (const key of keys) 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') { applyLink(root, value); return; }\n if (Object.hasOwn(inlineStyles, name)) {\n const color = normalizeInlineStyle(name, value);\n if (!selection.length) return;\n root.innerHTML = documentHTML(transformInlineAttributes(parseHTML(root.innerHTML), selection.index, selection.index + selection.length, { kind: 'style', property: inlineStyles[name], value: color }));\n selectText(root, selection.index, selection.length); 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 { inlineStyles, normalizeInlineStyle } from './inline-attributes.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 actions = actions.map((action) => action.format && Object.hasOwn(inlineStyles, action.format) ? { ...action, value: normalizeInlineStyle(action.format, action.value) } : action);\n const toolbar = document.createElement('div'); 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';\nimport { inlineStyles, normalizeInlineStyle } from './inline-attributes.js';\nexport type { LinkFormat } from './inline-attributes.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, 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) || Object.hasOwn(inlineStyles, name))) {\n if (!typingAtCaret()) clearTyping();\n typingOffset = selection.index; typingOverrides[name] = Object.hasOwn(inlineStyles, name) ? normalizeInlineStyle(name, value) : 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 ((Object.hasOwn(inlineStyles, name) ? readFormats(surface)[name] ?? false : 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,OAA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,EAC5DP,GAAU,KAAK,IAAM,SAAS,oBAAoB,kBAAmBO,CAAe,CAAC,EACrF,GAAI,CACFM,EAAO,YAAY7B,CAAQ,EAC3B,QAAWN,KAAUD,EAAS,CAC5B,IAAMoE,EAAUnE,EAAO,MAAMmC,CAAM,EAC/BgC,GACF7C,GAAU,KAAK6C,CAAO,CAC1B,CACA,OAAOhC,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", "tokens", "token", "readDOM", "node", "depth", "budget", "element", "original", "children", "child", "attributes", "attr", "parseHTML", "html", "template", "validateDocument", "count", "textLength", "visit", "attrs", "renderDocument", "fragment", "append", "parent", "documentHTML", "container", "sanitizeHTML", "activeRange", "root", "selection", "range", "nodePath", "target", "result", "node", "bookmark", "restoreBookmark", "saved", "resolve", "path", "index", "start", "end", "limit", "offset", "startOffset", "endOffset", "readTextSelection", "prefix", "selectText", "length", "value", "walker", "nodes", "current", "locate", "last", "placeCaret", "element", "preserveRange", "mutate", "native", "backward", "tail", "head", "next", "blocks", "isList", "element", "elementAt", "node", "blockAt", "root", "preferItem", "item", "block", "touches", "range", "content", "start", "end", "first", "last", "selectedBlocks", "activeRange", "preferItems", "found", "walker", "topItems", "items", "parent", "itemRange", "siblings", "depth", "result", "compatible", "a", "b", "joinLists", "list", "previous", "splitAround", "replacement", "tail", "ownContent", "unwrapRoot", "paragraphOnly", "paragraphNode", "paragraph", "nested", "output", "lift", "owner", "trailing", "listState", "canIndent", "child", "indentList", "direction", "preserveRange", "applyList", "value", "selected", "tag", "empty", "placeholder", "atStart", "prefix", "handlesListInput", "inputType", "editListInput", "next", "caret", "selection", "placeCaret", "br", "marker", "target", "inlineStyles", "blocks", "checkedAttributes", "tag", "attributes", "validateDocument", "normalizeInlineStyle", "name", "value", "property", "attrs", "probe", "color", "normalizeLink", "input", "link", "clean", "mergeLinkAttributes", "previous", "patch", "equalAttributes", "a", "b", "withoutProperty", "style", "part", "groupPieces", "pieces", "result", "piece", "last", "compact", "nodes", "node", "next", "transformInlineAttributes", "document", "from", "to", "operation", "position", "wrap", "group", "children", "visit", "inheritedLink", "start", "left", "right", "begin", "end", "selected", "text", "child", "content", "applyLink", "root", "value", "link", "normalizeLink", "range", "activeRange", "selection", "readTextSelection", "element", "anchor", "existing", "documentHTML", "transformInlineAttributes", "parseHTML", "selectText", "attrs", "mergeLinkAttributes", "attr", "preserveRange", "key", "val", "created", "parent", "tail", "native", "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", "property", "inlineStyles", "readFormats", "range", "activeRange", "mixed", "index", "length", "readTextSelection", "walker", "samples", "keys", "normalized", "sample", "key", "listState", "applyFormat", "selection", "applyList", "indentList", "content", "parseHTML", "documentHTML", "selectText", "applyLink", "color", "normalizeInlineStyle", "transformInlineAttributes", "blocks", "selectedBlocks", "paragraph", "preserveRange", "block", "nextTag", "replacement", "defaultActions", "editor", "createToolbar", "host", "actions", "options", "action", "inlineStyles", "normalizeInlineStyle", "toolbar", "saved", "disposed", "tabIndex", "cleanups", "buttons", "button", "down", "event", "click", "restoreBookmark", "formats", "mixed", "update", "bookmark", "index", "keyboard", "enabled", "direction", "next", "unsubscribe", "change", "unselect", "dispose", "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", "inlineStyles", "normalizeInlineStyle", "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,25 @@
1
+ import type { EditorDocument } from './model.js';
2
+ export interface LinkFormat {
3
+ href: string;
4
+ title?: string;
5
+ target?: '_self' | '_blank';
6
+ text?: string;
7
+ }
8
+ export declare const inlineStyles: Record<string, string>;
9
+ type Attributes = Record<string, string>;
10
+ export declare const normalizeInlineStyle: (name: string, value: unknown) => string | false;
11
+ export declare const normalizeLink: (value: unknown) => {
12
+ attributes: Attributes;
13
+ text?: string;
14
+ } | false;
15
+ export declare const mergeLinkAttributes: (previous: Attributes, patch: Attributes) => Attributes;
16
+ type Operation = {
17
+ kind: 'style';
18
+ property: string;
19
+ value: string | false;
20
+ } | {
21
+ kind: 'link';
22
+ attributes: Attributes | false;
23
+ };
24
+ export declare const transformInlineAttributes: (document: EditorDocument, from: number, to: number, operation: Operation) => EditorDocument;
25
+ export {};
@@ -0,0 +1 @@
1
+ export declare const applyLink: (root: HTMLElement, value: unknown) => void;
@@ -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": "1.0.1",
3
+ "version": "1.2.0",
4
4
  "type": "module",
5
5
  "files": [
6
6
  "dist"