@notectl/core 0.0.2 → 0.0.5
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/notectl-core.js +1195 -607
- package/dist/notectl-core.js.map +1 -1
- package/dist/notectl-core.umd.cjs +7 -3
- package/dist/notectl-core.umd.cjs.map +1 -1
- package/dist/types/index.d.ts +380 -1
- package/package.json +2 -2
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
(function(h,B){typeof exports=="object"&&typeof module<"u"?B(exports):typeof define=="function"&&define.amd?define(["exports"],B):(h=typeof globalThis<"u"?globalThis:h||self,B(h.NotectlCore={}))})(this,(function(h){"use strict";class B{constructor(t){this.nodes=new Map(t.nodes.map(e=>[e.type,e])),this.marks=new Map(t.marks.map(e=>[e.type,e])),this.topNode=t.topNode||"paragraph"}node(t){return this.nodes.get(t)}mark(t){return this.marks.get(t)}validateNode(t){const e=[];if("text"in t){const i=t;if(typeof i.text!="string"&&e.push("Text node must have a string text property"),i.marks)for(const o of i.marks)this.marks.has(o.type)||e.push(`Unknown mark type: ${o.type}`)}else{const i=t,o=this.nodes.get(i.type);if(!o)return e.push(`Unknown node type: ${i.type}`),{valid:!1,errors:e};if(o.attrs)for(const[a,u]of Object.entries(o.attrs))u.required&&(!i.attrs||!(a in i.attrs))&&e.push(`Required attribute missing: ${a}`),i.attrs?.[a]&&u.validate&&(u.validate(i.attrs[a])||e.push(`Invalid attribute value: ${a}`));if(i.children)for(const a of i.children){const u=this.validateNode(a);e.push(...u.errors)}}return{valid:e.length===0,errors:e}}markAllowedOn(t,e){const i=this.nodes.get(e);return!i||!i.marks?!1:i.marks==="_"?!0:i.marks.split(" ").includes(t)}marksCompatible(t,e){const i=this.marks.get(t),o=this.marks.get(e);return!(i?.excludes&&i.excludes.split(" ").includes(e)||o?.excludes&&o.excludes.split(" ").includes(t))}}function bt(){return new B({nodes:[{type:"paragraph",group:"block",content:"inline*",marks:"_"},{type:"heading",group:"block",content:"inline*",marks:"_",attrs:{level:{default:1,validate:r=>typeof r=="number"&&r>=1&&r<=6}}},{type:"list",group:"block",content:"list_item+"},{type:"list_item",content:"paragraph block*",defining:!0},{type:"table",group:"block",content:"table_row+",isolating:!0},{type:"table_row",content:"table_cell+"},{type:"table_cell",content:"block+",isolating:!0},{type:"image",group:"inline",attrs:{src:{required:!0},alt:{default:""},decorative:{default:!1}}},{type:"code_block",group:"block",content:"text*",marks:""},{type:"text",group:"inline"}],marks:[{type:"bold",excludes:""},{type:"italic",excludes:""},{type:"underline",excludes:""},{type:"strikethrough",excludes:""},{type:"code",excludes:"link"},{type:"link",attrs:{href:{required:!0},title:{default:""}},excludes:"code"}],topNode:"paragraph"})}function w(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,r=>{const t=Math.random()*16|0;return(r==="x"?t:t&3|8).toString(16)})}class Kt{constructor(t){this.schema=t}text(t,e){return{type:"text",text:t,marks:e||[]}}paragraph(t,e){return{id:w(),type:"paragraph",attrs:e,children:t||[]}}heading(t,e,i){return{id:w(),type:"heading",attrs:{...i,level:t},children:e||[]}}list(t,e){return{id:w(),type:"list",attrs:e,children:t}}listItem(t,e){return{id:w(),type:"list_item",attrs:e,children:t}}table(t,e){return{id:w(),type:"table",attrs:e,children:t}}tableRow(t,e){return{id:w(),type:"table_row",attrs:e,children:t}}tableCell(t,e){return{id:w(),type:"table_cell",attrs:e,children:t}}image(t,e,i){return{id:w(),type:"image",attrs:{src:t,alt:e||"",decorative:!e,...i},children:[]}}codeBlock(t,e){return{id:w(),type:"code_block",attrs:e,children:[this.text(t)]}}block(t,e,i){if(!this.schema.node(t))throw new Error(`Unknown node type: ${t}`);return{id:w(),type:t,attrs:e,children:i}}mark(t,e){if(!this.schema.mark(t))throw new Error(`Unknown mark type: ${t}`);return{type:t,attrs:e}}cloneNode(t,e){return{...t,id:w(),children:e!==void 0?e:t.children}}}function Vt(r){return new Kt(r)}class ${constructor(t,e,i){this.selection=null,this.history=[],this.historyIndex=-1,this.schema=e||bt(),this.nodeFactory=Vt(this.schema),this.maxHistoryDepth=i?.maxHistoryDepth||100,this.document=t||{version:0,schemaVersion:"1.0.0",children:[this.nodeFactory.paragraph()]}}getDocument(){return this.document}getVersion(){return this.document.version}getSelection(){return this.selection}setSelection(t){this.selection=t}applyDelta(t){if(t.baseVersion!==this.document.version)throw new Error(`Delta version mismatch: expected ${this.document.version}, got ${t.baseVersion}`);t.ops.some(i=>i.op!=="update_selection")&&this.addToHistory(t);for(const i of t.ops)this.applyOperation(i);this.document.version++}applyOperation(t){switch(t.op){case"insert_text":this.applyInsertText(t);break;case"delete_range":this.applyDeleteRange(t);break;case"apply_mark":this.applyMark(t);break;case"insert_block_after":this.applyInsertBlockAfter(t);break;case"insert_block_before":this.applyInsertBlockBefore(t);break;case"delete_block":this.applyDeleteBlock(t);break;case"set_attrs":this.applySetAttrs(t);break;case"update_selection":this.selection={anchor:t.selection.anchor,head:t.selection.head};break;default:console.warn("Unhandled operation type:",t.op)}}applyInsertText(t){const e=this.findBlock(t.target.blockId);if(!e||!e.children)return;const i=e.children.find(o=>"text"in o);if(i){const o=i.text.slice(0,t.target.offset),a=i.text.slice(t.target.offset);i.text=o+t.text+a,t.marks&&t.marks.length>0&&(i.marks=t.marks)}}applyDeleteRange(t){const e=this.findBlock(t.range.start.blockId);if(!e||!e.children)return;const i=e.children.find(o=>"text"in o);if(i){const o=i.text.slice(0,t.range.start.offset),a=i.text.slice(t.range.end.offset);i.text=o+a}}applyMark(t){const e=this.findBlock(t.range.start.blockId);if(!e||!e.children)return;const i=e.children.find(o=>"text"in o);i&&(t.add?(i.marks=i.marks||[],i.marks.some(o=>o.type===t.mark.type)||i.marks.push(t.mark)):i.marks=i.marks?.filter(o=>o.type!==t.mark.type))}applyInsertBlockAfter(t){const e=this.document.children.findIndex(i=>i.id===t.after);e!==-1&&this.document.children.splice(e+1,0,t.block)}applyInsertBlockBefore(t){const e=this.document.children.findIndex(i=>i.id===t.before);e!==-1&&this.document.children.splice(e,0,t.block)}applyDeleteBlock(t){const e=this.document.children.findIndex(i=>i.id===t.target.blockId);e!==-1&&this.document.children.splice(e,1)}applySetAttrs(t){const e=this.findBlock(t.target.blockId);e&&(e.attrs={...e.attrs,...t.attrs})}findBlock(t){const e=i=>{for(const o of i){if(o.id===t)return o;if(o.children){const a=o.children.filter(f=>"id"in f),u=e(a);if(u)return u}}};return e(this.document.children)}addToHistory(t){this.historyIndex<this.history.length-1&&(this.history=this.history.slice(0,this.historyIndex+1)),this.history.push({delta:t,inverseOps:t.inverseOps||[],timestamp:Date.now()}),this.history.length>this.maxHistoryDepth?this.history.shift():this.historyIndex++}canUndo(){return this.historyIndex>=0}undo(){if(!this.canUndo())return null;const t=this.history[this.historyIndex];return this.historyIndex--,{txnId:`undo-${t.delta.txnId}`,clientId:t.delta.clientId,timestamp:new Date().toISOString(),baseVersion:this.document.version,ltime:Date.now(),intent:"edit",ops:t.inverseOps}}canRedo(){return this.historyIndex<this.history.length-1}redo(){return this.canRedo()?(this.historyIndex++,this.history[this.historyIndex].delta):null}toJSON(){return this.document}static fromJSON(t,e){return new $(t,e)}}class Yt{constructor(){this.plugins=new Map,this.initializationOrder=[]}async register(t,e){if(this.plugins.has(t.id))throw new Error(`Plugin ${t.id} is already registered`);if(t.dependencies){for(const i of t.dependencies)if(!this.plugins.has(i))throw new Error(`Plugin ${t.id} depends on ${i} which is not registered`)}await t.init(e),this.plugins.set(t.id,t),this.initializationOrder.push(t.id),e.emit("plugin-registered",{pluginId:t.id,plugin:t})}async unregister(t,e){const i=this.plugins.get(t);if(!i)throw new Error(`Plugin ${t} is not registered`);for(const[o,a]of this.plugins.entries())if(a.dependencies?.includes(t))throw new Error(`Cannot unregister ${t}: plugin ${o} depends on it`);i.destroy&&await i.destroy(),this.plugins.delete(t),this.initializationOrder=this.initializationOrder.filter(o=>o!==t),e.emit("plugin-unregistered",{pluginId:t})}get(t){return this.plugins.get(t)}has(t){return this.plugins.has(t)}getAll(){return this.initializationOrder.map(t=>this.plugins.get(t))}notifyStateUpdate(t,e){for(const i of this.initializationOrder){const o=this.plugins.get(i);if(o?.onStateUpdate)try{o.onStateUpdate(t,e)}catch(a){console.error(`Error in plugin ${i} onStateUpdate:`,a)}}}notifyDeltaApplied(t){for(const e of this.initializationOrder){const i=this.plugins.get(e);if(i?.onDeltaApplied)try{i.onDeltaApplied(t)}catch(o){console.error(`Error in plugin ${e} onDeltaApplied:`,o)}}}async destroyAll(){const t=[...this.initializationOrder].reverse();for(const e of t){const i=this.plugins.get(e);if(i?.destroy)try{await i.destroy()}catch(o){console.error(`Error destroying plugin ${e}:`,o)}}this.plugins.clear(),this.initializationOrder=[]}}/*! @license DOMPurify 3.2.7 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/3.2.7/LICENSE */const{entries:jt,setPrototypeOf:Xt,isFrozen:Me,getPrototypeOf:Pe,getOwnPropertyDescriptor:Ue}=Object;let{freeze:S,seal:I,create:qt}=Object,{apply:_t,construct:xt}=typeof Reflect<"u"&&Reflect;S||(S=function(t){return t}),I||(I=function(t){return t}),_t||(_t=function(t,e){for(var i=arguments.length,o=new Array(i>2?i-2:0),a=2;a<i;a++)o[a-2]=arguments[a];return t.apply(e,o)}),xt||(xt=function(t){for(var e=arguments.length,i=new Array(e>1?e-1:0),o=1;o<e;o++)i[o-1]=arguments[o];return new t(...i)});const at=k(Array.prototype.forEach),He=k(Array.prototype.lastIndexOf),Zt=k(Array.prototype.pop),q=k(Array.prototype.push),Fe=k(Array.prototype.splice),lt=k(String.prototype.toLowerCase),St=k(String.prototype.toString),At=k(String.prototype.match),Z=k(String.prototype.replace),ze=k(String.prototype.indexOf),Be=k(String.prototype.trim),N=k(Object.prototype.hasOwnProperty),A=k(RegExp.prototype.test),J=$e(TypeError);function k(r){return function(t){t instanceof RegExp&&(t.lastIndex=0);for(var e=arguments.length,i=new Array(e>1?e-1:0),o=1;o<e;o++)i[o-1]=arguments[o];return _t(r,t,i)}}function $e(r){return function(){for(var t=arguments.length,e=new Array(t),i=0;i<t;i++)e[i]=arguments[i];return xt(r,e)}}function d(r,t){let e=arguments.length>2&&arguments[2]!==void 0?arguments[2]:lt;Xt&&Xt(r,null);let i=t.length;for(;i--;){let o=t[i];if(typeof o=="string"){const a=e(o);a!==o&&(Me(t)||(t[i]=a),o=a)}r[o]=!0}return r}function Ge(r){for(let t=0;t<r.length;t++)N(r,t)||(r[t]=null);return r}function M(r){const t=qt(null);for(const[e,i]of jt(r))N(r,e)&&(Array.isArray(i)?t[e]=Ge(i):i&&typeof i=="object"&&i.constructor===Object?t[e]=M(i):t[e]=i);return t}function Q(r,t){for(;r!==null;){const i=Ue(r,t);if(i){if(i.get)return k(i.get);if(typeof i.value=="function")return k(i.value)}r=Pe(r)}function e(){return null}return e}const Jt=S(["a","abbr","acronym","address","area","article","aside","audio","b","bdi","bdo","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dialog","dir","div","dl","dt","element","em","fieldset","figcaption","figure","font","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","img","input","ins","kbd","label","legend","li","main","map","mark","marquee","menu","menuitem","meter","nav","nobr","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","search","section","select","shadow","slot","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","tr","track","tt","u","ul","var","video","wbr"]),kt=S(["svg","a","altglyph","altglyphdef","altglyphitem","animatecolor","animatemotion","animatetransform","circle","clippath","defs","desc","ellipse","enterkeyhint","exportparts","filter","font","g","glyph","glyphref","hkern","image","inputmode","line","lineargradient","marker","mask","metadata","mpath","part","path","pattern","polygon","polyline","radialgradient","rect","slot","stop","style","switch","symbol","text","textpath","title","tref","tspan","view","vkern"]),Lt=S(["feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence"]),We=S(["animate","color-profile","cursor","discard","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignobject","hatch","hatchpath","mesh","meshgradient","meshpatch","meshrow","missing-glyph","script","set","solidcolor","unknown","use"]),Rt=S(["math","menclose","merror","mfenced","mfrac","mglyph","mi","mlabeledtr","mmultiscripts","mn","mo","mover","mpadded","mphantom","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msup","msubsup","mtable","mtd","mtext","mtr","munder","munderover","mprescripts"]),Ke=S(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),Qt=S(["#text"]),te=S(["accept","action","align","alt","autocapitalize","autocomplete","autopictureinpicture","autoplay","background","bgcolor","border","capture","cellpadding","cellspacing","checked","cite","class","clear","color","cols","colspan","controls","controlslist","coords","crossorigin","datetime","decoding","default","dir","disabled","disablepictureinpicture","disableremoteplayback","download","draggable","enctype","enterkeyhint","exportparts","face","for","headers","height","hidden","high","href","hreflang","id","inert","inputmode","integrity","ismap","kind","label","lang","list","loading","loop","low","max","maxlength","media","method","min","minlength","multiple","muted","name","nonce","noshade","novalidate","nowrap","open","optimum","part","pattern","placeholder","playsinline","popover","popovertarget","popovertargetaction","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","slot","span","srclang","start","src","srcset","step","style","summary","tabindex","title","translate","type","usemap","valign","value","width","wrap","xmlns","slot"]),Ct=S(["accent-height","accumulate","additive","alignment-baseline","amplitude","ascent","attributename","attributetype","azimuth","basefrequency","baseline-shift","begin","bias","by","class","clip","clippathunits","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","cx","cy","d","dx","dy","diffuseconstant","direction","display","divisor","dur","edgemode","elevation","end","exponent","fill","fill-opacity","fill-rule","filter","filterunits","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","fx","fy","g1","g2","glyph-name","glyphref","gradientunits","gradienttransform","height","href","id","image-rendering","in","in2","intercept","k","k1","k2","k3","k4","kerning","keypoints","keysplines","keytimes","lang","lengthadjust","letter-spacing","kernelmatrix","kernelunitlength","lighting-color","local","marker-end","marker-mid","marker-start","markerheight","markerunits","markerwidth","maskcontentunits","maskunits","max","mask","media","method","mode","min","name","numoctaves","offset","operator","opacity","order","orient","orientation","origin","overflow","paint-order","path","pathlength","patterncontentunits","patterntransform","patternunits","points","preservealpha","preserveaspectratio","primitiveunits","r","rx","ry","radius","refx","refy","repeatcount","repeatdur","restart","result","rotate","scale","seed","shape-rendering","slope","specularconstant","specularexponent","spreadmethod","startoffset","stddeviation","stitchtiles","stop-color","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke","stroke-width","style","surfacescale","systemlanguage","tabindex","tablevalues","targetx","targety","transform","transform-origin","text-anchor","text-decoration","text-rendering","textlength","type","u1","u2","unicode","values","viewbox","visibility","version","vert-adv-y","vert-origin-x","vert-origin-y","width","word-spacing","wrap","writing-mode","xchannelselector","ychannelselector","x","x1","x2","xmlns","y","y1","y2","z","zoomandpan"]),ee=S(["accent","accentunder","align","bevelled","close","columnsalign","columnlines","columnspan","denomalign","depth","dir","display","displaystyle","encoding","fence","frame","height","href","id","largeop","length","linethickness","lspace","lquote","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","rquote","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","voffset","width","xmlns"]),ct=S(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),Ve=I(/\{\{[\w\W]*|[\w\W]*\}\}/gm),Ye=I(/<%[\w\W]*|[\w\W]*%>/gm),je=I(/\$\{[\w\W]*/gm),Xe=I(/^data-[\-\w.\u00B7-\uFFFF]+$/),qe=I(/^aria-[\-\w]+$/),ne=I(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),Ze=I(/^(?:\w+script|data):/i),Je=I(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),ie=I(/^html$/i),Qe=I(/^[a-z][.\w]*(-[.\w]+)+$/i);var re=Object.freeze({__proto__:null,ARIA_ATTR:qe,ATTR_WHITESPACE:Je,CUSTOM_ELEMENT:Qe,DATA_ATTR:Xe,DOCTYPE_NAME:ie,ERB_EXPR:Ye,IS_ALLOWED_URI:ne,IS_SCRIPT_OR_DATA:Ze,MUSTACHE_EXPR:Ve,TMPLIT_EXPR:je});const tt={element:1,text:3,progressingInstruction:7,comment:8,document:9},tn=function(){return typeof window>"u"?null:window},en=function(t,e){if(typeof t!="object"||typeof t.createPolicy!="function")return null;let i=null;const o="data-tt-policy-suffix";e&&e.hasAttribute(o)&&(i=e.getAttribute(o));const a="dompurify"+(i?"#"+i:"");try{return t.createPolicy(a,{createHTML(u){return u},createScriptURL(u){return u}})}catch{return console.warn("TrustedTypes policy "+a+" could not be created."),null}},oe=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function se(){let r=arguments.length>0&&arguments[0]!==void 0?arguments[0]:tn();const t=c=>se(c);if(t.version="3.2.7",t.removed=[],!r||!r.document||r.document.nodeType!==tt.document||!r.Element)return t.isSupported=!1,t;let{document:e}=r;const i=e,o=i.currentScript,{DocumentFragment:a,HTMLTemplateElement:u,Node:f,Element:m,NodeFilter:C,NamedNodeMap:D=r.NamedNodeMap||r.MozNamedAttrMap,HTMLFormElement:dt,DOMParser:Cn,trustedTypes:ut}=r,nt=m.prototype,On=Q(nt,"cloneNode"),wn=Q(nt,"remove"),In=Q(nt,"nextSibling"),Nn=Q(nt,"childNodes"),ht=Q(nt,"parentNode");if(typeof u=="function"){const c=e.createElement("template");c.content&&c.content.ownerDocument&&(e=c.content.ownerDocument)}let L,it="";const{implementation:wt,createNodeIterator:Dn,createDocumentFragment:vn,getElementsByTagName:Mn}=e,{importNode:Pn}=i;let R=oe();t.isSupported=typeof jt=="function"&&typeof ht=="function"&&wt&&wt.createHTMLDocument!==void 0;const{MUSTACHE_EXPR:It,ERB_EXPR:Nt,TMPLIT_EXPR:Dt,DATA_ATTR:Un,ARIA_ATTR:Hn,IS_SCRIPT_OR_DATA:Fn,ATTR_WHITESPACE:de,CUSTOM_ELEMENT:zn}=re;let{IS_ALLOWED_URI:ue}=re,E=null;const he=d({},[...Jt,...kt,...Lt,...Rt,...Qt]);let b=null;const fe=d({},[...te,...Ct,...ee,...ct]);let g=Object.seal(qt(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),rt=null,vt=null,pe=!0,Mt=!0,me=!1,ge=!0,G=!1,ft=!0,F=!1,Pt=!1,Ut=!1,W=!1,pt=!1,mt=!1,ye=!0,Ee=!1;const Bn="user-content-";let Ht=!0,ot=!1,K={},V=null;const Te=d({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","style","svg","template","thead","title","video","xmp"]);let be=null;const _e=d({},["audio","video","img","source","image","track"]);let Ft=null;const xe=d({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),gt="http://www.w3.org/1998/Math/MathML",yt="http://www.w3.org/2000/svg",P="http://www.w3.org/1999/xhtml";let Y=P,zt=!1,Bt=null;const $n=d({},[gt,yt,P],St);let Et=d({},["mi","mo","mn","ms","mtext"]),Tt=d({},["annotation-xml"]);const Gn=d({},["title","style","font","a","script"]);let st=null;const Wn=["application/xhtml+xml","text/html"],Kn="text/html";let T=null,j=null;const Vn=e.createElement("form"),Se=function(n){return n instanceof RegExp||n instanceof Function},$t=function(){let n=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!(j&&j===n)){if((!n||typeof n!="object")&&(n={}),n=M(n),st=Wn.indexOf(n.PARSER_MEDIA_TYPE)===-1?Kn:n.PARSER_MEDIA_TYPE,T=st==="application/xhtml+xml"?St:lt,E=N(n,"ALLOWED_TAGS")?d({},n.ALLOWED_TAGS,T):he,b=N(n,"ALLOWED_ATTR")?d({},n.ALLOWED_ATTR,T):fe,Bt=N(n,"ALLOWED_NAMESPACES")?d({},n.ALLOWED_NAMESPACES,St):$n,Ft=N(n,"ADD_URI_SAFE_ATTR")?d(M(xe),n.ADD_URI_SAFE_ATTR,T):xe,be=N(n,"ADD_DATA_URI_TAGS")?d(M(_e),n.ADD_DATA_URI_TAGS,T):_e,V=N(n,"FORBID_CONTENTS")?d({},n.FORBID_CONTENTS,T):Te,rt=N(n,"FORBID_TAGS")?d({},n.FORBID_TAGS,T):M({}),vt=N(n,"FORBID_ATTR")?d({},n.FORBID_ATTR,T):M({}),K=N(n,"USE_PROFILES")?n.USE_PROFILES:!1,pe=n.ALLOW_ARIA_ATTR!==!1,Mt=n.ALLOW_DATA_ATTR!==!1,me=n.ALLOW_UNKNOWN_PROTOCOLS||!1,ge=n.ALLOW_SELF_CLOSE_IN_ATTR!==!1,G=n.SAFE_FOR_TEMPLATES||!1,ft=n.SAFE_FOR_XML!==!1,F=n.WHOLE_DOCUMENT||!1,W=n.RETURN_DOM||!1,pt=n.RETURN_DOM_FRAGMENT||!1,mt=n.RETURN_TRUSTED_TYPE||!1,Ut=n.FORCE_BODY||!1,ye=n.SANITIZE_DOM!==!1,Ee=n.SANITIZE_NAMED_PROPS||!1,Ht=n.KEEP_CONTENT!==!1,ot=n.IN_PLACE||!1,ue=n.ALLOWED_URI_REGEXP||ne,Y=n.NAMESPACE||P,Et=n.MATHML_TEXT_INTEGRATION_POINTS||Et,Tt=n.HTML_INTEGRATION_POINTS||Tt,g=n.CUSTOM_ELEMENT_HANDLING||{},n.CUSTOM_ELEMENT_HANDLING&&Se(n.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(g.tagNameCheck=n.CUSTOM_ELEMENT_HANDLING.tagNameCheck),n.CUSTOM_ELEMENT_HANDLING&&Se(n.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(g.attributeNameCheck=n.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),n.CUSTOM_ELEMENT_HANDLING&&typeof n.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements=="boolean"&&(g.allowCustomizedBuiltInElements=n.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),G&&(Mt=!1),pt&&(W=!0),K&&(E=d({},Qt),b=[],K.html===!0&&(d(E,Jt),d(b,te)),K.svg===!0&&(d(E,kt),d(b,Ct),d(b,ct)),K.svgFilters===!0&&(d(E,Lt),d(b,Ct),d(b,ct)),K.mathMl===!0&&(d(E,Rt),d(b,ee),d(b,ct))),n.ADD_TAGS&&(E===he&&(E=M(E)),d(E,n.ADD_TAGS,T)),n.ADD_ATTR&&(b===fe&&(b=M(b)),d(b,n.ADD_ATTR,T)),n.ADD_URI_SAFE_ATTR&&d(Ft,n.ADD_URI_SAFE_ATTR,T),n.FORBID_CONTENTS&&(V===Te&&(V=M(V)),d(V,n.FORBID_CONTENTS,T)),Ht&&(E["#text"]=!0),F&&d(E,["html","head","body"]),E.table&&(d(E,["tbody"]),delete rt.tbody),n.TRUSTED_TYPES_POLICY){if(typeof n.TRUSTED_TYPES_POLICY.createHTML!="function")throw J('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof n.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw J('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');L=n.TRUSTED_TYPES_POLICY,it=L.createHTML("")}else L===void 0&&(L=en(ut,o)),L!==null&&typeof it=="string"&&(it=L.createHTML(""));S&&S(n),j=n}},Ae=d({},[...kt,...Lt,...We]),ke=d({},[...Rt,...Ke]),Yn=function(n){let s=ht(n);(!s||!s.tagName)&&(s={namespaceURI:Y,tagName:"template"});const l=lt(n.tagName),p=lt(s.tagName);return Bt[n.namespaceURI]?n.namespaceURI===yt?s.namespaceURI===P?l==="svg":s.namespaceURI===gt?l==="svg"&&(p==="annotation-xml"||Et[p]):!!Ae[l]:n.namespaceURI===gt?s.namespaceURI===P?l==="math":s.namespaceURI===yt?l==="math"&&Tt[p]:!!ke[l]:n.namespaceURI===P?s.namespaceURI===yt&&!Tt[p]||s.namespaceURI===gt&&!Et[p]?!1:!ke[l]&&(Gn[l]||!Ae[l]):!!(st==="application/xhtml+xml"&&Bt[n.namespaceURI]):!1},v=function(n){q(t.removed,{element:n});try{ht(n).removeChild(n)}catch{wn(n)}},z=function(n,s){try{q(t.removed,{attribute:s.getAttributeNode(n),from:s})}catch{q(t.removed,{attribute:null,from:s})}if(s.removeAttribute(n),n==="is")if(W||pt)try{v(s)}catch{}else try{s.setAttribute(n,"")}catch{}},Le=function(n){let s=null,l=null;if(Ut)n="<remove></remove>"+n;else{const y=At(n,/^[\r\n\t ]+/);l=y&&y[0]}st==="application/xhtml+xml"&&Y===P&&(n='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+n+"</body></html>");const p=L?L.createHTML(n):n;if(Y===P)try{s=new Cn().parseFromString(p,st)}catch{}if(!s||!s.documentElement){s=wt.createDocument(Y,"template",null);try{s.documentElement.innerHTML=zt?it:p}catch{}}const x=s.body||s.documentElement;return n&&l&&x.insertBefore(e.createTextNode(l),x.childNodes[0]||null),Y===P?Mn.call(s,F?"html":"body")[0]:F?s.documentElement:x},Re=function(n){return Dn.call(n.ownerDocument||n,n,C.SHOW_ELEMENT|C.SHOW_COMMENT|C.SHOW_TEXT|C.SHOW_PROCESSING_INSTRUCTION|C.SHOW_CDATA_SECTION,null)},Gt=function(n){return n instanceof dt&&(typeof n.nodeName!="string"||typeof n.textContent!="string"||typeof n.removeChild!="function"||!(n.attributes instanceof D)||typeof n.removeAttribute!="function"||typeof n.setAttribute!="function"||typeof n.namespaceURI!="string"||typeof n.insertBefore!="function"||typeof n.hasChildNodes!="function")},Ce=function(n){return typeof f=="function"&&n instanceof f};function U(c,n,s){at(c,l=>{l.call(t,n,s,j)})}const Oe=function(n){let s=null;if(U(R.beforeSanitizeElements,n,null),Gt(n))return v(n),!0;const l=T(n.nodeName);if(U(R.uponSanitizeElement,n,{tagName:l,allowedTags:E}),ft&&n.hasChildNodes()&&!Ce(n.firstElementChild)&&A(/<[/\w!]/g,n.innerHTML)&&A(/<[/\w!]/g,n.textContent)||n.nodeType===tt.progressingInstruction||ft&&n.nodeType===tt.comment&&A(/<[/\w]/g,n.data))return v(n),!0;if(!E[l]||rt[l]){if(!rt[l]&&Ie(l)&&(g.tagNameCheck instanceof RegExp&&A(g.tagNameCheck,l)||g.tagNameCheck instanceof Function&&g.tagNameCheck(l)))return!1;if(Ht&&!V[l]){const p=ht(n)||n.parentNode,x=Nn(n)||n.childNodes;if(x&&p){const y=x.length;for(let O=y-1;O>=0;--O){const H=On(x[O],!0);H.__removalCount=(n.__removalCount||0)+1,p.insertBefore(H,In(n))}}}return v(n),!0}return n instanceof m&&!Yn(n)||(l==="noscript"||l==="noembed"||l==="noframes")&&A(/<\/no(script|embed|frames)/i,n.innerHTML)?(v(n),!0):(G&&n.nodeType===tt.text&&(s=n.textContent,at([It,Nt,Dt],p=>{s=Z(s,p," ")}),n.textContent!==s&&(q(t.removed,{element:n.cloneNode()}),n.textContent=s)),U(R.afterSanitizeElements,n,null),!1)},we=function(n,s,l){if(ye&&(s==="id"||s==="name")&&(l in e||l in Vn))return!1;if(!(Mt&&!vt[s]&&A(Un,s))){if(!(pe&&A(Hn,s))){if(!b[s]||vt[s]){if(!(Ie(n)&&(g.tagNameCheck instanceof RegExp&&A(g.tagNameCheck,n)||g.tagNameCheck instanceof Function&&g.tagNameCheck(n))&&(g.attributeNameCheck instanceof RegExp&&A(g.attributeNameCheck,s)||g.attributeNameCheck instanceof Function&&g.attributeNameCheck(s,n))||s==="is"&&g.allowCustomizedBuiltInElements&&(g.tagNameCheck instanceof RegExp&&A(g.tagNameCheck,l)||g.tagNameCheck instanceof Function&&g.tagNameCheck(l))))return!1}else if(!Ft[s]){if(!A(ue,Z(l,de,""))){if(!((s==="src"||s==="xlink:href"||s==="href")&&n!=="script"&&ze(l,"data:")===0&&be[n])){if(!(me&&!A(Fn,Z(l,de,"")))){if(l)return!1}}}}}}return!0},Ie=function(n){return n!=="annotation-xml"&&At(n,zn)},Ne=function(n){U(R.beforeSanitizeAttributes,n,null);const{attributes:s}=n;if(!s||Gt(n))return;const l={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:b,forceKeepAttr:void 0};let p=s.length;for(;p--;){const x=s[p],{name:y,namespaceURI:O,value:H}=x,X=T(y),Wt=H;let _=y==="value"?Wt:Be(Wt);if(l.attrName=X,l.attrValue=_,l.keepAttr=!0,l.forceKeepAttr=void 0,U(R.uponSanitizeAttribute,n,l),_=l.attrValue,Ee&&(X==="id"||X==="name")&&(z(y,n),_=Bn+_),ft&&A(/((--!?|])>)|<\/(style|title|textarea)/i,_)){z(y,n);continue}if(X==="attributename"&&At(_,"href")){z(y,n);continue}if(l.forceKeepAttr)continue;if(!l.keepAttr){z(y,n);continue}if(!ge&&A(/\/>/i,_)){z(y,n);continue}G&&at([It,Nt,Dt],ve=>{_=Z(_,ve," ")});const De=T(n.nodeName);if(!we(De,X,_)){z(y,n);continue}if(L&&typeof ut=="object"&&typeof ut.getAttributeType=="function"&&!O)switch(ut.getAttributeType(De,X)){case"TrustedHTML":{_=L.createHTML(_);break}case"TrustedScriptURL":{_=L.createScriptURL(_);break}}if(_!==Wt)try{O?n.setAttributeNS(O,y,_):n.setAttribute(y,_),Gt(n)?v(n):Zt(t.removed)}catch{z(y,n)}}U(R.afterSanitizeAttributes,n,null)},jn=function c(n){let s=null;const l=Re(n);for(U(R.beforeSanitizeShadowDOM,n,null);s=l.nextNode();)U(R.uponSanitizeShadowNode,s,null),Oe(s),Ne(s),s.content instanceof a&&c(s.content);U(R.afterSanitizeShadowDOM,n,null)};return t.sanitize=function(c){let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},s=null,l=null,p=null,x=null;if(zt=!c,zt&&(c="<!-->"),typeof c!="string"&&!Ce(c))if(typeof c.toString=="function"){if(c=c.toString(),typeof c!="string")throw J("dirty is not a string, aborting")}else throw J("toString is not a function");if(!t.isSupported)return c;if(Pt||$t(n),t.removed=[],typeof c=="string"&&(ot=!1),ot){if(c.nodeName){const H=T(c.nodeName);if(!E[H]||rt[H])throw J("root node is forbidden and cannot be sanitized in-place")}}else if(c instanceof f)s=Le("<!---->"),l=s.ownerDocument.importNode(c,!0),l.nodeType===tt.element&&l.nodeName==="BODY"||l.nodeName==="HTML"?s=l:s.appendChild(l);else{if(!W&&!G&&!F&&c.indexOf("<")===-1)return L&&mt?L.createHTML(c):c;if(s=Le(c),!s)return W?null:mt?it:""}s&&Ut&&v(s.firstChild);const y=Re(ot?c:s);for(;p=y.nextNode();)Oe(p),Ne(p),p.content instanceof a&&jn(p.content);if(ot)return c;if(W){if(pt)for(x=vn.call(s.ownerDocument);s.firstChild;)x.appendChild(s.firstChild);else x=s;return(b.shadowroot||b.shadowrootmode)&&(x=Pn.call(i,x,!0)),x}let O=F?s.outerHTML:s.innerHTML;return F&&E["!doctype"]&&s.ownerDocument&&s.ownerDocument.doctype&&s.ownerDocument.doctype.name&&A(ie,s.ownerDocument.doctype.name)&&(O="<!DOCTYPE "+s.ownerDocument.doctype.name+`>
|
|
2
|
-
`+
|
|
1
|
+
(function(u,z){typeof exports=="object"&&typeof module<"u"?z(exports):typeof define=="function"&&define.amd?define(["exports"],z):(u=typeof globalThis<"u"?globalThis:u||self,z(u.NotectlCore={}))})(this,(function(u){"use strict";class z{constructor(t){this.nodes=new Map(t.nodes.map(e=>[e.type,e])),this.marks=new Map(t.marks.map(e=>[e.type,e])),this.topNode=t.topNode||"paragraph"}node(t){return this.nodes.get(t)}mark(t){return this.marks.get(t)}validateNode(t){const e=[];if("text"in t){const n=t;if(typeof n.text!="string"&&e.push("Text node must have a string text property"),n.marks)for(const o of n.marks)this.marks.has(o.type)||e.push(`Unknown mark type: ${o.type}`)}else{const n=t,o=this.nodes.get(n.type);if(!o)return e.push(`Unknown node type: ${n.type}`),{valid:!1,errors:e};if(o.attrs)for(const[s,l]of Object.entries(o.attrs))l.required&&(!n.attrs||!(s in n.attrs))&&e.push(`Required attribute missing: ${s}`),n.attrs?.[s]&&l.validate&&(l.validate(n.attrs[s])||e.push(`Invalid attribute value: ${s}`));if(n.children)for(const s of n.children){const l=this.validateNode(s);e.push(...l.errors)}}return{valid:e.length===0,errors:e}}markAllowedOn(t,e){const n=this.nodes.get(e);return!n||!n.marks?!1:n.marks==="_"?!0:n.marks.split(" ").includes(t)}marksCompatible(t,e){const n=this.marks.get(t),o=this.marks.get(e);return!(n?.excludes&&n.excludes.split(" ").includes(e)||o?.excludes&&o.excludes.split(" ").includes(t))}}function bt(){return new z({nodes:[{type:"paragraph",group:"block",content:"inline*",marks:"_"},{type:"heading",group:"block",content:"inline*",marks:"_",attrs:{level:{default:1,validate:r=>typeof r=="number"&&r>=1&&r<=6}}},{type:"list",group:"block",content:"list_item+"},{type:"list_item",content:"paragraph block*",defining:!0},{type:"table",group:"block",content:"table_row+",isolating:!0},{type:"table_row",content:"table_cell+"},{type:"table_cell",content:"block+",isolating:!0},{type:"image",group:"inline",attrs:{src:{required:!0},alt:{default:""},decorative:{default:!1}}},{type:"code_block",group:"block",content:"text*",marks:""},{type:"text",group:"inline"}],marks:[{type:"bold",excludes:""},{type:"italic",excludes:""},{type:"underline",excludes:""},{type:"strikethrough",excludes:""},{type:"code",excludes:"link"},{type:"link",attrs:{href:{required:!0},title:{default:""}},excludes:"code"}],topNode:"paragraph"})}function w(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,r=>{const t=Math.random()*16|0;return(r==="x"?t:t&3|8).toString(16)})}class jt{constructor(t){this.schema=t}text(t,e){return{type:"text",text:t,marks:e||[]}}paragraph(t,e){return{id:w(),type:"paragraph",attrs:e,children:t||[]}}heading(t,e,n){return{id:w(),type:"heading",attrs:{...n,level:t},children:e||[]}}list(t,e){return{id:w(),type:"list",attrs:e,children:t}}listItem(t,e){return{id:w(),type:"list_item",attrs:e,children:t}}table(t,e){return{id:w(),type:"table",attrs:e,children:t}}tableRow(t,e){return{id:w(),type:"table_row",attrs:e,children:t}}tableCell(t,e){return{id:w(),type:"table_cell",attrs:e,children:t}}image(t,e,n){return{id:w(),type:"image",attrs:{src:t,alt:e||"",decorative:!e,...n},children:[]}}codeBlock(t,e){return{id:w(),type:"code_block",attrs:e,children:[this.text(t)]}}block(t,e,n){if(!this.schema.node(t))throw new Error(`Unknown node type: ${t}`);return{id:w(),type:t,attrs:e,children:n}}mark(t,e){if(!this.schema.mark(t))throw new Error(`Unknown mark type: ${t}`);return{type:t,attrs:e}}cloneNode(t,e){return{...t,id:w(),children:e!==void 0?e:t.children}}}function Kt(r){return new jt(r)}class V{constructor(t,e,n){this.selection=null,this.history=[],this.historyIndex=-1,this.schema=e||bt(),this.nodeFactory=Kt(this.schema),this.maxHistoryDepth=n?.maxHistoryDepth||100,this.document=t||{version:0,schemaVersion:"1.0.0",children:[this.nodeFactory.paragraph()]}}getDocument(){return this.document}getVersion(){return this.document.version}getSelection(){return this.selection}setSelection(t){this.selection=t}applyDelta(t){if(t.baseVersion!==this.document.version)throw new Error(`Delta version mismatch: expected ${this.document.version}, got ${t.baseVersion}`);t.ops.some(n=>n.op!=="update_selection")&&this.addToHistory(t);for(const n of t.ops)this.applyOperation(n);this.document.version++}applyOperation(t){switch(t.op){case"insert_text":this.applyInsertText(t);break;case"delete_range":this.applyDeleteRange(t);break;case"apply_mark":this.applyMark(t);break;case"insert_block_after":this.applyInsertBlockAfter(t);break;case"insert_block_before":this.applyInsertBlockBefore(t);break;case"delete_block":this.applyDeleteBlock(t);break;case"set_attrs":this.applySetAttrs(t);break;case"update_selection":this.selection={anchor:t.selection.anchor,head:t.selection.head};break;default:console.warn("Unhandled operation type:",t.op)}}applyInsertText(t){const e=this.findBlock(t.target.blockId);if(!e||!e.children)return;const n=e.children.find(o=>"text"in o);if(n){const o=n.text.slice(0,t.target.offset),s=n.text.slice(t.target.offset);n.text=o+t.text+s,t.marks&&t.marks.length>0&&(n.marks=t.marks)}}applyDeleteRange(t){const e=this.findBlock(t.range.start.blockId);if(!e||!e.children)return;const n=e.children.find(o=>"text"in o);if(n){const o=n.text.slice(0,t.range.start.offset),s=n.text.slice(t.range.end.offset);n.text=o+s}}applyMark(t){const e=this.findBlock(t.range.start.blockId);if(!e||!e.children)return;const n=e.children.find(o=>"text"in o);n&&(t.add?(n.marks=n.marks||[],n.marks.some(o=>o.type===t.mark.type)||n.marks.push(t.mark)):n.marks=n.marks?.filter(o=>o.type!==t.mark.type))}applyInsertBlockAfter(t){const e=this.document.children.findIndex(n=>n.id===t.after);e!==-1&&this.document.children.splice(e+1,0,t.block)}applyInsertBlockBefore(t){const e=this.document.children.findIndex(n=>n.id===t.before);e!==-1&&this.document.children.splice(e,0,t.block)}applyDeleteBlock(t){const e=this.document.children.findIndex(n=>n.id===t.target.blockId);e!==-1&&this.document.children.splice(e,1)}applySetAttrs(t){const e=this.findBlock(t.target.blockId);e&&(e.attrs={...e.attrs,...t.attrs})}findBlock(t){const e=n=>{for(const o of n){if(o.id===t)return o;if(o.children){const s=o.children.filter(h=>"id"in h),l=e(s);if(l)return l}}};return e(this.document.children)}addToHistory(t){this.historyIndex<this.history.length-1&&(this.history=this.history.slice(0,this.historyIndex+1)),this.history.push({delta:t,inverseOps:t.inverseOps||[],timestamp:Date.now()}),this.history.length>this.maxHistoryDepth?this.history.shift():this.historyIndex++}canUndo(){return this.historyIndex>=0}undo(){if(!this.canUndo())return null;const t=this.history[this.historyIndex];return this.historyIndex--,{txnId:`undo-${t.delta.txnId}`,clientId:t.delta.clientId,timestamp:new Date().toISOString(),baseVersion:this.document.version,ltime:Date.now(),intent:"edit",ops:t.inverseOps}}canRedo(){return this.historyIndex<this.history.length-1}redo(){return this.canRedo()?(this.historyIndex++,this.history[this.historyIndex].delta):null}toJSON(){return this.document}static fromJSON(t,e){return new V(t,e)}}const Ue=100,Fe=100,He=100,Ge=200,C={PLUGIN_ALREADY_REGISTERED:"PLUGIN_ALREADY_REGISTERED",PLUGIN_NOT_FOUND:"PLUGIN_NOT_FOUND",PLUGIN_MISSING_DEPENDENCY:"PLUGIN_MISSING_DEPENDENCY",PLUGIN_INVALID_CONFIG:"PLUGIN_INVALID_CONFIG",PLUGIN_INIT_FAILED:"PLUGIN_INIT_FAILED",PLUGIN_DESTROY_FAILED:"PLUGIN_DESTROY_FAILED",PLUGIN_DEPENDENCY_CONFLICT:"PLUGIN_DEPENDENCY_CONFLICT",EDITOR_NOT_MOUNTED:"EDITOR_NOT_MOUNTED",EDITOR_NOT_INITIALIZED:"EDITOR_NOT_INITIALIZED",EDITOR_DESTROYED:"EDITOR_DESTROYED",COMMAND_NOT_FOUND:"COMMAND_NOT_FOUND",COMMAND_ALREADY_REGISTERED:"COMMAND_ALREADY_REGISTERED",COMMAND_EXECUTION_FAILED:"COMMAND_EXECUTION_FAILED",COMMAND_INVALID_ARGS:"COMMAND_INVALID_ARGS",INVALID_CONTENT:"INVALID_CONTENT",INVALID_DELTA:"INVALID_DELTA",INVALID_DOCUMENT:"INVALID_DOCUMENT",SANITIZATION_FAILED:"SANITIZATION_FAILED",XSS_DETECTED:"XSS_DETECTED",UNSAFE_OPERATION:"UNSAFE_OPERATION",INVALID_OPERATION:"INVALID_OPERATION",INTERNAL_ERROR:"INTERNAL_ERROR"};class A extends Error{constructor(t,e,n){super(e),this.code=t,this.details=n,this.name="NotectlError",Error.captureStackTrace&&Error.captureStackTrace(this,A)}toJSON(){return{error:{code:this.code,message:this.message,details:this.details}}}}const Be={NO_DANGLING_REFS:"noDanglingRefs",TABLE_GRID_CONSISTENT:"tableGridConsistent",ALT_OR_DECORATIVE:"altOrDecorative",RTL_INTEGRITY:"rtlIntegrity"};class Xt{constructor(){this.plugins=new Map,this.initializationOrder=[]}async register(t,e){if(!t)throw new A(C.PLUGIN_INVALID_CONFIG,"Cannot register null or undefined plugin");if(!t.id||typeof t.id!="string")throw new A(C.PLUGIN_INVALID_CONFIG,'Plugin must have a valid string "id" property',{plugin:t});if(!t.name||typeof t.name!="string")throw new A(C.PLUGIN_INVALID_CONFIG,`Plugin "${t.id}" must have a valid string "name" property`,{pluginId:t.id});if(!t.version||typeof t.version!="string")throw new A(C.PLUGIN_INVALID_CONFIG,`Plugin "${t.id}" must have a valid string "version" property`,{pluginId:t.id,pluginName:t.name});if(typeof t.init!="function")throw new A(C.PLUGIN_INVALID_CONFIG,`Plugin "${t.id}" must have an "init" method`,{pluginId:t.id,pluginName:t.name});if(this.plugins.has(t.id)){const n=this.plugins.get(t.id);throw new A(C.PLUGIN_ALREADY_REGISTERED,`Plugin "${t.id}" is already registered (version: ${n.version})`,{pluginId:t.id,existingVersion:n.version,newVersion:t.version})}if(t.dependencies&&t.dependencies.length>0){const n=[];for(const o of t.dependencies)this.plugins.has(o)||n.push(o);if(n.length>0)throw new A(C.PLUGIN_MISSING_DEPENDENCY,`Plugin "${t.id}" (${t.name}) cannot be registered because the following dependencies are missing: ${n.join(", ")}. Please register these plugins first.`,{pluginId:t.id,pluginName:t.name,missingDependencies:n,registeredPlugins:Array.from(this.plugins.keys())})}try{await t.init(e)}catch(n){throw new A(C.PLUGIN_INIT_FAILED,`Failed to initialize plugin "${t.id}" (${t.name}): ${n instanceof Error?n.message:String(n)}`,{pluginId:t.id,pluginName:t.name,originalError:n})}this.plugins.set(t.id,t),this.initializationOrder.push(t.id),e.emit("plugin-registered",{pluginId:t.id,plugin:t})}async unregister(t,e){if(!t||typeof t!="string")throw new A(C.PLUGIN_NOT_FOUND,"Plugin ID must be a non-empty string",{pluginId:t});const n=this.plugins.get(t);if(!n)throw new A(C.PLUGIN_NOT_FOUND,`Plugin "${t}" is not registered and cannot be unregistered`,{pluginId:t,registeredPlugins:Array.from(this.plugins.keys())});const o=[];for(const[s,l]of this.plugins.entries())l.dependencies?.includes(t)&&o.push(`${s} (${l.name})`);if(o.length>0)throw new A(C.PLUGIN_DEPENDENCY_CONFLICT,`Cannot unregister plugin "${t}" (${n.name}) because the following plugins depend on it: ${o.join(", ")}. Please unregister dependent plugins first.`,{pluginId:t,pluginName:n.name,dependentPlugins:o});if(n.destroy)try{await n.destroy()}catch(s){throw new A(C.PLUGIN_DESTROY_FAILED,`Failed to destroy plugin "${t}" (${n.name}): ${s instanceof Error?s.message:String(s)}`,{pluginId:t,pluginName:n.name,originalError:s})}this.plugins.delete(t),this.initializationOrder=this.initializationOrder.filter(s=>s!==t),e.emit("plugin-unregistered",{pluginId:t})}get(t){return this.plugins.get(t)}has(t){return this.plugins.has(t)}getAll(){return this.initializationOrder.map(t=>this.plugins.get(t))}notifyStateUpdate(t,e){for(const n of this.initializationOrder){const o=this.plugins.get(n);if(o?.onStateUpdate)try{o.onStateUpdate(t,e)}catch(s){console.error(`Error in plugin ${n} onStateUpdate:`,s)}}}notifyDeltaApplied(t){for(const e of this.initializationOrder){const n=this.plugins.get(e);if(n?.onDeltaApplied)try{n.onDeltaApplied(t)}catch(o){console.error(`Error in plugin ${e} onDeltaApplied:`,o)}}}async destroyAll(){const t=[...this.initializationOrder].reverse();for(const e of t){const n=this.plugins.get(e);if(n?.destroy)try{await n.destroy()}catch(o){console.error(`Error destroying plugin ${e}:`,o)}}this.plugins.clear(),this.initializationOrder=[]}}/*! @license DOMPurify 3.2.7 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/3.2.7/LICENSE */const{entries:qt,setPrototypeOf:Zt,isFrozen:$e,getPrototypeOf:ze,getOwnPropertyDescriptor:Ve}=Object;let{freeze:D,seal:M,create:Jt}=Object,{apply:Nt,construct:At}=typeof Reflect<"u"&&Reflect;D||(D=function(t){return t}),M||(M=function(t){return t}),Nt||(Nt=function(t,e){for(var n=arguments.length,o=new Array(n>2?n-2:0),s=2;s<n;s++)o[s-2]=arguments[s];return t.apply(e,o)}),At||(At=function(t){for(var e=arguments.length,n=new Array(e>1?e-1:0),o=1;o<e;o++)n[o-1]=arguments[o];return new t(...n)});const ct=L(Array.prototype.forEach),We=L(Array.prototype.lastIndexOf),Qt=L(Array.prototype.pop),J=L(Array.prototype.push),Ye=L(Array.prototype.splice),dt=L(String.prototype.toLowerCase),Dt=L(String.prototype.toString),St=L(String.prototype.match),Q=L(String.prototype.replace),je=L(String.prototype.indexOf),Ke=L(String.prototype.trim),v=L(Object.prototype.hasOwnProperty),S=L(RegExp.prototype.test),tt=Xe(TypeError);function L(r){return function(t){t instanceof RegExp&&(t.lastIndex=0);for(var e=arguments.length,n=new Array(e>1?e-1:0),o=1;o<e;o++)n[o-1]=arguments[o];return Nt(r,t,n)}}function Xe(r){return function(){for(var t=arguments.length,e=new Array(t),n=0;n<t;n++)e[n]=arguments[n];return At(r,e)}}function f(r,t){let e=arguments.length>2&&arguments[2]!==void 0?arguments[2]:dt;Zt&&Zt(r,null);let n=t.length;for(;n--;){let o=t[n];if(typeof o=="string"){const s=e(o);s!==o&&($e(t)||(t[n]=s),o=s)}r[o]=!0}return r}function qe(r){for(let t=0;t<r.length;t++)v(r,t)||(r[t]=null);return r}function U(r){const t=Jt(null);for(const[e,n]of qt(r))v(r,e)&&(Array.isArray(n)?t[e]=qe(n):n&&typeof n=="object"&&n.constructor===Object?t[e]=U(n):t[e]=n);return t}function et(r,t){for(;r!==null;){const n=Ve(r,t);if(n){if(n.get)return L(n.get);if(typeof n.value=="function")return L(n.value)}r=ze(r)}function e(){return null}return e}const te=D(["a","abbr","acronym","address","area","article","aside","audio","b","bdi","bdo","big","blink","blockquote","body","br","button","canvas","caption","center","cite","code","col","colgroup","content","data","datalist","dd","decorator","del","details","dfn","dialog","dir","div","dl","dt","element","em","fieldset","figcaption","figure","font","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","img","input","ins","kbd","label","legend","li","main","map","mark","marquee","menu","menuitem","meter","nav","nobr","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","search","section","select","shadow","slot","small","source","spacer","span","strike","strong","style","sub","summary","sup","table","tbody","td","template","textarea","tfoot","th","thead","time","tr","track","tt","u","ul","var","video","wbr"]),Lt=D(["svg","a","altglyph","altglyphdef","altglyphitem","animatecolor","animatemotion","animatetransform","circle","clippath","defs","desc","ellipse","enterkeyhint","exportparts","filter","font","g","glyph","glyphref","hkern","image","inputmode","line","lineargradient","marker","mask","metadata","mpath","part","path","pattern","polygon","polyline","radialgradient","rect","slot","stop","style","switch","symbol","text","textpath","title","tref","tspan","view","vkern"]),Ot=D(["feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence"]),Ze=D(["animate","color-profile","cursor","discard","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignobject","hatch","hatchpath","mesh","meshgradient","meshpatch","meshrow","missing-glyph","script","set","solidcolor","unknown","use"]),kt=D(["math","menclose","merror","mfenced","mfrac","mglyph","mi","mlabeledtr","mmultiscripts","mn","mo","mover","mpadded","mphantom","mroot","mrow","ms","mspace","msqrt","mstyle","msub","msup","msubsup","mtable","mtd","mtext","mtr","munder","munderover","mprescripts"]),Je=D(["maction","maligngroup","malignmark","mlongdiv","mscarries","mscarry","msgroup","mstack","msline","msrow","semantics","annotation","annotation-xml","mprescripts","none"]),ee=D(["#text"]),ne=D(["accept","action","align","alt","autocapitalize","autocomplete","autopictureinpicture","autoplay","background","bgcolor","border","capture","cellpadding","cellspacing","checked","cite","class","clear","color","cols","colspan","controls","controlslist","coords","crossorigin","datetime","decoding","default","dir","disabled","disablepictureinpicture","disableremoteplayback","download","draggable","enctype","enterkeyhint","exportparts","face","for","headers","height","hidden","high","href","hreflang","id","inert","inputmode","integrity","ismap","kind","label","lang","list","loading","loop","low","max","maxlength","media","method","min","minlength","multiple","muted","name","nonce","noshade","novalidate","nowrap","open","optimum","part","pattern","placeholder","playsinline","popover","popovertarget","popovertargetaction","poster","preload","pubdate","radiogroup","readonly","rel","required","rev","reversed","role","rows","rowspan","spellcheck","scope","selected","shape","size","sizes","slot","span","srclang","start","src","srcset","step","style","summary","tabindex","title","translate","type","usemap","valign","value","width","wrap","xmlns","slot"]),xt=D(["accent-height","accumulate","additive","alignment-baseline","amplitude","ascent","attributename","attributetype","azimuth","basefrequency","baseline-shift","begin","bias","by","class","clip","clippathunits","clip-path","clip-rule","color","color-interpolation","color-interpolation-filters","color-profile","color-rendering","cx","cy","d","dx","dy","diffuseconstant","direction","display","divisor","dur","edgemode","elevation","end","exponent","fill","fill-opacity","fill-rule","filter","filterunits","flood-color","flood-opacity","font-family","font-size","font-size-adjust","font-stretch","font-style","font-variant","font-weight","fx","fy","g1","g2","glyph-name","glyphref","gradientunits","gradienttransform","height","href","id","image-rendering","in","in2","intercept","k","k1","k2","k3","k4","kerning","keypoints","keysplines","keytimes","lang","lengthadjust","letter-spacing","kernelmatrix","kernelunitlength","lighting-color","local","marker-end","marker-mid","marker-start","markerheight","markerunits","markerwidth","maskcontentunits","maskunits","max","mask","media","method","mode","min","name","numoctaves","offset","operator","opacity","order","orient","orientation","origin","overflow","paint-order","path","pathlength","patterncontentunits","patterntransform","patternunits","points","preservealpha","preserveaspectratio","primitiveunits","r","rx","ry","radius","refx","refy","repeatcount","repeatdur","restart","result","rotate","scale","seed","shape-rendering","slope","specularconstant","specularexponent","spreadmethod","startoffset","stddeviation","stitchtiles","stop-color","stop-opacity","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke","stroke-width","style","surfacescale","systemlanguage","tabindex","tablevalues","targetx","targety","transform","transform-origin","text-anchor","text-decoration","text-rendering","textlength","type","u1","u2","unicode","values","viewbox","visibility","version","vert-adv-y","vert-origin-x","vert-origin-y","width","word-spacing","wrap","writing-mode","xchannelselector","ychannelselector","x","x1","x2","xmlns","y","y1","y2","z","zoomandpan"]),ie=D(["accent","accentunder","align","bevelled","close","columnsalign","columnlines","columnspan","denomalign","depth","dir","display","displaystyle","encoding","fence","frame","height","href","id","largeop","length","linethickness","lspace","lquote","mathbackground","mathcolor","mathsize","mathvariant","maxsize","minsize","movablelimits","notation","numalign","open","rowalign","rowlines","rowspacing","rowspan","rspace","rquote","scriptlevel","scriptminsize","scriptsizemultiplier","selection","separator","separators","stretchy","subscriptshift","supscriptshift","symmetric","voffset","width","xmlns"]),ht=D(["xlink:href","xml:id","xlink:title","xml:space","xmlns:xlink"]),Qe=M(/\{\{[\w\W]*|[\w\W]*\}\}/gm),tn=M(/<%[\w\W]*|[\w\W]*%>/gm),en=M(/\$\{[\w\W]*/gm),nn=M(/^data-[\-\w.\u00B7-\uFFFF]+$/),rn=M(/^aria-[\-\w]+$/),re=M(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),on=M(/^(?:\w+script|data):/i),sn=M(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),oe=M(/^html$/i),an=M(/^[a-z][.\w]*(-[.\w]+)+$/i);var se=Object.freeze({__proto__:null,ARIA_ATTR:rn,ATTR_WHITESPACE:sn,CUSTOM_ELEMENT:an,DATA_ATTR:nn,DOCTYPE_NAME:oe,ERB_EXPR:tn,IS_ALLOWED_URI:re,IS_SCRIPT_OR_DATA:on,MUSTACHE_EXPR:Qe,TMPLIT_EXPR:en});const nt={element:1,text:3,progressingInstruction:7,comment:8,document:9},ln=function(){return typeof window>"u"?null:window},cn=function(t,e){if(typeof t!="object"||typeof t.createPolicy!="function")return null;let n=null;const o="data-tt-policy-suffix";e&&e.hasAttribute(o)&&(n=e.getAttribute(o));const s="dompurify"+(n?"#"+n:"");try{return t.createPolicy(s,{createHTML(l){return l},createScriptURL(l){return l}})}catch{return console.warn("TrustedTypes policy "+s+" could not be created."),null}},ae=function(){return{afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}};function le(){let r=arguments.length>0&&arguments[0]!==void 0?arguments[0]:ln();const t=d=>le(d);if(t.version="3.2.7",t.removed=[],!r||!r.document||r.document.nodeType!==nt.document||!r.Element)return t.isSupported=!1,t;let{document:e}=r;const n=e,o=n.currentScript,{DocumentFragment:s,HTMLTemplateElement:l,Node:h,Element:p,NodeFilter:y,NamedNodeMap:x=r.NamedNodeMap||r.MozNamedAttrMap,HTMLFormElement:ut,DOMParser:Un,trustedTypes:ft}=r,rt=p.prototype,Fn=et(rt,"cloneNode"),Hn=et(rt,"remove"),Gn=et(rt,"nextSibling"),Bn=et(rt,"childNodes"),pt=et(rt,"parentNode");if(typeof l=="function"){const d=e.createElement("template");d.content&&d.content.ownerDocument&&(e=d.content.ownerDocument)}let O,ot="";const{implementation:Ct,createNodeIterator:$n,createDocumentFragment:zn,getElementsByTagName:Vn}=e,{importNode:Wn}=n;let k=ae();t.isSupported=typeof qt=="function"&&typeof pt=="function"&&Ct&&Ct.createHTMLDocument!==void 0;const{MUSTACHE_EXPR:wt,ERB_EXPR:Mt,TMPLIT_EXPR:vt,DATA_ATTR:Yn,ARIA_ATTR:jn,IS_SCRIPT_OR_DATA:Kn,ATTR_WHITESPACE:ue,CUSTOM_ELEMENT:Xn}=se;let{IS_ALLOWED_URI:fe}=se,T=null;const pe=f({},[...te,...Lt,...Ot,...kt,...ee]);let I=null;const me=f({},[...ne,...xt,...ie,...ht]);let g=Object.seal(Jt(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),st=null,Pt=null,ge=!0,Ut=!0,Ee=!1,ye=!0,W=!1,mt=!0,B=!1,Ft=!1,Ht=!1,Y=!1,gt=!1,Et=!1,Te=!0,_e=!1;const qn="user-content-";let Gt=!0,at=!1,j={},K=null;const Ie=f({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","style","svg","template","thead","title","video","xmp"]);let be=null;const Ne=f({},["audio","video","img","source","image","track"]);let Bt=null;const Ae=f({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),yt="http://www.w3.org/1998/Math/MathML",Tt="http://www.w3.org/2000/svg",F="http://www.w3.org/1999/xhtml";let X=F,$t=!1,zt=null;const Zn=f({},[yt,Tt,F],Dt);let _t=f({},["mi","mo","mn","ms","mtext"]),It=f({},["annotation-xml"]);const Jn=f({},["title","style","font","a","script"]);let lt=null;const Qn=["application/xhtml+xml","text/html"],ti="text/html";let _=null,q=null;const ei=e.createElement("form"),De=function(i){return i instanceof RegExp||i instanceof Function},Vt=function(){let i=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};if(!(q&&q===i)){if((!i||typeof i!="object")&&(i={}),i=U(i),lt=Qn.indexOf(i.PARSER_MEDIA_TYPE)===-1?ti:i.PARSER_MEDIA_TYPE,_=lt==="application/xhtml+xml"?Dt:dt,T=v(i,"ALLOWED_TAGS")?f({},i.ALLOWED_TAGS,_):pe,I=v(i,"ALLOWED_ATTR")?f({},i.ALLOWED_ATTR,_):me,zt=v(i,"ALLOWED_NAMESPACES")?f({},i.ALLOWED_NAMESPACES,Dt):Zn,Bt=v(i,"ADD_URI_SAFE_ATTR")?f(U(Ae),i.ADD_URI_SAFE_ATTR,_):Ae,be=v(i,"ADD_DATA_URI_TAGS")?f(U(Ne),i.ADD_DATA_URI_TAGS,_):Ne,K=v(i,"FORBID_CONTENTS")?f({},i.FORBID_CONTENTS,_):Ie,st=v(i,"FORBID_TAGS")?f({},i.FORBID_TAGS,_):U({}),Pt=v(i,"FORBID_ATTR")?f({},i.FORBID_ATTR,_):U({}),j=v(i,"USE_PROFILES")?i.USE_PROFILES:!1,ge=i.ALLOW_ARIA_ATTR!==!1,Ut=i.ALLOW_DATA_ATTR!==!1,Ee=i.ALLOW_UNKNOWN_PROTOCOLS||!1,ye=i.ALLOW_SELF_CLOSE_IN_ATTR!==!1,W=i.SAFE_FOR_TEMPLATES||!1,mt=i.SAFE_FOR_XML!==!1,B=i.WHOLE_DOCUMENT||!1,Y=i.RETURN_DOM||!1,gt=i.RETURN_DOM_FRAGMENT||!1,Et=i.RETURN_TRUSTED_TYPE||!1,Ht=i.FORCE_BODY||!1,Te=i.SANITIZE_DOM!==!1,_e=i.SANITIZE_NAMED_PROPS||!1,Gt=i.KEEP_CONTENT!==!1,at=i.IN_PLACE||!1,fe=i.ALLOWED_URI_REGEXP||re,X=i.NAMESPACE||F,_t=i.MATHML_TEXT_INTEGRATION_POINTS||_t,It=i.HTML_INTEGRATION_POINTS||It,g=i.CUSTOM_ELEMENT_HANDLING||{},i.CUSTOM_ELEMENT_HANDLING&&De(i.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(g.tagNameCheck=i.CUSTOM_ELEMENT_HANDLING.tagNameCheck),i.CUSTOM_ELEMENT_HANDLING&&De(i.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(g.attributeNameCheck=i.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),i.CUSTOM_ELEMENT_HANDLING&&typeof i.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements=="boolean"&&(g.allowCustomizedBuiltInElements=i.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),W&&(Ut=!1),gt&&(Y=!0),j&&(T=f({},ee),I=[],j.html===!0&&(f(T,te),f(I,ne)),j.svg===!0&&(f(T,Lt),f(I,xt),f(I,ht)),j.svgFilters===!0&&(f(T,Ot),f(I,xt),f(I,ht)),j.mathMl===!0&&(f(T,kt),f(I,ie),f(I,ht))),i.ADD_TAGS&&(T===pe&&(T=U(T)),f(T,i.ADD_TAGS,_)),i.ADD_ATTR&&(I===me&&(I=U(I)),f(I,i.ADD_ATTR,_)),i.ADD_URI_SAFE_ATTR&&f(Bt,i.ADD_URI_SAFE_ATTR,_),i.FORBID_CONTENTS&&(K===Ie&&(K=U(K)),f(K,i.FORBID_CONTENTS,_)),Gt&&(T["#text"]=!0),B&&f(T,["html","head","body"]),T.table&&(f(T,["tbody"]),delete st.tbody),i.TRUSTED_TYPES_POLICY){if(typeof i.TRUSTED_TYPES_POLICY.createHTML!="function")throw tt('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if(typeof i.TRUSTED_TYPES_POLICY.createScriptURL!="function")throw tt('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');O=i.TRUSTED_TYPES_POLICY,ot=O.createHTML("")}else O===void 0&&(O=cn(ft,o)),O!==null&&typeof ot=="string"&&(ot=O.createHTML(""));D&&D(i),q=i}},Se=f({},[...Lt,...Ot,...Ze]),Le=f({},[...kt,...Je]),ni=function(i){let a=pt(i);(!a||!a.tagName)&&(a={namespaceURI:X,tagName:"template"});const c=dt(i.tagName),m=dt(a.tagName);return zt[i.namespaceURI]?i.namespaceURI===Tt?a.namespaceURI===F?c==="svg":a.namespaceURI===yt?c==="svg"&&(m==="annotation-xml"||_t[m]):!!Se[c]:i.namespaceURI===yt?a.namespaceURI===F?c==="math":a.namespaceURI===Tt?c==="math"&&It[m]:!!Le[c]:i.namespaceURI===F?a.namespaceURI===Tt&&!It[m]||a.namespaceURI===yt&&!_t[m]?!1:!Le[c]&&(Jn[c]||!Se[c]):!!(lt==="application/xhtml+xml"&&zt[i.namespaceURI]):!1},P=function(i){J(t.removed,{element:i});try{pt(i).removeChild(i)}catch{Hn(i)}},$=function(i,a){try{J(t.removed,{attribute:a.getAttributeNode(i),from:a})}catch{J(t.removed,{attribute:null,from:a})}if(a.removeAttribute(i),i==="is")if(Y||gt)try{P(a)}catch{}else try{a.setAttribute(i,"")}catch{}},Oe=function(i){let a=null,c=null;if(Ht)i="<remove></remove>"+i;else{const E=St(i,/^[\r\n\t ]+/);c=E&&E[0]}lt==="application/xhtml+xml"&&X===F&&(i='<html xmlns="http://www.w3.org/1999/xhtml"><head></head><body>'+i+"</body></html>");const m=O?O.createHTML(i):i;if(X===F)try{a=new Un().parseFromString(m,lt)}catch{}if(!a||!a.documentElement){a=Ct.createDocument(X,"template",null);try{a.documentElement.innerHTML=$t?ot:m}catch{}}const N=a.body||a.documentElement;return i&&c&&N.insertBefore(e.createTextNode(c),N.childNodes[0]||null),X===F?Vn.call(a,B?"html":"body")[0]:B?a.documentElement:N},ke=function(i){return $n.call(i.ownerDocument||i,i,y.SHOW_ELEMENT|y.SHOW_COMMENT|y.SHOW_TEXT|y.SHOW_PROCESSING_INSTRUCTION|y.SHOW_CDATA_SECTION,null)},Wt=function(i){return i instanceof ut&&(typeof i.nodeName!="string"||typeof i.textContent!="string"||typeof i.removeChild!="function"||!(i.attributes instanceof x)||typeof i.removeAttribute!="function"||typeof i.setAttribute!="function"||typeof i.namespaceURI!="string"||typeof i.insertBefore!="function"||typeof i.hasChildNodes!="function")},xe=function(i){return typeof h=="function"&&i instanceof h};function H(d,i,a){ct(d,c=>{c.call(t,i,a,q)})}const Re=function(i){let a=null;if(H(k.beforeSanitizeElements,i,null),Wt(i))return P(i),!0;const c=_(i.nodeName);if(H(k.uponSanitizeElement,i,{tagName:c,allowedTags:T}),mt&&i.hasChildNodes()&&!xe(i.firstElementChild)&&S(/<[/\w!]/g,i.innerHTML)&&S(/<[/\w!]/g,i.textContent)||i.nodeType===nt.progressingInstruction||mt&&i.nodeType===nt.comment&&S(/<[/\w]/g,i.data))return P(i),!0;if(!T[c]||st[c]){if(!st[c]&&we(c)&&(g.tagNameCheck instanceof RegExp&&S(g.tagNameCheck,c)||g.tagNameCheck instanceof Function&&g.tagNameCheck(c)))return!1;if(Gt&&!K[c]){const m=pt(i)||i.parentNode,N=Bn(i)||i.childNodes;if(N&&m){const E=N.length;for(let R=E-1;R>=0;--R){const G=Fn(N[R],!0);G.__removalCount=(i.__removalCount||0)+1,m.insertBefore(G,Gn(i))}}}return P(i),!0}return i instanceof p&&!ni(i)||(c==="noscript"||c==="noembed"||c==="noframes")&&S(/<\/no(script|embed|frames)/i,i.innerHTML)?(P(i),!0):(W&&i.nodeType===nt.text&&(a=i.textContent,ct([wt,Mt,vt],m=>{a=Q(a,m," ")}),i.textContent!==a&&(J(t.removed,{element:i.cloneNode()}),i.textContent=a)),H(k.afterSanitizeElements,i,null),!1)},Ce=function(i,a,c){if(Te&&(a==="id"||a==="name")&&(c in e||c in ei))return!1;if(!(Ut&&!Pt[a]&&S(Yn,a))){if(!(ge&&S(jn,a))){if(!I[a]||Pt[a]){if(!(we(i)&&(g.tagNameCheck instanceof RegExp&&S(g.tagNameCheck,i)||g.tagNameCheck instanceof Function&&g.tagNameCheck(i))&&(g.attributeNameCheck instanceof RegExp&&S(g.attributeNameCheck,a)||g.attributeNameCheck instanceof Function&&g.attributeNameCheck(a,i))||a==="is"&&g.allowCustomizedBuiltInElements&&(g.tagNameCheck instanceof RegExp&&S(g.tagNameCheck,c)||g.tagNameCheck instanceof Function&&g.tagNameCheck(c))))return!1}else if(!Bt[a]){if(!S(fe,Q(c,ue,""))){if(!((a==="src"||a==="xlink:href"||a==="href")&&i!=="script"&&je(c,"data:")===0&&be[i])){if(!(Ee&&!S(Kn,Q(c,ue,"")))){if(c)return!1}}}}}}return!0},we=function(i){return i!=="annotation-xml"&&St(i,Xn)},Me=function(i){H(k.beforeSanitizeAttributes,i,null);const{attributes:a}=i;if(!a||Wt(i))return;const c={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:I,forceKeepAttr:void 0};let m=a.length;for(;m--;){const N=a[m],{name:E,namespaceURI:R,value:G}=N,Z=_(E),Yt=G;let b=E==="value"?Yt:Ke(Yt);if(c.attrName=Z,c.attrValue=b,c.keepAttr=!0,c.forceKeepAttr=void 0,H(k.uponSanitizeAttribute,i,c),b=c.attrValue,_e&&(Z==="id"||Z==="name")&&($(E,i),b=qn+b),mt&&S(/((--!?|])>)|<\/(style|title|textarea)/i,b)){$(E,i);continue}if(Z==="attributename"&&St(b,"href")){$(E,i);continue}if(c.forceKeepAttr)continue;if(!c.keepAttr){$(E,i);continue}if(!ye&&S(/\/>/i,b)){$(E,i);continue}W&&ct([wt,Mt,vt],Pe=>{b=Q(b,Pe," ")});const ve=_(i.nodeName);if(!Ce(ve,Z,b)){$(E,i);continue}if(O&&typeof ft=="object"&&typeof ft.getAttributeType=="function"&&!R)switch(ft.getAttributeType(ve,Z)){case"TrustedHTML":{b=O.createHTML(b);break}case"TrustedScriptURL":{b=O.createScriptURL(b);break}}if(b!==Yt)try{R?i.setAttributeNS(R,E,b):i.setAttribute(E,b),Wt(i)?P(i):Qt(t.removed)}catch{$(E,i)}}H(k.afterSanitizeAttributes,i,null)},ii=function d(i){let a=null;const c=ke(i);for(H(k.beforeSanitizeShadowDOM,i,null);a=c.nextNode();)H(k.uponSanitizeShadowNode,a,null),Re(a),Me(a),a.content instanceof s&&d(a.content);H(k.afterSanitizeShadowDOM,i,null)};return t.sanitize=function(d){let i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},a=null,c=null,m=null,N=null;if($t=!d,$t&&(d="<!-->"),typeof d!="string"&&!xe(d))if(typeof d.toString=="function"){if(d=d.toString(),typeof d!="string")throw tt("dirty is not a string, aborting")}else throw tt("toString is not a function");if(!t.isSupported)return d;if(Ft||Vt(i),t.removed=[],typeof d=="string"&&(at=!1),at){if(d.nodeName){const G=_(d.nodeName);if(!T[G]||st[G])throw tt("root node is forbidden and cannot be sanitized in-place")}}else if(d instanceof h)a=Oe("<!---->"),c=a.ownerDocument.importNode(d,!0),c.nodeType===nt.element&&c.nodeName==="BODY"||c.nodeName==="HTML"?a=c:a.appendChild(c);else{if(!Y&&!W&&!B&&d.indexOf("<")===-1)return O&&Et?O.createHTML(d):d;if(a=Oe(d),!a)return Y?null:Et?ot:""}a&&Ht&&P(a.firstChild);const E=ke(at?d:a);for(;m=E.nextNode();)Re(m),Me(m),m.content instanceof s&&ii(m.content);if(at)return d;if(Y){if(gt)for(N=zn.call(a.ownerDocument);a.firstChild;)N.appendChild(a.firstChild);else N=a;return(I.shadowroot||I.shadowrootmode)&&(N=Wn.call(n,N,!0)),N}let R=B?a.outerHTML:a.innerHTML;return B&&T["!doctype"]&&a.ownerDocument&&a.ownerDocument.doctype&&a.ownerDocument.doctype.name&&S(oe,a.ownerDocument.doctype.name)&&(R="<!DOCTYPE "+a.ownerDocument.doctype.name+`>
|
|
2
|
+
`+R),W&&ct([wt,Mt,vt],G=>{R=Q(R,G," ")}),O&&Et?O.createHTML(R):R},t.setConfig=function(){let d=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};Vt(d),Ft=!0},t.clearConfig=function(){q=null,Ft=!1},t.isValidAttribute=function(d,i,a){q||Vt({});const c=_(d),m=_(i);return Ce(c,m,a)},t.addHook=function(d,i){typeof i=="function"&&J(k[d],i)},t.removeHook=function(d,i){if(i!==void 0){const a=We(k[d],i);return a===-1?void 0:Ye(k[d],a,1)[0]}return Qt(k[d])},t.removeHooks=function(d){k[d]=[]},t.removeAllHooks=function(){k=ae()},t}var dn=le();const hn={ALLOWED_TAGS:["p","br","strong","em","u","s","code","pre","h1","h2","h3","h4","h5","h6","ul","ol","li","blockquote","a","img","table","thead","tbody","tr","th","td","div","span"],ALLOWED_ATTR:["href","src","alt","title","class","id","style","data-*","role","aria-*"],ALLOWED_URI_REGEXP:/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i,KEEP_CONTENT:!0,SANITIZE_DOM:!0,SAFE_FOR_TEMPLATES:!0},un={ALLOWED_TAGS:["p","br","strong","em","u","code"],ALLOWED_ATTR:[],KEEP_CONTENT:!0,SANITIZE_DOM:!0,SAFE_FOR_TEMPLATES:!0};function it(r,t=!1){const e=t?un:hn;return dn.sanitize(r,e)}function fn(r,t=!0){return t?it(r):pn(r)}function pn(r){const t=document.createElement("div");return t.textContent=r,t.innerHTML}function mn(r){try{if(!r||typeof r!="object"||!Array.isArray(r.ops))return!1;for(const t of r.ops){if("insert"in t){const e=t.insert;if(typeof e=="string"&&it(e)!==e&&e.includes("<script"))return!1;if(typeof e=="object"&&e!==null){const n=e;if("script"in n||"onerror"in n||"onclick"in n)return!1}}if("attributes"in t&&t.attributes){const e=t.attributes;for(const n in e)if(n.startsWith("on")||n.toLowerCase().includes("script"))return!1}}return!0}catch(t){return console.error("Error validating delta:",t),!1}}function ce(r,t="polite"){let e=document.getElementById("notectl-sr-live");e?e.setAttribute("aria-live",t):(e=document.createElement("div"),e.id="notectl-sr-live",e.setAttribute("role","status"),e.setAttribute("aria-live",t),e.setAttribute("aria-atomic","true"),e.style.position="absolute",e.style.left="-10000px",e.style.width="1px",e.style.height="1px",e.style.overflow="hidden",document.body.appendChild(e)),e.textContent="",setTimeout(()=>{e.textContent=r},100)}function gn(r,t){const e=n=>{for(const o of r){const s=o.ctrlKey?n.ctrlKey:!0,l=o.metaKey?n.metaKey:!0,h=o.shiftKey?n.shiftKey:!n.shiftKey,p=o.altKey?n.altKey:!n.altKey;if(n.key.toLowerCase()===o.key.toLowerCase()&&s&&l&&h&&p){n.preventDefault(),o.action(),ce(o.description);break}}};return t.addEventListener("keydown",e),()=>{t.removeEventListener("keydown",e)}}function En(r,t){for(const[e,n]of Object.entries(t)){const o=e.startsWith("aria-")?e:`aria-${e}`;r.setAttribute(o,String(n))}}class Rt extends HTMLElement{constructor(){super(),this.eventListeners=new Map,this.commands=new Map,this.contentElement=null,this.pluginContainerTop=null,this.pluginContainerBottom=null,this.ariaLiveRegion=null,this.pendingPlugins=[],this.isReady=!1,this.handleInput=e=>{this.updatePlaceholder(),e.target?.closest('[data-node-type="table"]')||this.syncContentToState(),this.emit("change",{state:this.state})},this.handleKeydown=e=>{this.emit("keydown",e),!e.defaultPrevented&&((e.ctrlKey||e.metaKey)&&e.key==="z"&&(e.preventDefault(),e.shiftKey?(this.redo(),this.announceToScreenReader("Action redone")):(this.undo(),this.announceToScreenReader("Action undone"))),["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"].includes(e.key)&&(e.ctrlKey||e.metaKey)&&this.announceToScreenReader(`Navigating ${e.key.replace("Arrow","").toLowerCase()}`))},this.handleFocus=()=>{this.emit("focus",{state:this.state})},this.handleBlur=()=>{this.emit("blur",{state:this.state})},this.handleContextMenu=e=>{this.emit("contextmenu",e)},this.config={placeholder:"Start typing...",readonly:!1,autofocus:!1,sanitizeHTML:!0,maxHistoryDepth:100};const t=bt();this.state=new V(void 0,t,{maxHistoryDepth:this.config.maxHistoryDepth}),this.pluginManager=new Xt,this.readyPromise=new Promise(e=>{this.readyResolve=e}),this.attachShadow({mode:"open"})}static get observedAttributes(){return["placeholder","readonly","autofocus"]}async connectedCallback(){if(this.render(),this.attachEventListeners(),this.setupAccessibility(),this.setupKeyboardShortcuts(),this.isReady=!0,this.pendingPlugins.length>0){const t=[...this.pendingPlugins];this.pendingPlugins=[];for(const e of t)try{await this.pluginManager.register(e,this.createPluginContext())}catch(n){console.error(`Failed to register pending plugin ${e.id}:`,n)}}this.readyResolve&&this.readyResolve(),this.emit("ready",{editor:this}),this.config.autofocus&&this.focus()}disconnectedCallback(){this.detachEventListeners(),this.pluginManager.destroyAll(),this.keyboardShortcutCleanup&&this.keyboardShortcutCleanup(),this.ariaLiveRegion&&this.ariaLiveRegion.parentNode&&this.ariaLiveRegion.parentNode.removeChild(this.ariaLiveRegion),this.isReady=!1,this.readyPromise=new Promise(t=>{this.readyResolve=t})}attributeChangedCallback(t,e,n){if(e!==n)switch(t){case"placeholder":this.config.placeholder=n||"",this.updatePlaceholder();break;case"readonly":this.config.readonly=n!==null,this.updateReadonly();break;case"autofocus":this.config.autofocus=n!==null;break}}render(){this.shadowRoot&&(this.shadowRoot.innerHTML=`
|
|
3
3
|
<style>
|
|
4
4
|
:host {
|
|
5
5
|
display: block;
|
|
@@ -109,5 +109,9 @@
|
|
|
109
109
|
Press Ctrl+Z to undo, Ctrl+Shift+Z to redo.
|
|
110
110
|
</div>
|
|
111
111
|
<div id="notectl-aria-live" role="status" aria-live="polite" aria-atomic="true" class="visually-hidden"></div>
|
|
112
|
-
`,this.contentElement=this.shadowRoot.querySelector(".notectl-editor"),this.pluginContainerTop=this.shadowRoot.querySelector('.notectl-plugin-container[data-position="top"]'),this.pluginContainerBottom=this.shadowRoot.querySelector('.notectl-plugin-container[data-position="bottom"]'),this.ariaLiveRegion=this.shadowRoot.querySelector("#notectl-aria-live"),this.renderContent())}renderContent(){if(!this.contentElement)return;const t=this.state.getDocument(),e=this.documentToHTML(t);this.contentElement.innerHTML=this.config.sanitizeHTML?et(e):e}documentToHTML(t){return t.children.map(e=>this.blockToHTML(e)).join("")}blockToHTML(t){switch(t.type){case"paragraph":return`<p>${this.childrenToHTML(t.children||[])}</p>`;case"heading":const e=t.attrs?.level||1;return`<h${e}>${this.childrenToHTML(t.children||[])}</h${e}>`;default:return`<div>${this.childrenToHTML(t.children||[])}</div>`}}childrenToHTML(t){return t.map(e=>{if(e.type==="text"){let i=this.escapeHTML(e.text);if(e.marks)for(const o of e.marks)i=this.applyMarkHTML(i,o);return i}return this.blockToHTML(e)}).join("")}applyMarkHTML(t,e){switch(e.type){case"bold":return`<strong>${t}</strong>`;case"italic":return`<em>${t}</em>`;case"underline":return`<u>${t}</u>`;case"strikethrough":return`<s>${t}</s>`;case"code":return`<code>${t}</code>`;default:return t}}escapeHTML(t){if(!this.config.sanitizeHTML)return t;const e=document.createElement("div");return e.textContent=t,e.innerHTML}setupAccessibility(){this.contentElement&&(dn(this.contentElement,{role:"textbox","aria-multiline":!0,"aria-label":"Rich text editor","aria-describedby":"notectl-help-text","aria-autocomplete":"none"}),this.config.readonly&&this.contentElement.setAttribute("aria-readonly","true"))}setupKeyboardShortcuts(){if(!this.contentElement)return;const t=[{key:"b",ctrlKey:!0,description:"Bold formatting applied",action:()=>this.toggleFormat("bold")},{key:"i",ctrlKey:!0,description:"Italic formatting applied",action:()=>this.toggleFormat("italic")},{key:"u",ctrlKey:!0,description:"Underline formatting applied",action:()=>this.toggleFormat("underline")},{key:"z",ctrlKey:!0,description:"Action undone",action:()=>this.undo()},{key:"z",ctrlKey:!0,shiftKey:!0,description:"Action redone",action:()=>this.redo()}];this.keyboardShortcutCleanup=cn(t,this.contentElement)}toggleFormat(t){const e=window.getSelection();if(!(!e||!this.contentElement))try{switch(t){case"bold":document.execCommand("bold",!1);break;case"italic":document.execCommand("italic",!1);break;case"underline":document.execCommand("underline",!1);break;case"strikethrough":document.execCommand("strikeThrough",!1);break;case"code":const i=document.createElement("code");if(e.rangeCount>0){const o=e.getRangeAt(0);i.appendChild(o.extractContents()),o.insertNode(i)}break}this.announceToScreenReader(`${t} formatting applied`),this.emit("change",{state:this.state})}catch(i){console.error(`Failed to apply ${t} formatting:`,i),this.announceToScreenReader(`Failed to apply ${t} formatting`)}}insertTable(t=3,e=3){if(this.contentElement)try{this.contentElement.focus();const i=document.createElement("table");i.setAttribute("data-notectl-table","true");const o=document.createElement("tbody");for(let m=0;m<t;m++){const C=document.createElement("tr");for(let D=0;D<e;D++){const dt=document.createElement("td");dt.textContent="",C.appendChild(dt)}o.appendChild(C)}i.appendChild(o);const a=window.getSelection();let u=this.contentElement.childNodes.length;if(a&&a.rangeCount>0){const m=a.getRangeAt(0);if(this.contentElement.contains(m.commonAncestorContainer)){let C=m.startContainer;if(C.nodeType===Node.TEXT_NODE&&(C=C.parentNode),C===this.contentElement)u=m.startOffset;else{let D=C;for(;D.parentNode&&D.parentNode!==this.contentElement;)D=D.parentNode;D.parentNode===this.contentElement&&(u=Array.from(this.contentElement.childNodes).indexOf(D)+1)}}}const f=document.createElement("p");if(f.innerHTML="<br>",u>=this.contentElement.childNodes.length)this.contentElement.appendChild(i),this.contentElement.appendChild(f);else{const m=this.contentElement.childNodes[u];this.contentElement.insertBefore(i,m),this.contentElement.insertBefore(f,m)}if(a){const m=document.createRange();m.setStart(f,0),m.setEnd(f,0),a.removeAllRanges(),a.addRange(m)}this.updatePlaceholder(),this.syncContentToState(),this.announceToScreenReader(`Table with ${t} rows and ${e} columns inserted`),this.emit("change",{state:this.state})}catch(i){console.error("Failed to insert table:",i),this.announceToScreenReader("Failed to insert table")}}announceToScreenReader(t){this.ariaLiveRegion?(this.ariaLiveRegion.textContent="",setTimeout(()=>{this.ariaLiveRegion&&(this.ariaLiveRegion.textContent=t)},100)):ae(t)}attachEventListeners(){this.contentElement&&(this.contentElement.addEventListener("input",this.handleInput.bind(this)),this.contentElement.addEventListener("keydown",this.handleKeydown.bind(this)),this.contentElement.addEventListener("focus",this.handleFocus.bind(this)),this.contentElement.addEventListener("blur",this.handleBlur.bind(this)))}detachEventListeners(){this.contentElement&&(this.contentElement.removeEventListener("input",this.handleInput.bind(this)),this.contentElement.removeEventListener("keydown",this.handleKeydown.bind(this)),this.contentElement.removeEventListener("focus",this.handleFocus.bind(this)),this.contentElement.removeEventListener("blur",this.handleBlur.bind(this)))}handleInput(t){this.updatePlaceholder(),this.syncContentToState(),this.emit("change",{state:this.state})}handleKeydown(t){(t.ctrlKey||t.metaKey)&&t.key==="z"&&(t.preventDefault(),t.shiftKey?(this.redo(),this.announceToScreenReader("Action redone")):(this.undo(),this.announceToScreenReader("Action undone"))),["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"].includes(t.key)&&(t.ctrlKey||t.metaKey)&&this.announceToScreenReader(`Navigating ${t.key.replace("Arrow","").toLowerCase()}`)}handleFocus(){this.emit("focus",{state:this.state})}handleBlur(){this.emit("blur",{state:this.state})}updatePlaceholder(){if(!this.shadowRoot)return;const t=this.shadowRoot.querySelector(".notectl-placeholder"),e=!this.contentElement?.textContent?.trim();t&&t.classList.toggle("hidden",!e)}syncContentToState(){if(this.contentElement)try{const t=this.htmlToDocument(this.contentElement.innerHTML);this.state=$.fromJSON(t,this.state.schema)}catch(t){console.error("Failed to sync content to state:",t)}}htmlToDocument(t){const o=new DOMParser().parseFromString(t,"text/html").body,a=[];return Array.from(o.childNodes).forEach(u=>{const f=this.nodeToBlock(u);f&&a.push(f)}),a.length===0&&a.push({id:crypto.randomUUID(),type:"paragraph",children:[]}),{version:this.state.getDocument().version+1,schemaVersion:"1.0.0",children:a}}nodeToBlock(t){if(t.nodeType===Node.TEXT_NODE){const e=t.textContent||"";return e.trim()?{type:"text",text:e,marks:[]}:null}if(t.nodeType===Node.ELEMENT_NODE){const e=t,i=e.tagName.toLowerCase();if(i==="p")return{id:crypto.randomUUID(),type:"paragraph",children:this.parseChildren(e)};if(["h1","h2","h3","h4","h5","h6"].includes(i)){const o=parseInt(i.charAt(1),10);return{id:crypto.randomUUID(),type:"heading",attrs:{level:o},children:this.parseChildren(e)}}return this.parseInlineElement(e)}return null}parseChildren(t){const e=[];return Array.from(t.childNodes).forEach(i=>{if(i.nodeType===Node.TEXT_NODE){const o=i.textContent||"";o&&e.push({type:"text",text:o,marks:[]})}else if(i.nodeType===Node.ELEMENT_NODE){const o=i,a=this.parseInlineElement(o);a&&(Array.isArray(a)?e.push(...a):e.push(a))}}),e}parseInlineElement(t){const e=t.tagName.toLowerCase(),i=[];e==="strong"||e==="b"?i.push({type:"bold"}):e==="em"||e==="i"?i.push({type:"italic"}):e==="u"?i.push({type:"underline"}):e==="s"||e==="strike"?i.push({type:"strikethrough"}):e==="code"&&i.push({type:"code"});const o=[];return Array.from(t.childNodes).forEach(a=>{if(a.nodeType===Node.TEXT_NODE){const u=a.textContent||"";u&&o.push({type:"text",text:u,marks:i})}else if(a.nodeType===Node.ELEMENT_NODE){const u=a,f=this.parseInlineElement(u);f&&(f.type==="text"?(f.marks=[...i,...f.marks||[]],o.push(f)):Array.isArray(f)&&f.forEach(m=>{m.type==="text"&&(m.marks=[...i,...m.marks||[]]),o.push(m)}))}}),o.length===1?o[0]:o}updateReadonly(){this.contentElement&&(this.contentElement.contentEditable=String(!this.config.readonly),this.contentElement.setAttribute("data-readonly",String(this.config.readonly)))}async registerPlugin(t){const e=this.createPluginContext();await this.pluginManager.register(t,e)}async unregisterPlugin(t){const e=this.createPluginContext();await this.pluginManager.unregister(t,e)}createPluginContext(){return{getState:()=>this.state,applyDelta:t=>this.applyDelta(t),on:(t,e)=>this.on(t,e),off:(t,e)=>this.off(t,e),emit:(t,e)=>this.emit(t,e),registerCommand:(t,e)=>this.registerCommand(t,e),executeCommand:(t,...e)=>this.executeCommand(t,...e),getContainer:()=>this.contentElement,getPluginContainer:t=>t==="top"?this.pluginContainerTop:this.pluginContainerBottom}}applyDelta(t){if(!ln(t)){console.error("Invalid or unsafe delta rejected"),this.announceToScreenReader("Action blocked due to security validation");return}this.state.applyDelta(t),this.renderContent(),this.pluginManager.notifyDeltaApplied(t),this.emit("change",{delta:t,state:this.state})}on(t,e){this.eventListeners.has(t)||this.eventListeners.set(t,new Set),this.eventListeners.get(t).add(e)}off(t,e){this.eventListeners.get(t)?.delete(e)}emit(t,e){this.eventListeners.get(t)?.forEach(i=>{try{i(e)}catch(o){console.error(`Error in event listener for ${t}:`,o)}})}registerCommand(t,e){this.commands.set(t,e)}executeCommand(t,...e){const i=this.commands.get(t);if(!i)throw new Error(`Command not found: ${t}`);return i(...e)}undo(){const t=this.state.undo();t?(this.renderContent(),this.announceToScreenReader("Undo performed"),this.emit("change",{delta:t,state:this.state})):this.announceToScreenReader("Nothing to undo")}redo(){const t=this.state.redo();t?(this.renderContent(),this.announceToScreenReader("Redo performed"),this.emit("change",{delta:t,state:this.state})):this.announceToScreenReader("Nothing to redo")}configure(t){if(this.config={...this.config,...t},t.readonly!==void 0&&this.updateReadonly(),t.placeholder!==void 0&&this.shadowRoot){const e=this.shadowRoot.querySelector(".notectl-placeholder");e&&(e.textContent=t.placeholder)}t.initialContent&&typeof t.initialContent=="object"&&this.setJSON(t.initialContent),t.content&&(typeof t.content=="string"?this.setContent(t.content):this.setJSON(t.content))}destroy(){this.detachEventListeners(),this.pluginManager.destroyAll(),this.keyboardShortcutCleanup&&this.keyboardShortcutCleanup(),this.ariaLiveRegion&&this.ariaLiveRegion.parentNode&&this.ariaLiveRegion.parentNode.removeChild(this.ariaLiveRegion),this.eventListeners.clear(),this.commands.clear()}getContent(){return this.getJSON()}getState(){return this.state}getJSON(){return this.state.toJSON()}setJSON(t){this.state=$.fromJSON(t,this.state.schema),this.renderContent()}getHTML(){const t=this.documentToHTML(this.state.getDocument());return this.config.sanitizeHTML?et(t):t}setHTML(t){const e=this.config.sanitizeHTML?et(t):t;this.contentElement&&(this.contentElement.innerHTML=e,this.announceToScreenReader("Content updated"))}setContent(t,e=!0){const i=this.config.sanitizeHTML?sn(t,e):t;this.contentElement&&(this.contentElement.innerHTML=i,this.announceToScreenReader("Content updated"))}exportHTML(){return this.getHTML()}focus(){this.contentElement?.focus()}blur(){this.contentElement?.blur()}}customElements.get("notectl-editor")||customElements.define("notectl-editor",Ot);class un{async init(t){this.context=t}async destroy(){this.context=void 0}getContext(){if(!this.context)throw new Error("Plugin not initialized");return this.context}}class le{constructor(t,e){this.operations=[],this.delta={txnId:this.generateTxnId(),clientId:t,timestamp:new Date().toISOString(),baseVersion:e,ltime:Date.now(),ops:[]}}setIntent(t){return this.delta.intent=t,this}setUndoGroup(t){return this.delta.undoGroup=t,this}addOperation(t){return this.operations.push(t),this}addOperations(t){return this.operations.push(...t),this}setInverseOps(t){return this.delta.inverseOps=t,this}setValidation(t){return this.delta.validation=t,this}build(){if(this.operations.length===0)throw new Error("Delta must contain at least one operation");return{...this.delta,ops:this.operations}}generateTxnId(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{const e=Math.random()*16|0;return(t==="x"?e:e&3|8).toString(16)})}}function hn(r,t){return new le(r,t)}function fn(r){return r.inverseOps||[]}function pn(r){const t=[];return r.txnId||t.push("Delta must have a transaction ID"),r.clientId||t.push("Delta must have a client ID"),r.ops.length===0&&t.push("Delta must contain at least one operation"),r.baseVersion<0&&t.push("Base version must be non-negative"),{valid:t.length===0,errors:t}}function mn(r){return r.op==="insert_text"||r.op==="delete_range"||r.op==="apply_mark"}function gn(r){return r.op==="insert_block_before"||r.op==="insert_block_after"||r.op==="delete_block"||r.op==="set_attrs"}function yn(r){return r.op.startsWith("table_")}function En(r){return r.op==="update_selection"}function ce(r,t,e){return r.op==="insert_text"&&t.op==="insert_text"?Tn(r,t,e):r.op==="insert_text"&&t.op==="delete_range"?bn(r,t):r.op==="delete_range"&&t.op==="insert_text"?_n(r,t):r.op==="delete_range"&&t.op==="delete_range"?xn(r,t):r}function Tn(r,t,e){if(r.target.blockId===t.target.blockId){if(t.target.offset<=r.target.offset)return{...r,target:{...r.target,offset:r.target.offset+t.text.length}};if(t.target.offset===r.target.offset&&e==="right")return{...r,target:{...r.target,offset:r.target.offset+t.text.length}}}return r}function bn(r,t){if(r.target.blockId===t.range.start.blockId&&r.target.offset>=t.range.start.offset){const e=t.range.end.offset-t.range.start.offset;return{...r,target:{...r.target,offset:Math.max(t.range.start.offset,r.target.offset-e)}}}return r}function _n(r,t){return r.range.start.blockId===t.target.blockId&&t.target.offset<=r.range.start.offset?{...r,range:{start:{...r.range.start,offset:r.range.start.offset+t.text.length},end:{...r.range.end,offset:r.range.end.offset+t.text.length}}}:r}function xn(r,t,e){if(r.range.start.blockId===t.range.start.blockId){const i=r.range.start.offset,o=r.range.end.offset,a=t.range.start.offset,u=t.range.end.offset;if(u<=i){const f=u-a;return{...r,range:{start:{...r.range.start,offset:i-f},end:{...r.range.end,offset:o-f}}}}if(a<=i&&u>=o)return{...r,range:{start:{...r.range.start,offset:a},end:{...r.range.end,offset:a}}}}return r}function Sn(r,t,e="left"){const i=r.ops.map(o=>{let a=o;for(const u of t.ops)a=ce(a,u,e);return a});return{...r,ops:i,baseVersion:t.baseVersion+1}}function An(r,t){return{...t,ops:[...r.ops,...t.ops],baseVersion:r.baseVersion}}function kn(r,t){return t.baseVersion===r.baseVersion||t.clientId===r.clientId}function Ln(r,t){const e=new Ot;return r.appendChild(e),e}const Rn="0.0.1";h.BasePlugin=un,h.DeltaBuilder=le,h.EditorState=$,h.NodeFactory=Kt,h.NotectlEditor=Ot,h.PluginManager=Yt,h.Schema=B,h.VERSION=Rn,h.canCompose=kn,h.composeDelta=An,h.computeInverse=fn,h.createDefaultSchema=bt,h.createDelta=hn,h.createEditor=Ln,h.createNodeFactory=Vt,h.generateBlockId=w,h.isBlockOperation=gn,h.isSelectionOperation=En,h.isTableOperation=yn,h.isTextOperation=mn,h.transformDelta=Sn,h.transformOperation=ce,h.validateDelta=pn,Object.defineProperty(h,Symbol.toStringTag,{value:"Module"})}));
|
|
112
|
+
`,this.contentElement=this.shadowRoot.querySelector(".notectl-editor"),this.pluginContainerTop=this.shadowRoot.querySelector('.notectl-plugin-container[data-position="top"]'),this.pluginContainerBottom=this.shadowRoot.querySelector('.notectl-plugin-container[data-position="bottom"]'),this.ariaLiveRegion=this.shadowRoot.querySelector("#notectl-aria-live"),this.renderContent())}renderContent(){if(!this.contentElement)return;const t=this.state.getDocument(),e=this.documentToHTML(t);this.contentElement.innerHTML=this.config.sanitizeHTML?it(e):e}documentToHTML(t){return t.children.map(e=>this.blockToHTML(e)).join("")}blockToHTML(t){switch(t.type){case"paragraph":return`<p>${this.childrenToHTML(t.children||[])}</p>`;case"heading":const e=t.attrs?.level||1;return`<h${e}>${this.childrenToHTML(t.children||[])}</h${e}>`;case"table":return this.tableToHTML(t);default:return`<div>${this.childrenToHTML(t.children||[])}</div>`}}childrenToHTML(t){return t.map(e=>{if(e.type==="text"){let n=this.escapeHTML(e.text);if(e.marks)for(const o of e.marks)n=this.applyMarkHTML(n,o);return n}return this.blockToHTML(e)}).join("")}applyMarkHTML(t,e){switch(e.type){case"bold":return`<strong>${t}</strong>`;case"italic":return`<em>${t}</em>`;case"underline":return`<u>${t}</u>`;case"strikethrough":return`<s>${t}</s>`;case"code":return`<code>${t}</code>`;default:return t}}escapeHTML(t){if(!this.config.sanitizeHTML)return t;const e=document.createElement("div");return e.textContent=t,e.innerHTML}tableToHTML(t){const e=t.attrs?.table,o=['data-node-type="table"',`data-block-id="${t.id||crypto.randomUUID()}"`];if(t.attrs?.style){const h=this.styleObjectToString(t.attrs.style);h&&o.push(`style="${h}"`)}let s="";const l=Array.isArray(e?.rows)?e.rows:[];if(l.length===0){const h=crypto.randomUUID();s=`
|
|
113
|
+
<tr data-node-type="table_row" data-row="0" data-block-id="${crypto.randomUUID()}">
|
|
114
|
+
<td data-node-type="table_cell" data-row="0" data-col="0" data-block-id="${h}"><br></td>
|
|
115
|
+
</tr>
|
|
116
|
+
`}else s=l.map((h,p)=>this.tableRowToHTML(h,p)).join("");return`<table ${o.join(" ")}><tbody>${s}</tbody></table>`}tableRowToHTML(t,e){const n=t.id||crypto.randomUUID(),o=['data-node-type="table_row"',`data-row="${e}"`,`data-block-id="${n}"`];if(t.attrs?.style){const h=this.styleObjectToString(t.attrs.style);h&&o.push(`style="${h}"`)}const l=(Array.isArray(t.cells)?t.cells:[]).map((h,p)=>this.tableCellToHTML(h,e,p)).join("");return`<tr ${o.join(" ")}>${l}</tr>`}tableCellToHTML(t,e,n){const o=t.id||crypto.randomUUID(),s=['data-node-type="table_cell"',`data-row="${e}"`,`data-col="${n}"`,`data-block-id="${o}"`],l=Number(t.rowSpan)||1,h=Number(t.colSpan)||1;if(l>1&&s.push(`rowspan="${l}"`),h>1&&s.push(`colspan="${h}"`),t.attrs?.style){const x=this.styleObjectToString(t.attrs.style);x&&s.push(`style="${x}"`)}const y=(typeof t.content=="string"?this.escapeHTML(t.content):"")||"<br>";return`<td ${s.join(" ")}>${y}</td>`}styleObjectToString(t){return Object.entries(t).map(([e,n])=>n==null||n===""?null:`${e.replace(/[A-Z]/g,s=>`-${s.toLowerCase()}`)}: ${String(n)}`).filter(Boolean).join("; ")}setupAccessibility(){this.contentElement&&(En(this.contentElement,{role:"textbox","aria-multiline":!0,"aria-label":"Rich text editor","aria-describedby":"notectl-help-text","aria-autocomplete":"none"}),this.config.readonly&&this.contentElement.setAttribute("aria-readonly","true"))}setupKeyboardShortcuts(){if(!this.contentElement)return;const t=[{key:"b",ctrlKey:!0,description:"Bold formatting applied",action:()=>this.toggleFormat("bold")},{key:"i",ctrlKey:!0,description:"Italic formatting applied",action:()=>this.toggleFormat("italic")},{key:"u",ctrlKey:!0,description:"Underline formatting applied",action:()=>this.toggleFormat("underline")},{key:"z",ctrlKey:!0,description:"Action undone",action:()=>this.undo()},{key:"z",ctrlKey:!0,shiftKey:!0,description:"Action redone",action:()=>this.redo()}];this.keyboardShortcutCleanup=gn(t,this.contentElement)}toggleFormat(t){const e=window.getSelection();if(!(!e||!this.contentElement))try{switch(t){case"bold":document.execCommand("bold",!1);break;case"italic":document.execCommand("italic",!1);break;case"underline":document.execCommand("underline",!1);break;case"strikethrough":document.execCommand("strikeThrough",!1);break;case"code":const n=document.createElement("code");if(e.rangeCount>0){const o=e.getRangeAt(0);n.appendChild(o.extractContents()),o.insertNode(n)}break}this.announceToScreenReader(`${t} formatting applied`),this.emit("change",{state:this.state})}catch(n){console.error(`Failed to apply ${t} formatting:`,n),this.announceToScreenReader(`Failed to apply ${t} formatting`)}}insertTable(t=3,e=3){if(this.contentElement)try{this.contentElement.focus();const n=document.createElement("table");n.setAttribute("data-notectl-table","true");const o=document.createElement("tbody");for(let p=0;p<t;p++){const y=document.createElement("tr");for(let x=0;x<e;x++){const ut=document.createElement("td");ut.textContent="",y.appendChild(ut)}o.appendChild(y)}n.appendChild(o);const s=window.getSelection();let l=this.contentElement.childNodes.length;if(s&&s.rangeCount>0){const p=s.getRangeAt(0);if(this.contentElement.contains(p.commonAncestorContainer)){let y=p.startContainer;if(y.nodeType===Node.TEXT_NODE&&(y=y.parentNode),y===this.contentElement)l=p.startOffset;else{let x=y;for(;x.parentNode&&x.parentNode!==this.contentElement;)x=x.parentNode;x.parentNode===this.contentElement&&(l=Array.from(this.contentElement.childNodes).indexOf(x)+1)}}}const h=document.createElement("p");if(h.innerHTML="<br>",l>=this.contentElement.childNodes.length)this.contentElement.appendChild(n),this.contentElement.appendChild(h);else{const p=this.contentElement.childNodes[l];this.contentElement.insertBefore(n,p),this.contentElement.insertBefore(h,p)}if(s){const p=document.createRange();p.setStart(h,0),p.setEnd(h,0),s.removeAllRanges(),s.addRange(p)}this.updatePlaceholder(),this.syncContentToState(),this.announceToScreenReader(`Table with ${t} rows and ${e} columns inserted`),this.emit("change",{state:this.state})}catch(n){console.error("Failed to insert table:",n),this.announceToScreenReader("Failed to insert table")}}announceToScreenReader(t){this.ariaLiveRegion?(this.ariaLiveRegion.textContent="",setTimeout(()=>{this.ariaLiveRegion&&(this.ariaLiveRegion.textContent=t)},100)):ce(t)}attachEventListeners(){this.contentElement&&(this.contentElement.addEventListener("input",this.handleInput),this.contentElement.addEventListener("keydown",this.handleKeydown),this.contentElement.addEventListener("focus",this.handleFocus),this.contentElement.addEventListener("blur",this.handleBlur),this.contentElement.addEventListener("contextmenu",this.handleContextMenu))}detachEventListeners(){this.contentElement&&(this.contentElement.removeEventListener("input",this.handleInput),this.contentElement.removeEventListener("keydown",this.handleKeydown),this.contentElement.removeEventListener("focus",this.handleFocus),this.contentElement.removeEventListener("blur",this.handleBlur),this.contentElement.removeEventListener("contextmenu",this.handleContextMenu))}updatePlaceholder(){if(!this.shadowRoot)return;const t=this.shadowRoot.querySelector(".notectl-placeholder"),e=!this.contentElement?.textContent?.trim();t&&t.classList.toggle("hidden",!e)}syncContentToState(){if(this.contentElement)try{const t=this.htmlToDocument(this.contentElement.innerHTML);this.state=V.fromJSON(t,this.state.schema)}catch(t){console.error("Failed to sync content to state:",t)}}htmlToDocument(t){const o=new DOMParser().parseFromString(t,"text/html").body,s=[];return Array.from(o.childNodes).forEach(l=>{const h=this.nodeToBlock(l);h&&s.push(h)}),s.length===0&&s.push({id:crypto.randomUUID(),type:"paragraph",children:[]}),{version:this.state.getDocument().version+1,schemaVersion:"1.0.0",children:s}}nodeToBlock(t){if(t.nodeType===Node.TEXT_NODE){const e=t.textContent||"";return e.trim()?{type:"text",text:e,marks:[]}:null}if(t.nodeType===Node.ELEMENT_NODE){const e=t,n=e.tagName.toLowerCase();if(n==="p")return{id:crypto.randomUUID(),type:"paragraph",children:this.parseChildren(e)};if(["h1","h2","h3","h4","h5","h6"].includes(n)){const o=parseInt(n.charAt(1),10);return{id:crypto.randomUUID(),type:"heading",attrs:{level:o},children:this.parseChildren(e)}}return this.parseInlineElement(e)}return null}parseChildren(t){const e=[];return Array.from(t.childNodes).forEach(n=>{if(n.nodeType===Node.TEXT_NODE){const o=n.textContent||"";o&&e.push({type:"text",text:o,marks:[]})}else if(n.nodeType===Node.ELEMENT_NODE){const o=n,s=this.parseInlineElement(o);s&&(Array.isArray(s)?e.push(...s):e.push(s))}}),e}parseInlineElement(t){const e=t.tagName.toLowerCase(),n=[];e==="strong"||e==="b"?n.push({type:"bold"}):e==="em"||e==="i"?n.push({type:"italic"}):e==="u"?n.push({type:"underline"}):e==="s"||e==="strike"?n.push({type:"strikethrough"}):e==="code"&&n.push({type:"code"});const o=[];return Array.from(t.childNodes).forEach(s=>{if(s.nodeType===Node.TEXT_NODE){const l=s.textContent||"";l&&o.push({type:"text",text:l,marks:n})}else if(s.nodeType===Node.ELEMENT_NODE){const l=s,h=this.parseInlineElement(l);h&&(h.type==="text"?(h.marks=[...n,...h.marks||[]],o.push(h)):Array.isArray(h)&&h.forEach(p=>{p.type==="text"&&(p.marks=[...n,...p.marks||[]]),o.push(p)}))}}),o.length===1?o[0]:o}updateReadonly(){this.contentElement&&(this.contentElement.contentEditable=String(!this.config.readonly),this.contentElement.setAttribute("data-readonly",String(this.config.readonly)))}async registerPlugin(t){if(!this.isReady){this.pendingPlugins.push(t);return}const e=this.createPluginContext();await this.pluginManager.register(t,e)}async unregisterPlugin(t){const e=this.createPluginContext();await this.pluginManager.unregister(t,e)}async whenReady(){return this.readyPromise}getSelectedBlock(){const t=this.state.getSelection();return t&&this.state.findBlock(t.anchor.blockId)||null}findBlocksByType(t){const e=[],n=this.state.getDocument(),o=s=>{for(const l of s)if(l.type===t&&e.push(l),l.children){const h=l.children.filter(p=>"id"in p);o(h)}};return o(n.children),e}findParentBlock(t){const e=this.state.getDocument(),n=(o,s=null)=>{for(const l of o){if(l.id===t.id)return s;if(l.children){const h=l.children.filter(y=>"id"in y),p=n(h,l);if(p)return p}}return null};return n(e.children)}getBlockAtCursor(){return this.getSelectedBlock()}insertBlockAfter(t,e){const n=this.state.getDocument(),o=e||n.children[n.children.length-1]?.id;if(!o){const l={txnId:crypto.randomUUID(),clientId:"editor",timestamp:new Date().toISOString(),baseVersion:this.state.getVersion(),ltime:Date.now(),intent:"edit",ops:[{op:"insert_block_after",after:"",block:t}]};this.applyDelta(l);return}const s={txnId:crypto.randomUUID(),clientId:"editor",timestamp:new Date().toISOString(),baseVersion:this.state.getVersion(),ltime:Date.now(),intent:"edit",ops:[{op:"insert_block_after",after:o,block:t}]};this.applyDelta(s)}insertBlockBefore(t,e){const n=this.state.getDocument(),o=e||n.children[0]?.id;if(!o){this.insertBlockAfter(t);return}const s={txnId:crypto.randomUUID(),clientId:"editor",timestamp:new Date().toISOString(),baseVersion:this.state.getVersion(),ltime:Date.now(),intent:"edit",ops:[{op:"insert_block_before",before:o,block:t}]};this.applyDelta(s)}updateBlockAttrs(t,e){const n={txnId:crypto.randomUUID(),clientId:"editor",timestamp:new Date().toISOString(),baseVersion:this.state.getVersion(),ltime:Date.now(),intent:"edit",ops:[{op:"set_attrs",target:{blockId:t},attrs:e}]};this.applyDelta(n)}deleteBlockById(t){const e={txnId:crypto.randomUUID(),clientId:"editor",timestamp:new Date().toISOString(),baseVersion:this.state.getVersion(),ltime:Date.now(),intent:"edit",ops:[{op:"delete_block",target:{blockId:t}}]};this.applyDelta(e)}addMarkToSelection(t){const e=this.state.getSelection();if(!e)return;const n={txnId:crypto.randomUUID(),clientId:"editor",timestamp:new Date().toISOString(),baseVersion:this.state.getVersion(),ltime:Date.now(),intent:"format",ops:[{op:"apply_mark",range:{start:e.anchor,end:e.head},mark:t,add:!0}]};this.applyDelta(n)}removeMarkFromSelection(t){const e=this.state.getSelection();if(!e)return;const n={txnId:crypto.randomUUID(),clientId:"editor",timestamp:new Date().toISOString(),baseVersion:this.state.getVersion(),ltime:Date.now(),intent:"format",ops:[{op:"apply_mark",range:{start:e.anchor,end:e.head},mark:{type:t},add:!1}]};this.applyDelta(n)}toggleMarkOnSelection(t){const e=this.state.getSelection();if(!e)return;const n=this.state.findBlock(e.anchor.blockId);if(!n||!n.children)return;const s=n.children.find(h=>"text"in h)?.marks?.some(h=>h.type===t)||!1,l={txnId:crypto.randomUUID(),clientId:"editor",timestamp:new Date().toISOString(),baseVersion:this.state.getVersion(),ltime:Date.now(),intent:"format",ops:[{op:"apply_mark",range:{start:e.anchor,end:e.head},mark:{type:t},add:!s}]};this.applyDelta(l)}createPluginContext(){return{getState:()=>this.state,applyDelta:t=>this.applyDelta(t),getSelection:()=>this.state.getSelection(),setSelection:t=>{this.state.setSelection(t),this.emit("selection-change",{selection:t})},getSelectedBlock:()=>this.getSelectedBlock(),findBlocksByType:t=>this.findBlocksByType(t),findBlockById:t=>this.state.findBlock(t),findParentBlock:t=>this.findParentBlock(t),getBlockAtCursor:()=>this.getBlockAtCursor(),insertBlockAfter:(t,e)=>this.insertBlockAfter(t,e),insertBlockBefore:(t,e)=>this.insertBlockBefore(t,e),updateBlockAttrs:(t,e)=>this.updateBlockAttrs(t,e),deleteBlock:t=>this.deleteBlockById(t),addMark:t=>this.addMarkToSelection(t),removeMark:t=>this.removeMarkFromSelection(t),toggleMark:t=>this.toggleMarkOnSelection(t),on:(t,e)=>this.on(t,e),off:(t,e)=>this.off(t,e),emit:(t,e)=>this.emit(t,e),registerCommand:(t,e)=>this.registerCommand(t,e),executeCommand:(t,...e)=>this.executeCommand(t,...e),getContainer:()=>this.contentElement,getPluginContainer:t=>t==="top"?this.pluginContainerTop:this.pluginContainerBottom}}applyDelta(t){if(!mn(t)){console.error("Invalid or unsafe delta rejected"),this.announceToScreenReader("Action blocked due to security validation");return}this.state.applyDelta(t),this.renderContent(),this.pluginManager.notifyDeltaApplied(t),this.emit("change",{delta:t,state:this.state})}on(t,e){this.eventListeners.has(t)||this.eventListeners.set(t,new Set),this.eventListeners.get(t).add(e)}off(t,e){this.eventListeners.get(t)?.delete(e)}emit(t,e){this.eventListeners.get(t)?.forEach(n=>{try{n(e)}catch(o){console.error(`Error in event listener for ${t}:`,o)}})}registerCommand(t,e){this.commands.set(t,e)}executeCommand(t,...e){const n=this.commands.get(t);if(!n)throw new Error(`Command not found: ${t}`);return n(...e)}undo(){const t=this.state.undo();t?(this.renderContent(),this.announceToScreenReader("Undo performed"),this.emit("change",{delta:t,state:this.state})):this.announceToScreenReader("Nothing to undo")}redo(){const t=this.state.redo();t?(this.renderContent(),this.announceToScreenReader("Redo performed"),this.emit("change",{delta:t,state:this.state})):this.announceToScreenReader("Nothing to redo")}configure(t){if(this.config={...this.config,...t},t.readonly!==void 0&&this.updateReadonly(),t.placeholder!==void 0&&this.shadowRoot){const e=this.shadowRoot.querySelector(".notectl-placeholder");e&&(e.textContent=t.placeholder)}t.initialContent&&typeof t.initialContent=="object"&&this.setJSON(t.initialContent),t.content&&(typeof t.content=="string"?this.setContent(t.content):this.setJSON(t.content))}destroy(){this.detachEventListeners(),this.pluginManager.destroyAll(),this.keyboardShortcutCleanup&&this.keyboardShortcutCleanup(),this.ariaLiveRegion&&this.ariaLiveRegion.parentNode&&this.ariaLiveRegion.parentNode.removeChild(this.ariaLiveRegion),this.eventListeners.clear(),this.commands.clear()}getContent(){return this.getJSON()}getState(){return this.state}getJSON(){return this.state.toJSON()}setJSON(t){this.state=V.fromJSON(t,this.state.schema),this.renderContent()}getHTML(){const t=this.documentToHTML(this.state.getDocument());return this.config.sanitizeHTML?it(t):t}setHTML(t){const e=this.config.sanitizeHTML?it(t):t;this.contentElement&&(this.contentElement.innerHTML=e,this.announceToScreenReader("Content updated"))}setContent(t,e=!0){const n=this.config.sanitizeHTML?fn(t,e):t;this.contentElement&&(this.contentElement.innerHTML=n,this.announceToScreenReader("Content updated"))}exportHTML(){return this.getHTML()}focus(){this.contentElement?.focus()}blur(){this.contentElement?.blur()}}customElements.get("notectl-editor")||customElements.define("notectl-editor",Rt);class yn{async init(t){this.context=t}async destroy(){this.context=void 0}getContext(){if(!this.context)throw new Error("Plugin not initialized");return this.context}}class de{constructor(t,e){this.operations=[],this.delta={txnId:this.generateTxnId(),clientId:t,timestamp:new Date().toISOString(),baseVersion:e,ltime:Date.now(),ops:[]}}setIntent(t){return this.delta.intent=t,this}setUndoGroup(t){return this.delta.undoGroup=t,this}addOperation(t){return this.operations.push(t),this}addOperations(t){return this.operations.push(...t),this}setInverseOps(t){return this.delta.inverseOps=t,this}setValidation(t){return this.delta.validation=t,this}build(){if(this.operations.length===0)throw new Error("Delta must contain at least one operation");return{...this.delta,ops:this.operations}}generateTxnId(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{const e=Math.random()*16|0;return(t==="x"?e:e&3|8).toString(16)})}}function Tn(r,t){return new de(r,t)}function _n(r){return r.inverseOps||[]}function In(r){const t=[];return r.txnId||t.push("Delta must have a transaction ID"),r.clientId||t.push("Delta must have a client ID"),r.ops.length===0&&t.push("Delta must contain at least one operation"),r.baseVersion<0&&t.push("Base version must be non-negative"),{valid:t.length===0,errors:t}}function bn(r){return r.op==="insert_text"||r.op==="delete_range"||r.op==="apply_mark"}function Nn(r){return r.op==="insert_block_before"||r.op==="insert_block_after"||r.op==="delete_block"||r.op==="set_attrs"}function An(r){return r.op.startsWith("table_")}function Dn(r){return r.op==="update_selection"}function he(r,t,e){return r.op==="insert_text"&&t.op==="insert_text"?Sn(r,t,e):r.op==="insert_text"&&t.op==="delete_range"?Ln(r,t):r.op==="delete_range"&&t.op==="insert_text"?On(r,t):r.op==="delete_range"&&t.op==="delete_range"?kn(r,t):r}function Sn(r,t,e){if(r.target.blockId===t.target.blockId){if(t.target.offset<=r.target.offset)return{...r,target:{...r.target,offset:r.target.offset+t.text.length}};if(t.target.offset===r.target.offset&&e==="right")return{...r,target:{...r.target,offset:r.target.offset+t.text.length}}}return r}function Ln(r,t){if(r.target.blockId===t.range.start.blockId&&r.target.offset>=t.range.start.offset){const e=t.range.end.offset-t.range.start.offset;return{...r,target:{...r.target,offset:Math.max(t.range.start.offset,r.target.offset-e)}}}return r}function On(r,t){return r.range.start.blockId===t.target.blockId&&t.target.offset<=r.range.start.offset?{...r,range:{start:{...r.range.start,offset:r.range.start.offset+t.text.length},end:{...r.range.end,offset:r.range.end.offset+t.text.length}}}:r}function kn(r,t,e){if(r.range.start.blockId===t.range.start.blockId){const n=r.range.start.offset,o=r.range.end.offset,s=t.range.start.offset,l=t.range.end.offset;if(l<=n){const h=l-s;return{...r,range:{start:{...r.range.start,offset:n-h},end:{...r.range.end,offset:o-h}}}}if(s<=n&&l>=o)return{...r,range:{start:{...r.range.start,offset:s},end:{...r.range.end,offset:s}}}}return r}function xn(r,t,e="left"){const n=r.ops.map(o=>{let s=o;for(const l of t.ops)s=he(s,l,e);return s});return{...r,ops:n,baseVersion:t.baseVersion+1}}function Rn(r,t){return{...t,ops:[...r.ops,...t.ops],baseVersion:r.baseVersion}}function Cn(r,t){return t.baseVersion===r.baseVersion||t.clientId===r.clientId}const wn={isCollapsed(r){return r.anchor.blockId===r.head.blockId&&r.anchor.offset===r.head.offset},isMultiBlock(r){return r.anchor.blockId!==r.head.blockId},getDirection(r){return this.isCollapsed(r)?"none":r.anchor.blockId===r.head.blockId?r.anchor.offset<r.head.offset?"forward":"backward":"forward"},createCollapsed(r){return{anchor:r,head:r}},createRange(r,t){return{anchor:r,head:t}}},Mn={isTextNode(r){return"text"in r&&r.type==="text"},isBlockNode(r){return"id"in r&&"type"in r},getTextContent(r){return r.children?r.children.map(t=>this.isTextNode(t)?t.text:this.isBlockNode(t)?this.getTextContent(t):"").join(""):""},isEmpty(r){return!r.children||r.children.length===0?!0:this.getTextContent(r).trim()===""}};function vn(r,t){const e=new Rt;return r.appendChild(e),e}const Pn="0.0.1";u.ARIA_ANNOUNCEMENT_DELAY=Fe,u.BasePlugin=yn,u.DEFAULT_MAX_HISTORY_DEPTH=He,u.DEFAULT_MIN_HEIGHT=Ge,u.DeltaBuilder=de,u.EDITOR_READY_TIMEOUT=Ue,u.EditorState=V,u.ErrorCodes=C,u.NodeFactory=jt,u.NotectlEditor=Rt,u.NotectlError=A,u.PluginManager=Xt,u.Schema=z,u.VERSION=Pn,u.ValidationConstraints=Be,u.blockHelpers=Mn,u.canCompose=Cn,u.composeDelta=Rn,u.computeInverse=_n,u.createDefaultSchema=bt,u.createDelta=Tn,u.createEditor=vn,u.createNodeFactory=Kt,u.generateBlockId=w,u.isBlockOperation=Nn,u.isSelectionOperation=Dn,u.isTableOperation=An,u.isTextOperation=bn,u.selectionHelpers=wn,u.transformDelta=xn,u.transformOperation=he,u.validateDelta=In,Object.defineProperty(u,Symbol.toStringTag,{value:"Module"})}));
|
|
113
117
|
//# sourceMappingURL=notectl-core.umd.cjs.map
|