@notectl/core 0.0.5 → 0.0.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +1816 -0
- package/dist/notectl-core.js +1046 -2792
- package/dist/notectl-core.js.map +1 -1
- package/dist/notectl-core.mjs +7886 -0
- package/dist/notectl-core.mjs.map +1 -0
- package/package.json +31 -55
- package/dist/notectl-core.umd.cjs +0 -117
- package/dist/notectl-core.umd.cjs.map +0 -1
- package/dist/types/index.d.ts +0 -1469
package/package.json
CHANGED
|
@@ -1,57 +1,33 @@
|
|
|
1
1
|
{
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
],
|
|
34
|
-
"author": "Samuel Abramov",
|
|
35
|
-
"license": "MIT",
|
|
36
|
-
"dependencies": {
|
|
37
|
-
"dompurify": "^3.2.3",
|
|
38
|
-
"uuid": "^11.0.6"
|
|
39
|
-
},
|
|
40
|
-
"devDependencies": {
|
|
41
|
-
"@types/dompurify": "^3.2.0",
|
|
42
|
-
"@types/node": "^22.10.7",
|
|
43
|
-
"@types/uuid": "^10.0.0",
|
|
44
|
-
"typescript": "^5.7.3",
|
|
45
|
-
"vite": "^6.0.7",
|
|
46
|
-
"vite-plugin-dts": "^4.4.1",
|
|
47
|
-
"vitest": "^2.1.8"
|
|
48
|
-
},
|
|
49
|
-
"publishConfig": {
|
|
50
|
-
"access": "public"
|
|
51
|
-
},
|
|
52
|
-
"repository": {
|
|
53
|
-
"type": "git",
|
|
54
|
-
"url": "git+https://github.com/Samyssmile/notectl.git",
|
|
55
|
-
"directory": "packages/core"
|
|
56
|
-
}
|
|
2
|
+
"name": "@notectl/core",
|
|
3
|
+
"version": "0.0.6",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"main": "./dist/notectl-core.js",
|
|
6
|
+
"module": "./dist/notectl-core.mjs",
|
|
7
|
+
"types": "./dist/index.d.ts",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"types": "./dist/index.d.ts",
|
|
11
|
+
"import": "./dist/notectl-core.mjs",
|
|
12
|
+
"require": "./dist/notectl-core.js"
|
|
13
|
+
}
|
|
14
|
+
},
|
|
15
|
+
"files": ["dist"],
|
|
16
|
+
"scripts": {
|
|
17
|
+
"build": "vite build",
|
|
18
|
+
"test": "vitest run",
|
|
19
|
+
"test:watch": "vitest",
|
|
20
|
+
"typecheck": "tsc --noEmit",
|
|
21
|
+
"dev": "vite build --watch"
|
|
22
|
+
},
|
|
23
|
+
"dependencies": {
|
|
24
|
+
"dompurify": "^3.2.0"
|
|
25
|
+
},
|
|
26
|
+
"devDependencies": {
|
|
27
|
+
"@types/dompurify": "^3.2.0",
|
|
28
|
+
"happy-dom": "^16.0.0",
|
|
29
|
+
"vite": "^6.0.0",
|
|
30
|
+
"vite-plugin-dts": "^4.3.0",
|
|
31
|
+
"vitest": "^2.1.0"
|
|
32
|
+
}
|
|
57
33
|
}
|
|
@@ -1,117 +0,0 @@
|
|
|
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
|
-
<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?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"})}));
|
|
117
|
-
//# sourceMappingURL=notectl-core.umd.cjs.map
|