@notectl/core 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,113 @@
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
+ `+O),G&&at([It,Nt,Dt],H=>{O=Z(O,H," ")}),L&&mt?L.createHTML(O):O},t.setConfig=function(){let c=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};$t(c),Pt=!0},t.clearConfig=function(){j=null,Pt=!1},t.isValidAttribute=function(c,n,s){j||$t({});const l=T(c),p=T(n);return we(l,p,s)},t.addHook=function(c,n){typeof n=="function"&&q(R[c],n)},t.removeHook=function(c,n){if(n!==void 0){const s=He(R[c],n);return s===-1?void 0:Fe(R[c],s,1)[0]}return Zt(R[c])},t.removeHooks=function(c){R[c]=[]},t.removeAllHooks=function(){R=oe()},t}var nn=se();const rn={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},on={ALLOWED_TAGS:["p","br","strong","em","u","code"],ALLOWED_ATTR:[],KEEP_CONTENT:!0,SANITIZE_DOM:!0,SAFE_FOR_TEMPLATES:!0};function et(r,t=!1){const e=t?on:rn;return nn.sanitize(r,e)}function sn(r,t=!0){return t?et(r):an(r)}function an(r){const t=document.createElement("div");return t.textContent=r,t.innerHTML}function ln(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"&&et(e)!==e&&e.includes("<script"))return!1;if(typeof e=="object"&&e!==null){const i=e;if("script"in i||"onerror"in i||"onclick"in i)return!1}}if("attributes"in t&&t.attributes){const e=t.attributes;for(const i in e)if(i.startsWith("on")||i.toLowerCase().includes("script"))return!1}}return!0}catch(t){return console.error("Error validating delta:",t),!1}}function ae(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 cn(r,t){const e=i=>{for(const o of r){const a=o.ctrlKey?i.ctrlKey:!0,u=o.metaKey?i.metaKey:!0,f=o.shiftKey?i.shiftKey:!i.shiftKey,m=o.altKey?i.altKey:!i.altKey;if(i.key.toLowerCase()===o.key.toLowerCase()&&a&&u&&f&&m){i.preventDefault(),o.action(),ae(o.description);break}}};return t.addEventListener("keydown",e),()=>{t.removeEventListener("keydown",e)}}function dn(r,t){for(const[e,i]of Object.entries(t)){const o=e.startsWith("aria-")?e:`aria-${e}`;r.setAttribute(o,String(i))}}class Ot 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.config={placeholder:"Start typing...",readonly:!1,autofocus:!1,sanitizeHTML:!0,maxHistoryDepth:100};const t=bt();this.state=new $(void 0,t,{maxHistoryDepth:this.config.maxHistoryDepth}),this.pluginManager=new Yt,this.attachShadow({mode:"open"})}static get observedAttributes(){return["placeholder","readonly","autofocus"]}connectedCallback(){this.render(),this.attachEventListeners(),this.setupAccessibility(),this.setupKeyboardShortcuts(),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)}attributeChangedCallback(t,e,i){if(e!==i)switch(t){case"placeholder":this.config.placeholder=i||"",this.updatePlaceholder();break;case"readonly":this.config.readonly=i!==null,this.updateReadonly();break;case"autofocus":this.config.autofocus=i!==null;break}}render(){this.shadowRoot&&(this.shadowRoot.innerHTML=`
3
+ <style>
4
+ :host {
5
+ display: block;
6
+ position: relative;
7
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
8
+ font-size: 16px;
9
+ line-height: 1.5;
10
+ }
11
+
12
+ .notectl-container {
13
+ display: flex;
14
+ flex-direction: column;
15
+ border: 1px solid #e0e0e0;
16
+ border-radius: 4px;
17
+ background: white;
18
+ }
19
+
20
+ .notectl-plugin-container {
21
+ display: block;
22
+ background: transparent;
23
+ }
24
+
25
+ .notectl-plugin-container[data-position="top"] {
26
+ order: -1;
27
+ }
28
+
29
+ .notectl-plugin-container[data-position="bottom"] {
30
+ order: 1;
31
+ }
32
+
33
+ .notectl-editor-wrapper {
34
+ position: relative;
35
+ flex: 1;
36
+ }
37
+
38
+ .notectl-editor {
39
+ min-height: 200px;
40
+ padding: 1rem;
41
+ outline: none;
42
+ background: white;
43
+ }
44
+
45
+ .notectl-container:focus-within {
46
+ border-color: #2196F3;
47
+ box-shadow: 0 0 0 2px rgba(33, 150, 243, 0.1);
48
+ }
49
+
50
+ .notectl-editor[data-readonly="true"] {
51
+ background: #f5f5f5;
52
+ cursor: not-allowed;
53
+ }
54
+
55
+ .notectl-editor table {
56
+ border-collapse: collapse;
57
+ width: 100%;
58
+ margin: 1em 0;
59
+ }
60
+
61
+ .notectl-editor table td,
62
+ .notectl-editor table th {
63
+ border: 1px solid #ddd;
64
+ padding: 8px;
65
+ min-width: 100px;
66
+ }
67
+
68
+ .notectl-placeholder {
69
+ position: absolute;
70
+ top: 1rem;
71
+ left: 1rem;
72
+ color: #9e9e9e;
73
+ pointer-events: none;
74
+ user-select: none;
75
+ }
76
+
77
+ .notectl-placeholder.hidden {
78
+ display: none;
79
+ }
80
+
81
+ .visually-hidden {
82
+ position: absolute;
83
+ left: -10000px;
84
+ width: 1px;
85
+ height: 1px;
86
+ overflow: hidden;
87
+ }
88
+ </style>
89
+
90
+ <div class="notectl-container">
91
+ <div class="notectl-plugin-container" data-position="top"></div>
92
+ <div class="notectl-editor-wrapper">
93
+ <div class="notectl-placeholder" aria-hidden="true">${this.config.placeholder}</div>
94
+ <div
95
+ class="notectl-editor"
96
+ contenteditable="${!this.config.readonly}"
97
+ data-readonly="${this.config.readonly}"
98
+ role="textbox"
99
+ aria-label="Rich text editor"
100
+ aria-multiline="true"
101
+ aria-describedby="notectl-help-text"
102
+ tabindex="0"
103
+ ></div>
104
+ </div>
105
+ <div class="notectl-plugin-container" data-position="bottom"></div>
106
+ </div>
107
+ <div id="notectl-help-text" class="visually-hidden">
108
+ Use arrow keys to navigate. Press Ctrl+B for bold, Ctrl+I for italic, Ctrl+U for underline.
109
+ Press Ctrl+Z to undo, Ctrl+Shift+Z to redo.
110
+ </div>
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"})}));
113
+ //# sourceMappingURL=notectl-core.umd.cjs.map