@notectl/core 2.3.5 → 2.3.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/chunks/{ToolbarPlugin-DdrLarMD.mjs → ToolbarPlugin-O7TirXQP.mjs} +2 -2
- package/dist/chunks/{ToolbarPlugin-DdrLarMD.mjs.map → ToolbarPlugin-O7TirXQP.mjs.map} +1 -1
- package/dist/chunks/register-BVvV0Vl_.mjs +3 -0
- package/dist/chunks/register-BVvV0Vl_.mjs.map +1 -0
- package/dist/full.mjs +1 -1
- package/dist/input/KeyboardHandler.d.ts.map +1 -1
- package/dist/model/Keymap.d.ts +5 -2
- package/dist/model/Keymap.d.ts.map +1 -1
- package/dist/model/KeymapRegistry.d.ts +4 -1
- package/dist/model/KeymapRegistry.d.ts.map +1 -1
- package/dist/notectl-core.mjs +1 -1
- package/dist/notectl-core.umd.js +1 -1
- package/dist/notectl-core.umd.js.map +1 -1
- package/dist/plugins/toolbar/ToolbarPlugin.d.ts +16 -0
- package/dist/plugins/toolbar/ToolbarPlugin.d.ts.map +1 -1
- package/dist/plugins/toolbar.mjs +1 -1
- package/dist/register.mjs +1 -1
- package/package.json +1 -1
- package/dist/chunks/register-ArnJV5vu.mjs +0 -3
- package/dist/chunks/register-ArnJV5vu.mjs.map +0 -1
|
@@ -26,6 +26,12 @@ export interface ToolbarServiceAPI {
|
|
|
26
26
|
refresh(): void;
|
|
27
27
|
/** Closes the currently open popup, if any. */
|
|
28
28
|
closePopup(): void;
|
|
29
|
+
/**
|
|
30
|
+
* Moves keyboard focus into the toolbar. Returns `false` when the toolbar
|
|
31
|
+
* cannot take focus (not rendered, hidden in read-only mode, or no enabled
|
|
32
|
+
* button), so callers can leave the caret where it is.
|
|
33
|
+
*/
|
|
34
|
+
focus(): boolean;
|
|
29
35
|
}
|
|
30
36
|
export declare const ToolbarServiceKey: ServiceKey<ToolbarServiceAPI>;
|
|
31
37
|
export declare class ToolbarPlugin implements Plugin {
|
|
@@ -64,6 +70,16 @@ export declare class ToolbarPlugin implements Plugin {
|
|
|
64
70
|
private getTabElements;
|
|
65
71
|
private initRovingTabindex;
|
|
66
72
|
private setRovingFocus;
|
|
73
|
+
/**
|
|
74
|
+
* Moves keyboard focus into the toolbar, honouring the roving tabindex: the
|
|
75
|
+
* previously focused button wins when it is still enabled, otherwise the
|
|
76
|
+
* first enabled one. Returns `false` when the toolbar cannot take focus.
|
|
77
|
+
*/
|
|
78
|
+
focus(): boolean;
|
|
79
|
+
/** Whether the toolbar is currently rendered, visible, and has an enabled button. */
|
|
80
|
+
private isFocusable;
|
|
81
|
+
/** Returns focus to the editable content, leaving the caret where it was. */
|
|
82
|
+
private returnFocusToContent;
|
|
67
83
|
/** Returns the active element, respecting shadow DOM boundaries. */
|
|
68
84
|
private getActiveElement;
|
|
69
85
|
private syncFocusedIndex;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ToolbarPlugin.d.ts","sourceRoot":"","sources":["../../../src/plugins/toolbar/ToolbarPlugin.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAIH,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,4BAA4B,CAAC;AAC9D,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,4BAA4B,CAAC;AAC9D,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAC1C,OAAO,KAAK,EAAE,MAAM,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAYxE,OAAO,EAEN,KAAK,uBAAuB,IAAI,2BAA2B,EAC3D,MAAM,8BAA8B,CAAC;AAQtC;;;;;;GAMG;AACH,MAAM,MAAM,kBAAkB,GAC3B,aAAa,CAAC,MAAM,CAAC,GACrB;IACA,QAAQ,CAAC,OAAO,EAAE,aAAa,CAAC,MAAM,CAAC,CAAC;IACxC,QAAQ,CAAC,KAAK,CAAC,EAAE,MAAM,CAAC;CACvB,CAAC;AAEL,MAAM,WAAW,mBAAmB;IACnC,QAAQ,CAAC,MAAM,EAAE,aAAa,CAAC,kBAAkB,CAAC,CAAC;IACnD;;;OAGG;IACH,QAAQ,CAAC,QAAQ,CAAC,EAAE,2BAA2B,CAAC;CAChD;AAoBD,MAAM,WAAW,iBAAiB;IACjC,sEAAsE;IACtE,OAAO,IAAI,IAAI,CAAC;IAChB,+CAA+C;IAC/C,UAAU,IAAI,IAAI,CAAC;
|
|
1
|
+
{"version":3,"file":"ToolbarPlugin.d.ts","sourceRoot":"","sources":["../../../src/plugins/toolbar/ToolbarPlugin.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAIH,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,4BAA4B,CAAC;AAC9D,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,4BAA4B,CAAC;AAC9D,OAAO,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AAC1C,OAAO,KAAK,EAAE,MAAM,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAYxE,OAAO,EAEN,KAAK,uBAAuB,IAAI,2BAA2B,EAC3D,MAAM,8BAA8B,CAAC;AAQtC;;;;;;GAMG;AACH,MAAM,MAAM,kBAAkB,GAC3B,aAAa,CAAC,MAAM,CAAC,GACrB;IACA,QAAQ,CAAC,OAAO,EAAE,aAAa,CAAC,MAAM,CAAC,CAAC;IACxC,QAAQ,CAAC,KAAK,CAAC,EAAE,MAAM,CAAC;CACvB,CAAC;AAEL,MAAM,WAAW,mBAAmB;IACnC,QAAQ,CAAC,MAAM,EAAE,aAAa,CAAC,kBAAkB,CAAC,CAAC;IACnD;;;OAGG;IACH,QAAQ,CAAC,QAAQ,CAAC,EAAE,2BAA2B,CAAC;CAChD;AAoBD,MAAM,WAAW,iBAAiB;IACjC,sEAAsE;IACtE,OAAO,IAAI,IAAI,CAAC;IAChB,+CAA+C;IAC/C,UAAU,IAAI,IAAI,CAAC;IACnB;;;;OAIG;IACH,KAAK,IAAI,OAAO,CAAC;CACjB;AAED,eAAO,MAAM,iBAAiB,+BAA+C,CAAC;AAa9E,qBAAa,aAAc,YAAW,MAAM;IAC3C,QAAQ,CAAC,EAAE,aAAa;IACxB,QAAQ,CAAC,IAAI,aAAa;IAC1B,QAAQ,CAAC,QAAQ,MAAM;IAEvB,OAAO,CAAC,OAAO,CAA8B;IAC7C,OAAO,CAAC,cAAc,CAA4B;IAClD,OAAO,CAAC,OAAO,CAAuB;IACtC,OAAO,CAAC,QAAQ,CAAC,WAAW,CAAqB;IACjD,OAAO,CAAC,QAAQ,CAAC,YAAY,CAA6B;IAC1D,OAAO,CAAC,gBAAgB,CAA8B;IACtD,OAAO,CAAC,YAAY,CAAK;IACzB,OAAO,CAAC,OAAO,CAA+B;IAC9C,OAAO,CAAC,eAAe,CAAuC;IAC9D,OAAO,CAAC,YAAY,CAA6B;IACjD,OAAO,CAAC,kBAAkB,CAA0C;IACpE,OAAO,CAAC,eAAe,CAA2B;IAClD,OAAO,CAAC,MAAM,CAAiB;gBAEnB,YAAY,CAAC,EAAE,mBAAmB;IAKxC,IAAI,CAAC,OAAO,EAAE,aAAa,GAAG,OAAO,CAAC,IAAI,CAAC;IAsCjD,6CAA6C;IAC7C,mBAAmB,IAAI,2BAA2B;IAIlD,iDAAiD;IACjD,mBAAmB,CAAC,QAAQ,EAAE,2BAA2B,GAAG,IAAI;IAQhE,OAAO,IAAI,IAAI;IAIf,OAAO,IAAI,IAAI;IAkBf,aAAa,CAAC,SAAS,EAAE,WAAW,EAAE,QAAQ,EAAE,WAAW,EAAE,GAAG,EAAE,WAAW,GAAG,IAAI;IAIpF,gBAAgB,CAAC,QAAQ,EAAE,OAAO,GAAG,IAAI;IAMzC,WAAW,CAAC,MAAM,EAAE,YAAY,GAAG,IAAI;IAavC,OAAO,CAAC,oBAAoB;IAuB5B,mHAAmH;IACnH,OAAO,CAAC,qBAAqB;IAgC7B,OAAO,CAAC,WAAW;IA+BnB,OAAO,CAAC,kBAAkB;IAa1B,OAAO,CAAC,cAAc;IAMtB,OAAO,CAAC,kBAAkB;IAO1B,OAAO,CAAC,cAAc;IAQtB;;;;OAIG;IACH,KAAK,IAAI,OAAO;IAiBhB,qFAAqF;IACrF,OAAO,CAAC,WAAW;IAMnB,6EAA6E;IAC7E,OAAO,CAAC,oBAAoB;IAI5B,oEAAoE;IACpE,OAAO,CAAC,gBAAgB;IAQxB,OAAO,CAAC,gBAAgB;IAWxB,OAAO,CAAC,oBAAoB;IA8C5B,4EAA4E;IAC5E,OAAO,CAAC,cAAc;IAWtB,OAAO,CAAC,mBAAmB;IAqC3B,OAAO,CAAC,kBAAkB;IAsC1B,OAAO,CAAC,YAAY;IA0DpB,OAAO,CAAC,kBAAkB;CAiC1B"}
|
package/dist/plugins/toolbar.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a,i as s,n as o,o as r,r as i,t as m}from"../chunks/ToolbarPlugin-
|
|
1
|
+
import{a,i as s,n as o,o as r,r as i,t as m}from"../chunks/ToolbarPlugin-O7TirXQP.mjs";export{s as TOOLBAR_LOCALE_EN,i as ToolbarOverflowBehavior,m as ToolbarPlugin,r as ToolbarRegistry,o as ToolbarServiceKey,a as loadToolbarLocale};
|
package/dist/register.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{t as r}from"./chunks/register-
|
|
1
|
+
import{t as r}from"./chunks/register-BVvV0Vl_.mjs";export{r as registerNotectlEditor};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@notectl/core",
|
|
3
|
-
"version": "2.3.
|
|
3
|
+
"version": "2.3.6",
|
|
4
4
|
"description": "A modern and accessible rich text editor shipped as a single Web Component. Immutable state, transaction-based architecture, and a plugin system that powers every feature.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
import{i as e,o as t,s as n,t as r}from"./HTMLUtils-B0nGyFLb.mjs";import{A as s,B as i,C as o,D as a,E as l,G as c,H as d,K as h,L as u,M as p,O as m,P as f,R as g,S as y,T as k,U as w,V as v,W as b,_ as I,a as S,b as x,c as R,d as M,f as C,g as P,h as T,i as E,j as B,k as A,l as N,m as O,o as D,p as L,q as H,r as z,s as F,t as j,u as $,v as _,w as K,x as V,y as U,z as q}from"./Document-D_2cIBJG.mjs";import{n as W,o as G,r as Q,s as J}from"./NodeResolver-BtIknXqD.mjs";import{a as X,c as Y,d as Z,f as ee,i as te,m as ne,n as re,o as se,p as ie,r as oe,s as ae,t as le,u as ce}from"./Selection-DC6AOGgF.mjs";import{a as de,i as he,r as ue,t as pe}from"./TypeBrands-Ch9856Gb.mjs";import{C as me,S as fe,a as ge,d as ye,f as ke,g as we,h as ve,i as be,m as Ie,n as Se,p as xe,r as Re,t as Me,u as Ce,w as Pe,x as Te,y as Ee}from"./BlockInsertion-O5pAFKid.mjs";import{i as Be,t as Ae}from"./NodeSelectionCommands-DK3iEh18.mjs";import{a as Ne,c as Oe,i as De,l as Le,n as He,o as ze,r as Fe,s as je,t as $e,u as _e}from"./Commands-D-0UXYvo.mjs";import{c as Ke,l as Ve,o as Ue,s as qe,t as We}from"./MarkCommands-CJvLGL5G.mjs";import{A as Ge,F as Qe,I as Je,L as Xe,M as Ye,N as Ze,P as et,R as tt,j as nt,t as rt,z as st}from"./CaretNavigationPlugin-DEZU09LJ.mjs";import{_ as it,b as ot,c as at,d as lt,f as ct,g as dt,i as ht,n as ut,p as pt,u as mt,y as ft}from"./ThemeEngine-kIXtSRkI.mjs";import{_ as gt,g as yt,h as kt,m as wt,v as vt}from"./TableDimensions-BcARMxQB.mjs";import{n as bt,t as It}from"./HTMLSanitization-Ce9dVT1q.mjs";import{n as St,t as xt}from"./DocumentParser-i-CreJ48.mjs";import{_ as Rt,c as Mt,d as Ct,f as Pt,g as Tt,l as Et,m as Bt,n as At,p as Nt,r as Ot,s as Dt,t as Lt,u as Ht}from"./Decoration-BwhoA4MU.mjs";import{c as zt,l as Ft,u as jt}from"./PluginHelpers-WG1Lzzh3.mjs";import{n as $t,t as _t}from"./EditorEventBoundary-zpYRxryo.mjs";import{a as Kt,c as Vt,l as Ut,r as qt,t as Wt,u as Gt}from"./StyleRuntime-C0RSqKzG.mjs";import{t as Qt}from"./Platform-ByobkiCc.mjs";import{t as Jt}from"./SchemaRegistry-acc6q_5x.mjs";import{t as Xt}from"./BlockTypePickerRegistry-BTET9jM-.mjs";import{o as Yt,t as Zt}from"./ToolbarPlugin-DdrLarMD.mjs";import{n as en,t as tn}from"./DomUtils-Bf7JLFlx.mjs";import{i as nn,n as rn,o as sn,r as on,s as an,t as ln}from"./SelectionSync-CwOHMMfI.mjs";import{n as cn,t as dn}from"./GapCursorPlugin-NozsEK9J.mjs";import{t as hn}from"./TextFormattingPlugin-DlS0SeW7.mjs";function un(e,t){const n=e.selection;if(Z(n))return Ae(e,n);if(ce(n))return null;if(!Y(n))return He(e);const r=e.getBlock(n.anchor.blockId);if(!r)return null;const s=t.range(r,n.anchor.offset);if(!s)return t.merge(e);const[i,o]=s;return e.transaction("input").deleteTextAt(r.id,i,o).setSelection(re(r.id,i)).build()}function pn(e){return un(e,{merge:Ne,range:(e,t)=>{if(t<=0)return null;if("inline"===p(e,t-1)?.kind)return[t-1,t];const n=B(e),r=E(e,t);return[t-(st(n,r)||1),t]}})}function mn(e){return un(e,{merge:ze,range:(e,t)=>{if(t>=A(e))return null;if("inline"===p(e,t)?.kind)return[t,t+1];const n=B(e),r=E(e,t);return[t,t+(tt(n,r)||1)]}})}function fn(e,t){return{children:e.children.map(e=>gn(e,t))}}function gn(e,t){const n=t.getNodeSpec(e.type);let r=e;if(n?.content&&n.content.allow.some(e=>"text"!==e)){const s=n.content.allow.includes("text");if(i(e)){if(!s&&(0!==e.children.length||0!==n.content.min)){const t=e.children.length>0?e.children:void 0,n=L(de("paragraph"),t);r=L(e.type,[n],e.id,e.attrs,e.htmlId)}}else{const n=function(e,t){const n=[];let r=[];const s=()=>{0!==r.length&&(n.push(L(de("paragraph"),r)),r=[])};for(const i of e)v(i)||q(i)?r.push(i):(s(),n.push(gn(i,t)));return s(),n}(e.children,t);r=L(e.type,n,e.id,e.attrs,e.htmlId)}}const s=n?.normalizeAttrs?.(r);if(n?.normalizeAttrs&&!z(r.attrs,s)){const{attrs:e,...t}=r;r={...t,...s?{attrs:s}:{}}}return n?.normalizeNode?.(r)??r}function yn(e,t,n){return{children:kn(e.children,t,n)}}function kn(e,t,n){let r=!1;const s=e.map(e=>{if(!g(e))return e;if(e.id===t)return r=!0,n(e);const s=kn(e.children,t,n);return s===e.children?e:(r=!0,{...e,children:s})});return r?s:e}function wn(e,t,n){if(0===t.length)return e;const r=t[0];return r?{children:e.children.map(e=>g(e)&&e.id===r?1===t.length?n(e):vn(e,t,1,n):e)}:e}function vn(e,t,n,r){const s=t[n];if(!s)return e;const i=e.children.map(e=>g(e)&&e.id===s?n===t.length-1?r(e):vn(e,t,n+1,r):e);return{...e,children:i}}function bn(e,t,n){if(t(e))return n(e);let r=!1;const s=e.map(e=>{if(!g(e))return e;const s=bn(e.children,t,n);return s?(r=!0,{...e,children:s}):e});return r?s:null}function In(e,t,n){const r=[];let s=0,i=!1;for(const o of e){if(q(o)){i||t!==s||(r.push(...n()),i=!0),r.push(o),s+=1;continue}const e=s+o.text.length;if(!i&&t>=s&&t<=e){const e=t-s,a=o.text.slice(0,e),l=o.text.slice(e);a&&r.push(I(a,o.marks)),r.push(...n()),l&&r.push(I(l,o.marks)),i=!0}else r.push(o);s=e}return i||r.push(...n()),r}function Sn(e,t,n){const r=[];let s=0;for(const i of e){if(q(i)){const e=s+1;e>t&&s<n&&r.push(i),s=e;continue}const e=s+i.text.length;if(e<=t||s>=n);else{const e=Math.max(0,t-s),o=Math.min(i.text.length,n-s),a=i.text.slice(e,o);a.length>0&&r.push(I(a,i.marks))}s=e}return 0===r.length&&r.push(I("")),r}function xn(e,t,n,r,s){const i=[];let o=0;for(const a of e){if(q(a)){i.push(a),o+=1;continue}const e=o+a.text.length;if(e<=t||o>=n)i.push(a);else if(o>=t&&e<=n){const e=s?j(a.marks,r):c(a.marks,r.type);i.push(I(a.text,e))}else{const e=Math.max(0,t-o),l=Math.min(a.text.length,n-o),d=a.text.slice(0,e),h=a.text.slice(e,l),u=a.text.slice(l);if(d&&i.push(I(d,a.marks)),h){const e=s?j(a.marks,r):c(a.marks,r.type);i.push(I(h,e))}u&&i.push(I(u,a.marks))}o=e}return i}function Rn(e,t){if(e.every(e=>v(e)||q(e)))return t;const n=e.filter(e=>!v(e)&&!q(e));return[...t,...n]}function Mn(e){return e.reduce((e,t)=>e+("inline"===t.kind?1:t.text.length),0)}var Cn=/\u200B|\u200C|\u200D|\u2060|\uFEFF/g;function Pn(e){return e.replace(Cn,"").length>0}function Tn(e){return"inline"===e.kind||Pn(e.text)}function En(e){return Nn(e.fromParentPath,e.toParentPath)&&e.toIndex>e.fromIndex?e.toIndex-1:e.toIndex}function Bn(e){return Nn(e.fromParentPath,e.toParentPath)&&En(e)===e.fromIndex}function An(e,t){const n=G(e,t.fromParentPath,t.fromIndex);if(!n||n.id!==t.movedNode.id)return null;if(t.toParentPath.includes(n.id))return null;const r=0===t.toParentPath.length?e.children.length:J(e,t.toParentPath)?.children.length??null;if(null===r||!Number.isInteger(t.toIndex)||t.toIndex<0||t.toIndex>r)return null;const s=Nn(t.fromParentPath,t.toParentPath),i=En(t);return i<0||i>r-(s?1:0)?null:{movedNode:n,destinationIndex:i}}function Nn(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}function On(e){return e.segments?Mn(e.segments):e.text.length}function Dn(e,t,n,r=!0){return yn(e,t,e=>{const t=n(f(e));return{...e,children:Rn(e.children,r?b(t):t)}})}function Ln(e,t){if(0===t.parentPath.length){const n=[...e.children];return n.splice(t.index,0,t.node),{children:n}}return wn(e,t.parentPath,e=>{const n=[...e.children];return n.splice(t.index,0,t.node),{...e,children:n}})}function Hn(e,t){if(0===t.parentPath.length){const n=[...e.children];return n.splice(t.index,1),{children:n}}return wn(e,t.parentPath,e=>{const n=[...e.children];return n.splice(t.index,1),{...e,children:n}})}function zn(e){return e.path?{path:e.path}:{}}function Fn(e){for(const t of e.steps)if("setStoredMarks"===t.type)return t.previousMarks;return e.storedMarksAfter}function jn(e,t,n){return n?e!==t?{}:{path:n}:{}}function $n(e,t,n){if(0===e.length)return!0;for(const r of e){const e=t.mapResult({blockId:r,offset:0},-1);if(e.deleted)return!1;if(e.pos.blockId!==r)return!1}return void 0!==J(n,e)}function _n(e,t){return t.blockId===e.blockId&&t.from===e.from&&t.to===e.to}var Kn=/* @__PURE__ */new WeakSet;function Vn(e){return ae(le(e))}function Un(e){if(!e)return null;const t=M(e);return k(t),t}function qn(e){switch(e.type){case"insertText":return Object.freeze({...e,marks:Un(e.marks)??Object.freeze([]),...e.segments?{segments:Zn(e.segments)}:{},...e.path?{path:er(e.path)}:{}});case"deleteText":return Object.freeze({...e,deletedMarks:Un(e.deletedMarks)??Object.freeze([]),deletedSegments:Zn(e.deletedSegments),...e.path?{path:er(e.path)}:{}});case"splitBlock":return Object.freeze({...e,...e.newBlockAttrs?{newBlockAttrs:Qn(e.newBlockAttrs)}:{},...e.path?{path:er(e.path)}:{}});case"mergeBlocks":return Object.freeze({...e,...e.sourceAttrs?{sourceAttrs:Qn(e.sourceAttrs)}:{},...e.path?{path:er(e.path)}:{}});case"addMark":case"removeMark":return Object.freeze({...e,mark:Gn(e.mark),...e.path?{path:er(e.path)}:{}});case"setStoredMarks":return Object.freeze({...e,marks:Un(e.marks),previousMarks:Un(e.previousMarks)});case"setBlockType":return Object.freeze({...e,...e.attrs?{attrs:Qn(e.attrs)}:{},...e.previousAttrs?{previousAttrs:Qn(e.previousAttrs)}:{},...e.path?{path:er(e.path)}:{}});case"insertNode":return Object.freeze({...e,parentPath:er(e.parentPath),node:Xn(e.node)});case"removeNode":return Object.freeze({...e,parentPath:er(e.parentPath),removedNode:Xn(e.removedNode)});case"moveNode":return Object.freeze({...e,fromParentPath:er(e.fromParentPath),toParentPath:er(e.toParentPath),movedNode:Xn(e.movedNode)});case"setNodeAttr":return Object.freeze({...e,path:er(e.path),...e.attrs?{attrs:Qn(e.attrs)}:{},...e.previousAttrs?{previousAttrs:Qn(e.previousAttrs)}:{}});case"insertInlineNode":return Object.freeze({...e,node:Yn(e.node),...e.path?{path:er(e.path)}:{}});case"removeInlineNode":return Object.freeze({...e,removedNode:Yn(e.removedNode),...e.path?{path:er(e.path)}:{}});case"setInlineNodeAttr":return Object.freeze({...e,attrs:Jn(e.attrs),previousAttrs:Jn(e.previousAttrs),...e.path?{path:er(e.path)}:{}})}}function Wn(e,t){if(e.steps.length!==e.forwardStepMaps.length)throw new Error("A transaction requires exactly one forward StepMap per step.");const n=Object.freeze({steps:Object.freeze([...e.steps]),selectionBefore:e.selectionBefore,selectionAfter:e.selectionAfter,storedMarksAfter:e.storedMarksAfter,mapping:Mt.from(e.forwardStepMaps),forwardStepMaps:Object.freeze([...e.forwardStepMaps]),metadata:Object.freeze({...e.metadata})});return!1!==t?.mapsVerified&&Kn.add(n),n}function Gn(e){const t=$(e);return K(t),t}function Qn(e){const t=S(e);return U(t),t}function Jn(e){return Object.freeze({...e})}function Xn(e){const t=D(e);return x(t),t}function Yn(e){const t=N(e);return o(t),t}function Zn(e){const t=F(e);return V(t),t}function er(e){return Object.freeze([...e])}var tr={insertText:{apply:function(e,t){return Dn(e,t.blockId,e=>{return t.segments?(n=e,r=t.offset,s=t.segments,In(n,r,()=>s.map(C))):function(e,t,n,r){return In(e,t,()=>[I(n,r)])}(e,t.offset,t.text,t.marks);var n,r,s})},invert:function(e){return{type:"deleteText",blockId:e.blockId,from:e.offset,to:e.offset+On(e),deletedText:e.text,deletedMarks:e.marks,deletedSegments:e.segments??[H(e.text,[...e.marks])],...zn(e)}},getMap:function(e,t){return{type:"shift",blockId:t.blockId,from:t.offset,to:t.offset,newLen:On(t)}},map:function(e,t,n){const r=Bt(e.blockId,e.offset,t,-1);return r?r.blockId===e.blockId&&r.from===e.offset?e:{type:"insertText",blockId:r.blockId,offset:r.from,text:e.text,marks:e.marks,...e.segments?{segments:e.segments}:{},...jn(e.blockId,r.blockId,e.path)}:null}},deleteText:{apply:function(e,t){return Dn(e,t.blockId,e=>function(e,t,n){const r=[];let s=0;for(const i of e){if(q(i)){const e=s+1;(e<=t||s>=n)&&r.push(i),s=e;continue}const e=s+i.text.length;if(e<=t||s>=n)r.push(i);else{const e=Math.max(0,t-s),o=Math.min(i.text.length,n-s),a=i.text.slice(0,e)+i.text.slice(o);a.length>0&&r.push(I(a,i.marks))}s=e}return r}(e,t.from,t.to))},invert:function(e){return{type:"insertText",blockId:e.blockId,offset:e.from,text:e.deletedText,marks:e.deletedMarks,segments:e.deletedSegments,...zn(e)}},getMap:function(e,t){return{type:"shift",blockId:t.blockId,from:t.from,to:t.to,newLen:0}},map:function(e,t,n){const r=Pt(e.blockId,e.from,e.to,t);if(!r)return null;if(_n({blockId:e.blockId,from:e.from,to:e.to},r))return e;const i=W(n,r.blockId);if(!i)return null;const o=B(i).slice(r.from,r.to),a=s(i,r.from),l=m(i,r.from,r.to);return{type:"deleteText",blockId:r.blockId,from:r.from,to:r.to,deletedText:o,deletedMarks:a,deletedSegments:l,...jn(e.blockId,r.blockId,e.path)}}},splitBlock:{apply:function(e,t){const n=bn(e.children,e=>e.some(e=>g(e)&&e.id===t.blockId),e=>{const n=e.findIndex(e=>g(e)&&e.id===t.blockId);if(-1===n)return e;const r=e[n],s=f(r),i=A(r),o=Sn(s,0,t.offset),a=Sn(s,t.offset,i),l={...r,children:b(o)},c=void 0!==t.newBlockType,d=t.newBlockType??r.type,h=c?t.newBlockAttrs:r.attrs,u=L(d,b(a),t.newBlockId,h,t.newBlockHTMLId),p=[...e];return p.splice(n,1,l,u),p});return n?{children:n}:e},invert:function(e){return{type:"mergeBlocks",targetBlockId:e.blockId,sourceBlockId:e.newBlockId,targetLengthBefore:e.offset,...void 0!==e.newBlockType?{sourceType:e.newBlockType}:{},...e.newBlockAttrs?{sourceAttrs:e.newBlockAttrs}:{},...void 0!==e.newBlockHTMLId?{sourceHTMLId:e.newBlockHTMLId}:{},...zn(e)}},getMap:function(e,t){return{type:"split",blockId:t.blockId,offset:t.offset,newBlockId:t.newBlockId}},map:function(e,t,n){const r=Bt(e.blockId,e.offset,t,-1);return r?r.blockId===e.blockId&&r.from===e.offset?e:{type:"splitBlock",blockId:r.blockId,offset:r.from,newBlockId:e.newBlockId,...void 0!==e.newBlockType?{newBlockType:e.newBlockType}:{},...e.newBlockAttrs?{newBlockAttrs:e.newBlockAttrs}:{},...void 0!==e.newBlockHTMLId?{newBlockHTMLId:e.newBlockHTMLId}:{},...jn(e.blockId,r.blockId,e.path)}:null}},mergeBlocks:{apply:function(e,t){const n=bn(e.children,e=>e.some(e=>g(e)&&e.id===t.targetBlockId)&&e.some(e=>g(e)&&e.id===t.sourceBlockId),e=>{const n=e.findIndex(e=>g(e)&&e.id===t.targetBlockId),r=e.findIndex(e=>g(e)&&e.id===t.sourceBlockId);if(-1===n||-1===r)return e;const s=e[n],i=e[r],o=f(s),a=f(i),l=b([...o,...a]),c={...s,children:l};return e.filter(e=>!g(e)||e.id!==t.sourceBlockId).map(e=>g(e)&&e.id===t.targetBlockId?c:e)});return n?{children:n}:e},invert:function(e){return{type:"splitBlock",blockId:e.targetBlockId,offset:e.targetLengthBefore,newBlockId:e.sourceBlockId,...void 0!==e.sourceType?{newBlockType:e.sourceType}:{},...e.sourceAttrs?{newBlockAttrs:e.sourceAttrs}:{},...void 0!==e.sourceHTMLId?{newBlockHTMLId:e.sourceHTMLId}:{},...zn(e)}},getMap:function(e,t){return{type:"merge",targetBlockId:t.targetBlockId,sourceBlockId:t.sourceBlockId,targetLengthBefore:t.targetLengthBefore}},map:function(e,t,n){if(t.isEmpty)return e;const r=t.mapResult({blockId:e.targetBlockId,offset:0},-1),s=t.mapResult({blockId:e.sourceBlockId,offset:0},-1);if(r.deleted||s.deleted)return null;const i=r.pos.blockId,o=s.pos.blockId;if(i===o)return null;const a=W(n,i);if(!a)return null;const l=A(a);return i===e.targetBlockId&&o===e.sourceBlockId&&l===e.targetLengthBefore?e:{type:"mergeBlocks",targetBlockId:i,sourceBlockId:o,targetLengthBefore:l,...void 0!==e.sourceType?{sourceType:e.sourceType}:{},...e.sourceAttrs?{sourceAttrs:e.sourceAttrs}:{},...void 0!==e.sourceHTMLId?{sourceHTMLId:e.sourceHTMLId}:{},...jn(e.targetBlockId,i,e.path)}}},addMark:{apply:function(e,t){return Dn(e,t.blockId,e=>xn(e,t.from,t.to,t.mark,!0))},invert:function(e){return{type:"removeMark",blockId:e.blockId,from:e.from,to:e.to,mark:e.mark,...zn(e)}},getMap:function(e,t){return Dt},map:function(e,t,n){const r=Pt(e.blockId,e.from,e.to,t);return r?_n({blockId:e.blockId,from:e.from,to:e.to},r)?e:{type:"addMark",blockId:r.blockId,from:r.from,to:r.to,mark:e.mark,...jn(e.blockId,r.blockId,e.path)}:null}},removeMark:{apply:function(e,t){return Dn(e,t.blockId,e=>xn(e,t.from,t.to,t.mark,!1))},invert:function(e){return{type:"addMark",blockId:e.blockId,from:e.from,to:e.to,mark:e.mark,...zn(e)}},getMap:function(e,t){return Dt},map:function(e,t,n){const r=Pt(e.blockId,e.from,e.to,t);return r?_n({blockId:e.blockId,from:e.from,to:e.to},r)?e:{type:"removeMark",blockId:r.blockId,from:r.from,to:r.to,mark:e.mark,...jn(e.blockId,r.blockId,e.path)}:null}},setStoredMarks:{apply:function(e){return e},invert:function(e){return{type:"setStoredMarks",marks:e.previousMarks,previousMarks:e.marks}},getMap:function(e,t){return Dt},map:function(e,t,n){return e}},setBlockType:{apply:function(e,t){return yn(e,t.blockId,e=>{const{attrs:n,...r}=e;return{...r,type:t.nodeType,...t.attrs?{attrs:t.attrs}:{}}})},invert:function(e){return{type:"setBlockType",blockId:e.blockId,nodeType:e.previousNodeType,attrs:e.previousAttrs,previousNodeType:e.nodeType,previousAttrs:e.attrs,...zn(e)}},getMap:function(e,t){return Dt},map:function(e,t,n){if(t.isEmpty)return e;const r=t.mapResult({blockId:e.blockId,offset:0},-1);if(r.deleted)return null;const s=r.pos.blockId,i=W(n,s);return i?s===e.blockId&&i.type===e.previousNodeType&&z(i.attrs,e.previousAttrs)?e:{type:"setBlockType",blockId:s,nodeType:e.nodeType,...e.attrs?{attrs:e.attrs}:{},previousNodeType:i.type,...i.attrs?{previousAttrs:i.attrs}:{},...jn(e.blockId,s,e.path)}:null}},insertNode:{apply:Ln,invert:function(e){return{type:"removeNode",parentPath:e.parentPath,index:e.index,removedNode:e.node}},getMap:function(e,t){return{type:"childIndexShift",parentPath:t.parentPath,fromIndex:t.index,delta:1,insertedBlockIds:Et(t.node)}},map:function(e,t,n){if(!$n(e.parentPath,t,n))return null;const r=Nt(e.parentPath,e.index,t);return r===e.index?e:{type:"insertNode",parentPath:e.parentPath,index:r,node:e.node}}},removeNode:{apply:Hn,invert:function(e){return{type:"insertNode",parentPath:e.parentPath,index:e.index,node:e.removedNode}},getMap:function(e,t){return{type:"blockRemoval",removedBlockIds:Et(t.removedNode),parentPath:t.parentPath,index:t.index}},map:function(e,t,n){if(!$n(e.parentPath,t,n))return null;const r=t.mapResult({blockId:e.removedNode.id,offset:0},-1);if(r.deleted)return null;if(r.pos.blockId!==e.removedNode.id)return null;const s=Ct(e.parentPath,e.index,t);if(null===s)return null;const i=G(n,e.parentPath,s);return i?i.id!==e.removedNode.id?null:s===e.index&&i===e.removedNode?e:{type:"removeNode",parentPath:e.parentPath,index:s,removedNode:i}:null}},moveNode:{apply:function(e,t){const n=An(e,t);return!n||Bn(t)?e:Ln(Hn(e,{type:"removeNode",parentPath:t.fromParentPath,index:t.fromIndex,removedNode:n.movedNode}),{type:"insertNode",parentPath:t.toParentPath,index:n.destinationIndex,node:n.movedNode})},invert:function(e){const t=En(e),n=e.fromParentPath.length===e.toParentPath.length&&e.fromParentPath.every((t,n)=>t===e.toParentPath[n])&&e.fromIndex>t?e.fromIndex+1:e.fromIndex;return{type:"moveNode",fromParentPath:e.toParentPath,fromIndex:t,toParentPath:e.fromParentPath,toIndex:n,movedNode:e.movedNode}},getMap:function(e,t){const n=An(e,t);return!n||Bn(t)?Dt:{type:"moveNode",movedNodeId:t.movedNode.id,fromParentPath:t.fromParentPath,fromIndex:t.fromIndex,toParentPath:t.toParentPath,destinationIndex:n.destinationIndex}},map:function(e,t,n){if(!$n(e.fromParentPath,t,n))return null;if(!$n(e.toParentPath,t,n))return null;const r=t.mapResult({blockId:e.movedNode.id,offset:0},-1);if(r.deleted||r.pos.blockId!==e.movedNode.id)return null;const s=Ct(e.fromParentPath,e.fromIndex,t);if(null===s)return null;const i=Nt(e.toParentPath,e.toIndex,t),o=G(n,e.fromParentPath,s);if(!o||o.id!==e.movedNode.id)return null;const a={type:"moveNode",fromParentPath:e.fromParentPath,fromIndex:s,toParentPath:e.toParentPath,toIndex:i,movedNode:o};return An(n,a)?s===e.fromIndex&&i===e.toIndex&&o===e.movedNode?e:a:null}},setNodeAttr:{apply:function(e,t){const n=t.path[t.path.length-1];return n?yn(e,n,e=>({...e,attrs:t.attrs})):e},invert:function(e){return{type:"setNodeAttr",path:e.path,attrs:e.previousAttrs,previousAttrs:e.attrs}},getMap:function(e,t){return Dt},map:function(e,t,n){if(t.isEmpty)return e;if(!$n(e.path,t,n))return null;const r=J(n,e.path);return r?{type:"setNodeAttr",path:e.path,attrs:e.attrs,...r.attrs?{previousAttrs:r.attrs}:{}}:null}},insertInlineNode:{apply:function(e,t){return Dn(e,t.blockId,e=>function(e,t,n){const r=[];let s=0,i=!1;for(const o of e){if(q(o)){i||t!==s||(r.push(n),i=!0),r.push(o),s+=1;continue}const e=s+o.text.length;if(!i&&t>=s&&t<=e){const e=t-s,a=o.text.slice(0,e),l=o.text.slice(e);a&&r.push(I(a,o.marks)),r.push(n),l&&r.push(I(l,o.marks)),i=!0}else r.push(o);s=e}return i||r.push(n),r}(e,t.offset,t.node))},invert:function(e){return{type:"removeInlineNode",blockId:e.blockId,offset:e.offset,removedNode:e.node,...zn(e)}},getMap:function(e,t){return{type:"shift",blockId:t.blockId,from:t.offset,to:t.offset,newLen:1}},map:function(e,t,n){const r=Bt(e.blockId,e.offset,t,-1);return r?r.blockId===e.blockId&&r.from===e.offset?e:{type:"insertInlineNode",blockId:r.blockId,offset:r.from,node:e.node,...jn(e.blockId,r.blockId,e.path)}:null}},removeInlineNode:{apply:function(e,t){return Dn(e,t.blockId,e=>function(e,t){const n=[];let r=0;for(const s of e)q(s)?(r!==t&&n.push(s),r+=1):(n.push(s),r+=s.text.length);return n}(e,t.offset))},invert:function(e){return{type:"insertInlineNode",blockId:e.blockId,offset:e.offset,node:e.removedNode,...zn(e)}},getMap:function(e,t){return{type:"shift",blockId:t.blockId,from:t.offset,to:t.offset+1,newLen:0}},map:function(e,t,n){const r=Pt(e.blockId,e.offset,e.offset+1,t,1,1);if(!r)return null;if(r.to-r.from!==1)return null;const s=W(n,r.blockId);if(!s)return null;const i=p(s,r.from);return i&&"inline"===i.kind&&q(i.node)?(o=e.removedNode)===(a=i.node)||o.inlineType===a.inlineType&&z(o.attrs,a.attrs)?r.blockId===e.blockId&&r.from===e.offset?e:{type:"removeInlineNode",blockId:r.blockId,offset:r.from,removedNode:i.node,...jn(e.blockId,r.blockId,e.path)}:null:null;var o,a}},setInlineNodeAttr:{apply:function(e,t){return Dn(e,t.blockId,e=>function(e,t,n){const r=[];let s=0;for(const i of e)q(i)?(s===t?r.push({...i,attrs:n}):r.push(i),s+=1):(r.push(i),s+=i.text.length);return r}(e,t.offset,t.attrs),!1)},invert:function(e){return{type:"setInlineNodeAttr",blockId:e.blockId,offset:e.offset,attrs:e.previousAttrs,previousAttrs:e.attrs,...zn(e)}},getMap:function(e,t){return Dt},map:function(e,t,n){const r=Pt(e.blockId,e.offset,e.offset+1,t,1,1);if(!r)return null;if(r.to-r.from!==1)return null;if(r.blockId===e.blockId&&r.from===e.offset)return e;const s=W(n,r.blockId);if(!s)return null;const i=p(s,r.from);return i&&"inline"===i.kind&&q(i.node)?{type:"setInlineNodeAttr",blockId:r.blockId,offset:r.from,attrs:e.attrs,previousAttrs:i.node.attrs,...jn(e.blockId,r.blockId,e.path)}:null}}};function nr(e){return tr[e.type]}function rr(e,t){return nr(t).apply(e,t)}function sr(e){return nr(e).invert(e)}function ir(e,t){return nr(t).getMap(e,t)}function or(e,t,n){return t.isEmpty?e:nr(e).map(e,t,n)}function ar(e){const t=e.steps.map(sr).reverse().map(qn);return Wn({steps:t,selectionBefore:Vn(e.selectionAfter),selectionAfter:Vn(e.selectionBefore),storedMarksAfter:Un(Fn(e)),forwardStepMaps:t.map(()=>Dt),metadata:{origin:"history",timestamp:Date.now()}},{mapsVerified:!1})}var lr=class{steps=[];stepMaps=[];selection;storedMarks;selectionBefore;origin;workingDoc;_readonlyAllowed=!1;constructor(e,t,n="api",r){const s=Vn(e);this.selection=s,this.selectionBefore=s,this.storedMarks=Un(t),this.origin=n,this.workingDoc=r??null}insertText(e,t,n,r,s){const i={type:"insertText",blockId:e,offset:t,text:n,marks:r,...s?{segments:s}:{}};return this.appendStep(i),this}deleteText(e,t,n,r,s,i){let o;if(i)o=i;else if(this.workingDoc){const i=W(this.workingDoc,e);o=i?m(i,t,n):[H(r,[...s])]}else o=[H(r,[...s])];const a={type:"deleteText",blockId:e,from:t,to:n,deletedText:r,deletedMarks:s,deletedSegments:o};return this.appendStep(a),this}deleteTextAt(e,t,n){const r=this.requireDoc("deleteTextAt"),i=this.requireBlock(r,e),o=B(i).slice(t,n),a=s(i,t),l=m(i,t,n);return this.deleteText(e,t,n,o,a,l)}splitBlock(e,t,n){const r={type:"splitBlock",blockId:e,offset:t,newBlockId:n};return this.appendStep(r),this}mergeBlocks(e,t,n,r,s,i){const o={type:"mergeBlocks",targetBlockId:e,sourceBlockId:t,targetLengthBefore:n,...void 0!==r?{sourceType:r}:{},...s?{sourceAttrs:s}:{},...void 0!==i?{sourceHTMLId:i}:{}};return this.appendStep(o),this}mergeBlocksAt(e,t){const n=this.requireDoc("mergeBlocksAt"),r=this.requireBlock(n,e),s=this.requireBlock(n,t),i=A(r);return this.mergeBlocks(e,t,i,s.type,s.attrs,s.htmlId)}addMark(e,t,n,r){const s=this.tryGetBlock(e);if(!s){const s={type:"addMark",blockId:e,from:t,to:n,mark:r};return this.appendStep(s),this}const i=function(e,t,n,r){const s=[];if(t>=n)return s;let i=null,o=0;const a=()=>{i&&(s.push(i),i=null)};for(const l of e){const e=o+(q(l)?1:l.text.length);if(e<=t||o>=n){o=e;continue}const s=Math.max(o,t),c=Math.min(e,n);q(l)?i&&(i.to=c):l.marks.some(e=>e.type===r)?a():i?i.to=c:i={from:s,to:c},o=e}return a(),s}(f(s),t,n,r.type);for(const o of i){const t={type:"addMark",blockId:e,from:o.from,to:o.to,mark:r};this.appendStep(t)}return this}removeMark(e,t,n,r){const s=this.tryGetBlock(e);if(!s){const s={type:"removeMark",blockId:e,from:t,to:n,mark:r};return this.appendStep(s),this}const i=function(e,t,n,r){const s=[];if(t>=n)return s;let i=null,o=0;const a=()=>{i&&(s.push(i),i=null)};for(const l of e){const e=o+(q(l)?1:l.text.length);if(e<=t||o>=n){o=e;continue}const s=Math.max(o,t),c=Math.min(e,n);if(q(l))i&&(i.to=c);else{const e=l.marks.find(e=>e.type===r);e?i&&w(i.mark,e)?i.to=c:(a(),i={from:s,to:c,mark:e}):a()}o=e}return a(),s}(f(s),t,n,r.type);for(const o of i){const t={type:"removeMark",blockId:e,from:o.from,to:o.to,mark:o.mark};this.appendStep(t)}return this}setBlockType(e,t,n){const r=this.requireDoc("setBlockType"),s=this.requireBlock(r,e),i={type:"setBlockType",blockId:e,nodeType:t,...n?{attrs:n}:{},previousNodeType:s.type,...s.attrs?{previousAttrs:s.attrs}:{}};return this.appendStep(i),this}insertNode(e,t,n){const r={type:"insertNode",parentPath:e,index:t,node:n};return this.appendStep(r),this}removeNode(e,t){const n=this.requireDoc("removeNode"),r=G(n,e,t);if(!r)throw new Error(`Node at index ${t} not found under parent path [${e.join(", ")}].`);const s={type:"removeNode",parentPath:e,index:t,removedNode:r};return this.appendStep(s),this}moveNode(e,t,n,r){const s=this.requireDoc("moveNode"),i=G(s,e,t);if(!i)throw new Error(`Node at index ${t} not found under source path [${e.join(", ")}].`);if(n.includes(i.id))throw new Error(`Cannot move node "${i.id}" into its own subtree.`);const o=0===n.length?s.children.length:J(s,n)?.children.length??-1;if(!Number.isInteger(r)||r<0||r>o)throw new Error(`Invalid destination index ${r} under path [${n.join(", ")}].`);const a={type:"moveNode",fromParentPath:e,fromIndex:t,toParentPath:n,toIndex:r,movedNode:i};return Bn(a)||this.appendStep(a),this}setNodeAttr(e,t){const n=this.requireDoc("setNodeAttr"),r=J(n,e);if(!r)throw new Error(`Node not found at path [${e.join(", ")}].`);const s={type:"setNodeAttr",path:e,attrs:t,...r.attrs?{previousAttrs:r.attrs}:{}};return this.appendStep(s),this}insertInlineNode(e,t,n){const r={type:"insertInlineNode",blockId:e,offset:t,node:n};return this.appendStep(r),this}removeInlineNode(e,t){const n=this.requireDoc("removeInlineNode"),r=this.requireBlock(n,e),s=p(r,t);if(!s||"inline"!==s.kind)throw new Error(`No InlineNode at offset ${t} in block "${e}".`);const i={type:"removeInlineNode",blockId:e,offset:t,removedNode:s.node};return this.appendStep(i),this}setInlineNodeAttr(e,t,n){const r=this.requireDoc("setInlineNodeAttr"),s=this.requireBlock(r,e),i=f(s);let o=0;for(const a of i){if(q(a)&&o===t){const r={type:"setInlineNodeAttr",blockId:e,offset:t,attrs:n,previousAttrs:a.attrs};return this.appendStep(r),this}o+=q(a)?1:a.text.length}throw new Error(`No InlineNode at offset ${t} in block "${e}".`)}readonlyAllowed(){return this._readonlyAllowed=!0,this}setSelection(e){return this.selection=Vn(e),this}setNodeSelection(e,t){return this.selection=Vn(te(e,t)),this}setStoredMarks(e,t){return this.appendStep({type:"setStoredMarks",marks:e,previousMarks:t}),this.storedMarks=Un(e),this}build(){return Wn({steps:this.steps,selectionBefore:this.selectionBefore,selectionAfter:this.selection,storedMarksAfter:this.storedMarks,forwardStepMaps:this.stepMaps,metadata:{origin:this.origin,timestamp:Date.now(),...this._readonlyAllowed?{readonlyAllowed:!0}:{}}})}requireDoc(e){if(!this.workingDoc)throw new Error(`${e} requires a document. Use state.transaction() or provide doc to constructor.`);return this.workingDoc}requireBlock(e,t){const n=W(e,t);if(!n)throw new Error(`Block "${t}" not found in working document.`);return n}tryGetBlock(e){return this.workingDoc?W(this.workingDoc,e)??null:null}appendStep(e){const t=qn(e);this.steps.push(t),this.advanceDoc(t)}advanceDoc(e){const t=this.workingDoc??cr;this.stepMaps.push(Tt(ir(t,e))),this.workingDoc&&(this.workingDoc=rr(this.workingDoc,e))}},cr={children:[]},dr=class e{doc;selection;storedMarks;schema;_blockMap=null;_blockOrder=null;constructor(e,t,n,r){if(this.doc=y(e),this.selection=ae(t),n){const e=M(n);k(e),this.storedMarks=e}else this.storedMarks=null;this.schema=r}static create(t){const n=t?.schema??Ue(),r=t?.doc?R(t.doc):O(),s=mr(r.children),i=t?.selection?ur(r,le(t.selection)):re(s?s.id:pe(""),0);return new e(r,i,null,n)}transaction(e="api"){return new lr(this.selection,this.storedMarks,e,this.doc)}apply(t){let n=this.doc;for(const e of t.steps)n=rr(n,e);const r=ur(n,le(t.selectionAfter));return new e(n,r,t.storedMarksAfter,this.schema)}getBlock(e){return this._blockMap??=function(e){const t=/* @__PURE__ */new Map;return function e(n){for(const r of n)g(r)&&(t.set(r.id,r),e(r.children))}(e.children),t}(this.doc),this._blockMap.get(e)}getBlockOrder(){return this._blockOrder??=function(e){const t=[];return function e(n){for(const r of n)g(r)&&(i(r)?t.push(r.id):e(r.children))}(e.children),Object.freeze(t)}(this.doc),this._blockOrder}getNodePath(e){return Q(this.doc,e)}getParent(e){const t=Q(this.doc,e);if(!t||t.length<=1)return;const n=t[t.length-2];return n?W(this.doc,n):void 0}withSelection(t){const n=ur(this.doc,le(t));return new e(this.doc,n,this.storedMarks,this.schema)}withStoredMarks(t){return new e(this.doc,this.selection,t,this.schema)}toJSON(){return{doc:R(this.doc),selection:le(this.selection)}}static fromJSON(t,n){return e.create({doc:t.doc,selection:t.selection,schema:n})}};function hr(e,t){const n=W(e,t.blockId);if(n&&i(n)){const e=A(n),r=Number.isFinite(t.offset)?Math.trunc(t.offset):0,s=Math.max(0,Math.min(e,r));return s!==t.offset?X(t.blockId,s,t.path):t}const r=mr(n?n.children:e.children);if(r)return X(r.id,0);const s=mr(e.children);return s?X(s.id,0):t}function ur(e,t){if(Z(t))return W(e,t.nodeId)?t:pr(e,t);if(ce(t))return W(e,t.blockId)?t:pr(e,t);const n=hr(e,t.anchor),r=hr(e,t.head);return n===t.anchor&&r===t.head?t:se(n,r)}function pr(e,t){const n=mr(e.children);return n?re(n.id,0):t}function mr(e){for(const t of e){if(!g(t))continue;if(i(t))return t;const e=mr(t.children);if(e)return e}return null}function fr(e,t,n){const r=function(e){const t=kr(e.children,yr);return t===e.children?e:{children:t}}(function(e){const t=kr(e.children,gr);return t===e.children?e:{children:t}}(e)),s=R(r),i=t?fn(s,t):s,o=t?Ve(t):void 0;n(dr.create({doc:i,schema:o}))}function gr(e){const n=kr(e.children,e=>v(e)||q(e)?e:gr(e)),r=e.htmlId,s=t(r),i=Object.prototype.hasOwnProperty.call(e,"htmlId"),o=r===s&&(void 0!==s||!i);if(n===e.children&&o)return e;const{htmlId:a,...l}=e;return{...l,...s?{htmlId:s}:{},children:n}}function yr(e){if(!e.children)return e;const t=kr(e.children,e=>v(e)||q(e)?e.marks?e:{...e,marks:[]}:yr(e));return t===e.children?e:{...e,children:t}}function kr(e,t){let n=!1;const r=e.map(e=>{const r=t(e);return r!==e&&(n=!0),r});return n?r:e}function wr(e){return e.doc.children.map(vr).join("\n")}function vr(e){return i(e)?B(e):a(e).map(vr).join("\n")}function br(e){if(!e)return!0;if(0===e.children.length)return!0;if(e.children.length>1)return!1;const t=e.children[0];return!t||"paragraph"===t.type&&0===A(t)}var Ir={shorthand:!0,paste:"auto"},Sr={shorthand:!1,paste:"never"};function xr(e){return void 0===e||!0===e?Ir:!1===e?Sr:{shorthand:e.shorthand??!0,paste:e.paste??"auto"}}var Rr=class{config={};getConfig(){return this.config}setConfig(e){this.config=e}mergeConfig(e){this.config={...this.config,...e}}applyAttribute(e,t,n){if("placeholder"===e){const e=t??void 0;this.config={...this.config,placeholder:e},this.applyPlaceholder(e,n.contentElement)}if("readonly"===e){const e=null!==t;this.applyReadonly(e,n.contentElement,n.pluginManager),this.config={...this.config,readonly:e}}if("theme"===e){const e=t??void 0;this.config={...this.config,theme:e},n.themeController?.apply(e??at.Light)}"paper-size"===e&&(null===t?(n.applyPaperSize(void 0),this.config={...this.config,paperSize:void 0}):it(t)&&(n.applyPaperSize(t),this.config={...this.config,paperSize:t})),"dir"===e&&this.applyDir("ltr"===t||"rtl"===t?t:void 0,n.contentElement,n.editorWrapper)}applyRuntimeConfig(e,t){void 0!==e.placeholder&&this.applyPlaceholder(e.placeholder,t.contentElement),void 0!==e.readonly&&this.applyReadonly(e.readonly,t.contentElement,t.pluginManager),"paperSize"in e&&t.applyPaperSize(e.paperSize),"dir"in e&&this.applyDir(e.dir,t.contentElement,t.editorWrapper),this.config={...this.config,...e}}applyTheme(e,t){this.config={...this.config,theme:e},t?.apply(e)}getTheme(){return this.config.theme??at.Light}get isReadOnly(){return this.config.readonly??!1}get markdownShorthand(){return xr(this.config.markdown).shorthand}get pasteMarkdown(){return xr(this.config.markdown).paste}getPaperSize(){return this.config.paperSize}applyPlaceholder(e,t){if(!t)return;const n=t.getAttribute("data-default-placeholder")??"";t.setAttribute("data-placeholder",e??n)}applyReadonly(e,t,n){t&&(t.contentEditable=e?"false":"true",e?t.setAttribute("aria-readonly","true"):t.removeAttribute("aria-readonly"),n?.setReadOnly(e))}applyDir(e,t,n){t&&(e?(n?.setAttribute("dir",e),t.setAttribute("dir",e)):(n?.removeAttribute("dir"),t.removeAttribute("dir")))}},Mr={error(e,t){void 0===t?console.error(e):console.error(e,t)},warn(e,t){void 0===t?console.warn(e):console.warn(e,t)},info(e,t){void 0===t?console.info(e):console.info(e,t)},debug(e,t){void 0===t?console.debug(e):console.debug(e,t)}},Cr={error(){},warn(){},info(){},debug(){}};function Pr(e,t){const n=`[${t}]`;return{error(t,r){Tr(()=>e.error(`${n} ${t}`,r))},warn(t,r){Tr(()=>e.warn(`${n} ${t}`,r))},info(t,r){Tr(()=>e.info(`${n} ${t}`,r))},debug(t,r){Tr(()=>e.debug(`${n} ${t}`,r))}}}function Tr(e){try{const t=e();null===t||"object"!=typeof t&&"function"!=typeof t||Promise.resolve(t).then(void 0,()=>{})}catch{}}var Er=class{listeners=/* @__PURE__ */new Map;log;constructor(e=Mr){this.log=e}setLogger(e=Mr){this.log=e}on(e,t){this.listeners.has(e)||this.listeners.set(e,/* @__PURE__ */new Set),this.listeners.get(e)?.add(t)}off(e,t){this.listeners.get(e)?.delete(t)}emit(e,t){const n=this.listeners.get(e);if(!n)return;const r=this.log;for(const i of n)try{const n=i(t);this.observeListenerResult(r,e,n)}catch(s){this.reportListenerError(r,e,s)}}observeListenerResult(e,t,n){null===n||"object"!=typeof n&&"function"!=typeof n||Promise.resolve(n).then(void 0,n=>{this.reportListenerError(e,t,n)})}reportListenerError(e,t,n){try{const r=e.error(`[EditorEventEmitter] Listener error on "${String(t)}"`,n);null===r||"object"!=typeof r&&"function"!=typeof r||Promise.resolve(r).then(void 0,()=>{})}catch{}}clear(){this.listeners.clear()}};function Br(e,t,n){if(i(e))return t.selectedLeafIds.has(e.id)?function(e,t){const n=A(e),r=e.id===t.firstBlockId?t.firstOffset:0,s=e.id===t.lastBlockId?t.lastOffset:n;if(0===r&&s===n)return e;const i=m(e,r,s),o=h(i),{htmlId:a,...l}=e;return{...l,children:o}}(e,t):null;const r=a(e),s=[];let o=r.length!==e.children.length;for(const i of r){const e=Br(i,t,n);e?(s.push(e),e!==i&&(o=!0)):o=!0}if(0===s.length)return null;if(!o)return e;const{htmlId:l,...c}=e,d={...c,children:s};return n?.getNodeSpec(e.type)?.transformSelectionSlice?.(e,d)??d}var Ar=class{element;getState;dispatch;schemaRegistry;syncSelection;isReadOnly;handleCopy;handleCut;constructor(e,t){this.element=e,this.getState=t.getState,this.dispatch=t.dispatch,this.schemaRegistry=t.schemaRegistry,this.syncSelection=t.syncSelection,this.isReadOnly=t.isReadOnly??(()=>!1),this.handleCopy=this.onCopy.bind(this),this.handleCut=this.onCut.bind(this),e.addEventListener("copy",this.handleCopy),e.addEventListener("cut",this.handleCut)}onCopy(e){if(!_t(e,this.element))return;this.syncSelection?.();const t=this.getState(),n=t.selection;if(ce(n))return;if(ee(n)&&Y(n))return;e.preventDefault();const r=e.clipboardData;r&&(Z(n)?this.writeNodeSelectionToClipboard(r,t):this.writeTextSelectionToClipboard(r,t))}onCut(e){if(!_t(e,this.element))return;if(this.isReadOnly())return;this.syncSelection?.();const t=this.getState(),n=t.selection;if(ce(n))return;if(ee(n)&&Y(n))return;e.preventDefault();const r=e.clipboardData;if(r)if(Z(n)){this.writeNodeSelectionToClipboard(r,t);const e=Ae(t,n);e&&this.dispatch(e)}else{this.writeTextSelectionToClipboard(r,t);const e=He(t);e&&this.dispatch(e)}}writeNodeSelectionToClipboard(e,t){const n=t.selection;if(!Z(n))return;const r=t.getBlock(n.nodeId);if(!r)return;if(!i(r))return this.schemaRegistry&&e.setData("text/html",kt({children:[r]},this.schemaRegistry)),void e.setData("text/plain",this.plainTextFromBlockTree(r));const s={type:r.type,...r.htmlId?{htmlId:r.htmlId}:{},...r.attrs?{attrs:{...r.attrs}}:{}};e.setData("application/x-notectl-block",JSON.stringify(s));const o=this.schemaRegistry?.getNodeSpec(r.type);o?.toHTML&&e.setData("text/html",yt(o.toHTML(r,""),r.htmlId));const a=r.attrs,l="string"==typeof a?.alt?a.alt:"";e.setData("text/plain",l)}plainTextFromBlockTree(e){return i(e)?B(e):a(e).map(e=>this.plainTextFromBlockTree(e)).join("\n")}writeTextSelectionToClipboard(e,t){const n=t.selection;if(Z(n))return;if(ce(n))return;if(Y(n))return;if(this.selectionRequiresDocumentSerializer(t))return void this.writeCompositeSelectionToClipboard(e,t);const r=t.getBlockOrder(),s=ie(n,r),i=r.indexOf(s.from.blockId),o=r.indexOf(s.to.blockId),a=[],l=[],c=[];for(let h=i;h<=o;h++){const e=r[h];if(!e)continue;const n=t.getBlock(e);if(!n)continue;const d=A(n),u=h===i?s.from.offset:0,p=h===o?s.to.offset:d,m=this.extractSegmentsForRange(n,u,p),f=this.plainTextFromSegments(m);a.push(f),c.push({block:n,start:u,end:p}),l.push({type:n.type,text:f,...0===u&&p===d&&n.htmlId?{htmlId:n.htmlId}:{},...n.attrs?{attrs:{...n.attrs}}:{},...m.length>0?{segments:m}:{}})}const d=a.join("\n");if(e.setData("text/plain",d),this.schemaRegistry){const n=gt(this.schemaRegistry),a=i!==o,d=l.some(e=>void 0!==e.htmlId||void 0!==e.type&&"paragraph"!==e.type);if(a||this.containsInlineSegments(l)||d){const t=this.serializeBlocksToClipboardHTML(c,n,l);e.setData("text/html",t)}else{const o=r[i],a=o?t.getBlock(o):void 0;if(a){const t=this.serializeBlockRangeToHTML(a,s.from.offset,s.to.offset,n);e.setData("text/html",t)}}}}selectionRequiresDocumentSerializer(e){const t=this.getTextSelection(e);if(!t||Y(t))return!1;const n=e.getBlockOrder(),r=ie(t,n),s=Q(e.doc,r.from.blockId),o=Q(e.doc,r.to.blockId);if(!s||!o)return!1;if(s[0]===o[0]){const t=e.doc.children.find(e=>e.id===s[0]);return!(!t||i(t))}const a=e.doc.children.findIndex(e=>e.id===s[0]),l=e.doc.children.findIndex(e=>e.id===o[0]);for(let c=a;c<=l;c++){const t=e.doc.children[c];if(t){if(!i(t))return!0;if((this.schemaRegistry?.getNodeSpec(t.type))?.isVoid)return!0}}return!1}getTextSelection(e){const t=e.selection;if(ee(t))return t}extractPlainTextForRange(e,t,n){return this.plainTextFromSegments(this.extractSegmentsForRange(e,t,n))}plainTextFromSegments(e){return e.map(e=>"inline"===e.kind?"":e.text).join("")}writeCompositeSelectionToClipboard(e,t){const n=this.getTextSelection(t);if(!n)return;const r=t.getBlockOrder(),s=ie(n,r),i=r.indexOf(s.from.blockId),o=r.indexOf(s.to.blockId),a=[];for(let l=i;l<=o;l++){const e=r[l];if(!e)continue;const n=t.getBlock(e);if(!n)continue;const c=l===i?s.from.offset:0,d=l===o?s.to.offset:A(n);a.push(this.extractPlainTextForRange(n,c,d))}if(e.setData("text/plain",a.join("\n")),this.schemaRegistry){const r=function(e,t,n){const r=e.getBlockOrder(),s=ie(t,r),i=r.indexOf(s.from.blockId),o=r.indexOf(s.to.blockId);if(-1===i||-1===o||i>o)return{children:[]};const a=e.getNodePath(s.from.blockId),l=e.getNodePath(s.to.blockId),c=a?.[0],d=l?.[0];if(!c||!d)return{children:[]};const h=e.doc.children.findIndex(e=>e.id===c),u=e.doc.children.findIndex(e=>e.id===d);if(-1===h||-1===u||h>u)return{children:[]};const p={firstBlockId:s.from.blockId,firstOffset:s.from.offset,lastBlockId:s.to.blockId,lastOffset:s.to.offset,selectedLeafIds:new Set(r.slice(i,o+1))},m=[];for(let f=h;f<=u;f++){const t=e.doc.children[f];if(!t)continue;const r=Br(t,p,n);r&&m.push(r)}return{children:m}}(t,n,this.schemaRegistry);if(r.children.length>0){const t=kt(r,this.schemaRegistry);e.setData("text/html",t)}}}serializeBlockRangeToHTML(e,t,n,r){const s=[];return _(e,t,n,{onText:(e,t)=>{this.schemaRegistry&&s.push(vt(e,t,this.schemaRegistry,r))},onInline:e=>{const t=this.schemaRegistry?.getInlineNodeSpec(e.inlineType);t?.toHTMLString&&s.push(t.toHTMLString(e))}}),s.join("")}extractSegmentsForRange(e,t,n){const r=[];return _(e,t,n,{onText:(e,t)=>{r.push({text:e,marks:t.map(e=>({type:e.type,...e.attrs?{attrs:{...e.attrs}}:{}}))})},onInline:e=>{r.push({kind:"inline",inlineType:e.inlineType,...Object.keys(e.attrs).length>0?{attrs:{...e.attrs}}:{}})}}),r}containsInlineSegments(e){return e.some(e=>e.segments?.some(e=>"inline"===e.kind))}serializeBlocksToClipboardHTML(e,t,n){const r=[];let s,i=[];const o=()=>{i.length>0&&s&&(r.push(`<${s}>${i.join("")}</${s}>`),i=[],s=void 0)};for(const l of e){const{block:e,start:n,end:a}=l,c=0===n&&a===A(e),{htmlId:d,...h}=e,u={...h,...c&&e.htmlId?{htmlId:e.htmlId}:{}},p=this.serializeBlockRangeToHTML(e,n,a,t),m=this.schemaRegistry?.getNodeSpec(u.type);if(m?.wrapper){const e=m.wrapper(u).tag;s!==e&&(o(),s=e),m.toHTML?i.push(yt(m.toHTML(u,p),u.htmlId)):i.push(yt(`<li>${p}</li>`,u.htmlId))}else o(),m?.toHTML?r.push(yt(m.toHTML(u,p),u.htmlId)):r.push(yt(`<p>${p}</p>`,u.htmlId))}o();const a=JSON.stringify(n).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/'/g,"'").replace(/"/g,""");return r.push(`<span data-notectl-rich="${a}" hidden></span>`),r.join("")}destroy(){this.element.removeEventListener("copy",this.handleCopy),this.element.removeEventListener("cut",this.handleCut)}},Nr=class{_composing=!1;_activeBlockId=null;get isComposing(){return this._composing}get activeBlockId(){return this._activeBlockId}start(e){this._composing=!0,this._activeBlockId=e}end(){this._composing=!1,this._activeBlockId=null}},Or=class e{failureReporter;static silent=new e;constructor(e=()=>{}){this.failureReporter=e}execute(e,t){try{return{ok:!0,value:t()}}catch(n){return this.reportFailure(e,n),{ok:!1}}}executeMaybeAsync(e,t){const n=this.execute(e,t);if(!n.ok)return n;try{return"object"!=typeof(r=n.value)&&"function"!=typeof r||null===r||!("then"in r)||"function"!=typeof r.then?{ok:!0,value:n.value}:Promise.resolve(n.value).then(e=>({ok:!0,value:e}),t=>(this.reportFailure(e,t),{ok:!1}))}catch(s){return this.reportFailure(e,s),{ok:!1}}var r}reportFailure(e,t){try{const n=this.failureReporter({...e,cause:t});null===n||"object"!=typeof n&&"function"!=typeof n||Promise.resolve(n).then(void 0,()=>{})}catch{}}},Dr=class{element;getState;dispatch;syncSelection;inputRuleRegistry;isReadOnly;shouldApplyInputRules;compositionTracker;getTextInputInterceptors;callbackExecutor;resolveTargetRange;compositionCommitHandled=!1;handleBeforeInput;handleCompositionStart;handleCompositionEnd;constructor(e,t){this.element=e,this.getState=t.getState,this.dispatch=t.dispatch,this.syncSelection=t.syncSelection,this.inputRuleRegistry=t.inputRuleRegistry,this.isReadOnly=t.isReadOnly??(()=>!1),this.shouldApplyInputRules=t.shouldApplyInputRules??(()=>!0),this.compositionTracker=t.compositionTracker??new Nr,this.getTextInputInterceptors=t.getTextInputInterceptors??(()=>[]),this.callbackExecutor=t.callbackExecutor??Or.silent,this.resolveTargetRange=t.resolveTargetRange,this.handleBeforeInput=this.onBeforeInput.bind(this),this.handleCompositionStart=this.onCompositionStart.bind(this),this.handleCompositionEnd=this.onCompositionEnd.bind(this),e.addEventListener("beforeinput",this.handleBeforeInput),e.addEventListener("compositionstart",this.handleCompositionStart),e.addEventListener("compositionend",this.handleCompositionEnd)}onBeforeInput(e){if(!_t(e,this.element))return;if(this.isReadOnly())return;if(this.compositionTracker.isComposing&&"insertCompositionText"===e.inputType)return;if(!function(e){switch(e){case"insertText":case"insertReplacementText":case"insertFromComposition":case"insertParagraph":case"insertLineBreak":case"deleteContentBackward":case"deleteContentForward":case"deleteWordBackward":case"deleteWordForward":case"deleteSoftLineBackward":case"deleteSoftLineForward":case"deleteByCut":case"insertFromPaste":case"insertFromDrop":case"formatBold":case"formatItalic":case"formatUnderline":case"historyUndo":case"historyRedo":return!0;default:return!1}}(e.inputType))return;const t="insertReplacementText"===e.inputType?function(e){if(e.data)return e.data;const t=e.dataTransfer?.getData("text/plain");return t||null}(e):null,n=t?function(e){return"function"==typeof e.getTargetRanges?e.getTargetRanges()[0]:void 0}(e):void 0,r=n&&this.resolveTargetRange?this.resolveTargetRange(n):null;"insertText"!==e.inputType&&"insertCompositionText"!==e.inputType&&"insertFromComposition"!==e.inputType&&this.syncSelection(),e.preventDefault();const s=this.getState();let i=null;switch(e.inputType){case"insertText":e.data&&(i=this.runTextInputInterceptors(e.data,s)??De(s,e.data,"input"));break;case"insertReplacementText":{if(!t)break;if(this.compositionTracker.isComposing)break;if(n&&!r&&(!ee(s.selection)||Y(s.selection)))break;const e=r?s.withSelection(r).withStoredMarks(null):s;i=this.runTextInputInterceptors(t,e)??De(e,t,"input");break}case"insertFromComposition":e.data&&(this.compositionCommitHandled=!0,i=this.runTextInputInterceptors(e.data,s)??De(s,e.data,"input"));break;case"insertParagraph":i=Oe(s);break;case"insertLineBreak":i=Fe(s);break;case"deleteContentBackward":i=pn(s);break;case"deleteContentForward":i=mn(s);break;case"deleteWordBackward":i=function(e){return un(e,{merge:Ne,range:(e,t)=>t>0?[Je(e,t),t]:null})}(s);break;case"deleteWordForward":i=function(e){return un(e,{merge:ze,range:(e,t)=>t<A(e)?[t,Xe(e,t)]:null})}(s);break;case"deleteSoftLineBackward":i=function(e){return un(e,{merge:Ne,range:(e,t)=>t>0?[0,t]:null})}(s);break;case"deleteSoftLineForward":i=function(e){return un(e,{merge:ze,range:(e,t)=>{const n=A(e);return t<n?[t,n]:null}})}(s)}i&&(this.dispatch(i),"insertText"!==e.inputType&&"insertReplacementText"!==e.inputType||this.checkInputRules())}onCompositionStart(e){if(!_t(e,this.element))return;const t=this.getState();ee(t.selection)&&(this.compositionCommitHandled=!1,this.compositionTracker.start(t.selection.anchor.blockId))}onCompositionEnd(e){if(!_t(e,this.element))return;if(this.compositionTracker.end(),this.isReadOnly())return;if(this.compositionCommitHandled)return void(this.compositionCommitHandled=!1);const t=e.data;if(!t)return;const n=this.getState(),r=De(n,t,"input");this.dispatch(r)}runTextInputInterceptors(e,t){const n=this.getTextInputInterceptors();if(0===n.length)return null;for(const r of n){const n=this.callbackExecutor.execute({pluginId:r.pluginId,name:r.name,kind:"text-input-interceptor"},()=>r.interceptor(e,t));if(n.ok&&n.value)return n.value}return null}checkInputRules(){if(!this.shouldApplyInputRules())return;if(!this.inputRuleRegistry)return;const e=this.inputRuleRegistry.getInputRuleEntries();if(0===e.length)return;const t=this.getState();if(!ee(t.selection))return;const{anchor:n}=t.selection,r=t.getBlock(n.blockId);if(!r)return;const s=function(e){let t="";for(const n of f(e))t+=v(n)?n.text:"";return t}(r).slice(0,n.offset);for(const i of e){const e=this.callbackExecutor.execute({pluginId:i.pluginId,name:i.name,kind:"input-rule"},()=>{const e=i.rule.pattern.exec(s);if(!e)return null;const n=e.index,r=n+e[0].length;return i.rule.handler(t,e,n,r)});if(e.ok&&e.value)return void this.dispatch(e.value)}}destroy(){this.element.removeEventListener("beforeinput",this.handleBeforeInput),this.element.removeEventListener("compositionstart",this.handleCompositionStart),this.element.removeEventListener("compositionend",this.handleCompositionEnd)}},Lr={Period:".",Comma:",",Slash:"/",Semicolon:";",Quote:"'",BracketLeft:"[",BracketRight:"]",Backslash:"\\",Minus:"-",Equal:"=",Backquote:"`"},Hr={1:"!",2:"@",3:"#",4:"$",5:"%",6:"^",7:"&",8:"*",9:"(",0:")","`":"~","-":"_","=":"+","[":"{","]":"}","\\":"|",";":":","'":'"',",":"<",".":">","/":"?"},zr=function(){const e=/* @__PURE__ */new Map;for(let t=0;t<26;t++){const n=String.fromCharCode(65+t);e.set(`Key${n}`,n)}for(let t=0;t<=9;t++)e.set(`Digit${t}`,String(t)),e.set(`Numpad${t}`,String(t));for(const[t,n]of Object.entries(Lr))e.set(t,n);return e}();function Fr(e){const t=[];return(e.metaKey||e.ctrlKey)&&t.push("Mod"),e.shiftKey&&t.push("Shift"),e.altKey&&t.push("Alt"),t}function jr(e){const t=Fr(e);let n=e.key;return" "===n?n="Space":1===n.length&&(n=n.toUpperCase()),t.push(n),t.join("-")}function $r(e){return e.ctrlKey||e.metaKey?e.ctrlKey&&e.altKey&&!e.metaKey?null:zr.get(e.code)??null:null}var _r={ArrowLeft:"left",ArrowRight:"right",ArrowUp:"up",ArrowDown:"down"},Kr=class{element;getState;dispatch;undo;redo;keymapRegistry;isReadOnly;compositionTracker;getTextDirectionFn;navigateFromGapCursorFn;callbackExecutor;handleKeydown;constructor(e,t){this.element=e,this.getState=t.getState,this.dispatch=t.dispatch,this.undo=t.undo,this.redo=t.redo,this.keymapRegistry=t.keymapRegistry,this.isReadOnly=t.isReadOnly??(()=>!1),this.compositionTracker=t.compositionTracker,this.getTextDirectionFn=t.getTextDirection??(()=>"ltr"),this.navigateFromGapCursorFn=t.navigateFromGapCursor,this.callbackExecutor=t.callbackExecutor??Or.silent,this.handleKeydown=this.onKeydown.bind(this),e.addEventListener("keydown",this.handleKeydown)}onKeydown(e){if(!_t(e,this.element))return;if(this.compositionTracker?.isComposing)return;if(this.handleNodeSelectionKeys(e))return;if(this.handleGapCursorKeys(e))return;if(this.isReadOnly()){if(this.keymapRegistry){const t=this.keymapRegistry.getKeymapEntriesByPriority();if(this.dispatchKeymaps(e,[t.navigation]))return}return void this.handleEscape(e)}if(this.keymapRegistry){const t=this.keymapRegistry.getKeymapEntriesByPriority();if(this.dispatchKeymaps(e,[t.context,t.navigation,t.default]))return}if(this.handleGapCursorArrowFallback(e))return;if(this.handleTab(e))return;if(this.handleEscape(e))return;if(!e.metaKey&&!e.ctrlKey)return;let t=this.resolveBuiltinShortcut(e.key.toLowerCase(),e.shiftKey);if(null===t){const n=$r(e);null!==n&&(t=this.resolveBuiltinShortcut(n.toLowerCase(),e.shiftKey))}if(null===t)return;if(e.preventDefault(),"undo"===t)return void this.undo();if("redo"===t)return void this.redo();const n=je(this.getState());n&&this.dispatch(n)}resolveBuiltinShortcut(e,t){return"z"!==e||t?"z"===e&&t||"y"===e&&!t?"redo":"a"!==e||t?null:"selectAll":"undo"}dispatchKeymaps(e,t){if(this.runDescriptor(e,t,jr(e)))return!0;for(const n of function(e){const t=$r(e);if(null===t)return[];const n=Fr(e),r=[[...n,t].join("-")];if(e.shiftKey){const e=Hr[t];void 0!==e&&r.push([...n,e].join("-"))}return r}(e))if(this.runDescriptor(e,t,n))return!0;return!1}runDescriptor(e,t,n){for(const r of t)for(let t=r.length-1;t>=0;t--){const s=r[t],i=s?.keymap[n];if(!s||!i)continue;const o=this.callbackExecutor.execute({pluginId:s.pluginId,name:`${s.name} (${n})`,kind:"keymap"},i);if(o.ok&&!0===o.value)return e.preventDefault(),!0}return!1}handleNodeSelectionKeys(e){const t=this.getState(),n=t.selection;if(!Z(n))return!1;const r=e.key;if(!("ArrowLeft"!==r&&"ArrowUp"!==r&&"ArrowRight"!==r&&"ArrowDown"!==r||e.shiftKey||e.metaKey||e.ctrlKey||e.altKey)){const s=_r[r];if(!s)return!1;const i=this.isSelectedBlockRtl(n.nodeId),o=Be(t,s,i);return!!o&&(e.preventDefault(),this.dispatch(o),!0)}if("Backspace"===r||"Delete"===r){if(this.isReadOnly())return e.preventDefault(),!0;e.preventDefault();const r=Ae(t,n);return r&&this.dispatch(r),!0}if("Enter"===r){if(this.isReadOnly())return e.preventDefault(),!0;e.preventDefault();const n=Oe(t);return n&&this.dispatch(n),!0}if("Escape"===r){e.preventDefault();const n=Be(t,"right");return n&&this.dispatch(n),!0}return!1}handleGapCursorKeys(e){const t=this.getState(),n=t.selection;if(!ce(n))return!1;const r=e.key;if("ArrowLeft"===r||"ArrowRight"===r||"ArrowUp"===r||"ArrowDown"===r)return!1;if("Escape"===r||"Tab"===r)return!1;if(e.ctrlKey||e.metaKey||e.altKey)return!1;if("Enter"===r){if(this.isReadOnly())return e.preventDefault(),!0;e.preventDefault();const n=Oe(t);return n&&this.dispatch(n),!0}if("Backspace"===r){if(this.isReadOnly())return e.preventDefault(),!0;e.preventDefault();const r=Le(t,n);return r&&this.dispatch(r),!0}if("Delete"===r){if(this.isReadOnly())return e.preventDefault(),!0;e.preventDefault();const r=_e(t,n);return r&&this.dispatch(r),!0}if(1===r.length){if(this.isReadOnly())return e.preventDefault(),!0;e.preventDefault();const n=De(t,r);return this.dispatch(n),!0}return!1}handleGapCursorArrowFallback(e){const t=this.getState(),n=t.selection;if(!ce(n))return!1;const r=e.key;if("ArrowLeft"!==r&&"ArrowRight"!==r&&"ArrowUp"!==r&&"ArrowDown"!==r)return!1;const s=_r[r];if(!s)return!1;if(!this.navigateFromGapCursorFn)return!1;const i=this.navigateFromGapCursorFn(t,s,this.element);return!(!i||ne(i.selectionAfter,n)||(e.preventDefault(),this.dispatch(i),0))}handleTab(e){if("Tab"!==e.key)return!1;if(e.metaKey||e.ctrlKey||e.altKey)return!1;if(e.preventDefault(),e.shiftKey)return!0;const t=this.getState(),n=De(t,"\t");return this.dispatch(n),!0}handleEscape(e){return"Escape"===e.key&&(this.element.blur(),!0)}isSelectedBlockRtl(e){const t=this.element.querySelector(`[data-block-id="${e}"]`);return t instanceof HTMLElement&&"rtl"===this.getTextDirectionFn(t)}destroy(){this.element.removeEventListener("keydown",this.handleKeydown)}};function Vr(e){const t=e.executor??Or.silent,n=e.isActive??(()=>!0),r=[...e.files],s=r.map(t=>e.registry.matchFileHandlerEntries(t.type)),i=(o,a,l)=>{let c=o,d=a,h=l;for(;c<r.length;){if(!n())return{handled:h,cancelled:!0};const o=r[c];if(!o){c++,d=0;continue}const a=(s[c]??[])[d];if(!a){c++,d=0;continue}const l=t.executeMaybeAsync({pluginId:a.pluginId,name:a.name,kind:"file-handler"},()=>a.handler(o,e.getPosition()));if(l instanceof Promise)return l.then(e=>Ur(e,c,d,h,i));l.ok&&!0===l.value?(h=!0,c++,d=0):d++}return n()?{handled:h,cancelled:!1}:{handled:h,cancelled:!0}};return i(0,0,!1)}function Ur(e,t,n,r,s){return e.ok&&!0===e.value?s(t+1,0,!0):s(t,n+1,r)}function qr(e,t){return t.isEmpty?e:Z(e)?function(e,t){const n={blockId:e.nodeId,offset:0},r=t.mapResult(n,-1);return r.deleted||r.pos.blockId!==e.nodeId?null:te(e.nodeId,e.path)}(e,t):ce(e)?function(e,t){const n={blockId:e.blockId,offset:0},r=t.mapResult(n,-1);return r.deleted||r.pos.blockId!==e.blockId?null:oe(e.blockId,e.side,e.path)}(e,t):Wr(e,t)}function Wr(e,t){if(Y(e)){const n=t.map(e.anchor,-1);return n===e.anchor?e:re(n.blockId,n.offset)}const n=t.map(e.anchor,-1),r=t.map(e.head,1);return n===e.anchor&&r===e.head?e:se(n,r)}var Gr=/(^|\n) {0,3}(```|~~~)/,Qr=/(^|\n)\s*\|?[ :|]*-{3,}[ :|-]*(\n|$)/,Jr=/(^|\n) {0,3}(#{1,6} |[-*+] |\d{1,9}[.)] |> )/g;function Xr(e,t){if(0===t.blocks.length)return e.transaction("paste").setSelection(e.selection).build();const n=t.blocks[0];return n?1===t.blocks.length&&n.type===de("paragraph")?function(e,t){const n=e.selection;if(Z(n))return e.transaction("paste").setSelection(n).build();if(ce(n))return function(e,t,n){const r=es(e,t);if(!r)return e.transaction("paste").setSelection(t).build();const s=l(),i=e.transaction("paste");i.insertNode(r.parentPath,r.insertIndex,L(de("paragraph"),[I("")],s));const o=Zr(i,s,0,n);return i.setSelection(re(s,o)),i.build()}(e,n,t);const{builder:r,insertBlockId:s,insertOffset:i}=Yr(e,n),o=Zr(r,s,i,t);return r.setSelection(re(s,o)),r.build()}(e,n.segments):1===t.blocks.length?function(e,t){const n=e.selection;if(Z(n))return e.transaction("paste").setSelection(n).build();if(ce(n))return ts(e,n,[t]);const{builder:r,insertBlockId:s,insertOffset:i}=Yr(e,n);r.setBlockType(s,t.type,t.attrs);const o=Zr(r,s,i,t.segments);return r.setSelection(re(s,o)),r.build()}(e,n):function(e,t){const n=e.selection;if(Z(n))return e.transaction("paste").setSelection(n).build();if(ce(n))return ts(e,n,t.blocks);const{builder:r,landingId:s,resolved:i,insertBlockId:o,insertOffset:a}=Yr(e,n),c=e.getBlockOrder();let d;if(s){const t=Q(e.doc,i.blockId)?.[0];d=t?e.doc.children.findIndex(e=>e.id===t):0}else d=c.indexOf(o);const u=t.blocks[0],p=t.blocks[t.blocks.length-1];if(!u||!p)return r.build();const m=t.blocks.slice(1,-1),f=Zr(r,o,a,u.segments),g=l();r.splitBlock(o,f,g),u.type!==de("paragraph")&&r.setBlockType(o,u.type,u.attrs);let y=d+1;for(const k of m){const e=L(k.type,h(k.segments),l(),k.attrs);r.insertNode([],y,e),y++}return Zr(r,g,0,p.segments),p.type!==de("paragraph")&&r.setBlockType(g,p.type,p.attrs),r.setSelection(re(g,Mn(p.segments))),r.build()}(e,t):e.transaction("paste").setSelection(e.selection).build()}function Yr(e,t){const n=e.transaction("paste");let r;Y(t)||(r=$e(e,n));const s=Pe(t,e.getBlockOrder());return{builder:n,landingId:r,resolved:s,insertBlockId:r??s.blockId,insertOffset:r?0:s.offset}}function Zr(e,t,n,r){let s=n,i=[];const o=()=>{if(0===i.length)return;const n=i.map(e=>"text"===e.kind?e.text:"").join("");n.length>0&&(e.insertText(t,s,n,[],i),s+=n.length),i=[]};for(const a of r)"inline"===a.kind?(o(),e.insertInlineNode(t,s,a.node),s+=1):i.push(a);return o(),s}function es(e,t){const n=Q(e.doc,t.blockId);if(!n)return null;const r=Ee(n),s=me(e,r),i=fe(s,t.blockId);return i<0?null:{parentPath:r,insertIndex:"before"===t.side?i:i+1}}function ts(e,t,n){const r=es(e,t);if(!r)return e.transaction("paste").setSelection(t).build();const s=e.transaction("paste");let i,o=r.insertIndex,a=0;for(const c of n){const e=l(),t=L(c.type,h(c.segments),e,c.attrs);s.insertNode(r.parentPath,o,t),o++,i=e,a=Mn(c.segments)}return i&&s.setSelection(re(i,a)),s.build()}var ns=/* @__PURE__ */new Set(["P","DIV","H1","H2","H3","H4","H5","H6","BLOCKQUOTE","UL","OL","LI","HR","PRE","TABLE","THEAD","TBODY","TR"]),rs=/* @__PURE__ */new Set(["STRONG","B","EM","I","U","S","STRIKE","DEL","A","SPAN","BR","SUB","SUP","CODE"]),ss=/^H([1-6])$/;function is(e){const t=e.style.fontWeight,n=Number.parseInt(t,10);return!("normal"===t||!Number.isNaN(n)&&n<700)&&{}}var os=/* @__PURE__ */new Map([["STRONG",{markName:"bold",getAttrs:is}],["B",{markName:"bold",getAttrs:is}],["EM",{markName:"italic"}],["I",{markName:"italic"}],["U",{markName:"underline"}],["S",{markName:"strikethrough"}],["STRIKE",{markName:"strikethrough"}],["DEL",{markName:"strikethrough"}],["A",{markName:"link",getAttrs:function(e){return{href:n(e.getAttribute("href")??"")}}}]]),as=class{schema;blockParseRules;markParseRules;inlineParseRules;blockTagHandlers;constructor(e){this.schema=e.schema,this.blockParseRules=e.schemaRegistry?.getBlockParseRules()??[],this.markParseRules=e.schemaRegistry?.getMarkParseRules()??[],this.inlineParseRules=e.schemaRegistry?.getInlineParseRules()??[],this.blockTagHandlers=this.buildBlockTagHandlers()}parse(e){St(e);const t=this.parseContainer(e);return 0===t.length?{blocks:[{type:this.resolveBlockType(de("paragraph")),segments:[H("")]}]}:{blocks:t}}buildBlockTagHandlers(){const e=e=>this.parseBlockWithLineBreaks(e,this.resolveBlockType(de("paragraph"))),t=e=>this.parseTableAsParagraphs(e);/* @__PURE__ */
|
|
2
|
-
return new Map([["P",e],["DIV",e],["BLOCKQUOTE",e=>this.parseBlockquote(e)],["UL",e=>this.parseList(e,"bullet",0)],["OL",e=>this.parseList(e,"ordered",0)],["LI",e=>this.parseListItem(e,"bullet",0)],["HR",()=>[{type:this.resolveBlockType(de("horizontal_rule")),segments:[]}]],["PRE",e=>[{type:this.resolveBlockType(de("paragraph")),segments:this.ensureSegments(this.parsePreContent(e))}]],["TABLE",t],["THEAD",t],["TBODY",t],["TR",t]])}parseContainer(e){const t=[];let n=[];for(const r of Array.from(e.childNodes))if(r.nodeType===Node.ELEMENT_NODE){const e=r;this.isBlockElement(e)?(this.flushPendingSegments(t,n),n=[],t.push(...this.parseBlockElement(e))):e.children.length>0&&this.containsBlockDescendants(e)?(this.flushPendingSegments(t,n),n=[],t.push(...this.parseContainerWithMarks(e,this.marksFromElement(e)))):n.push(...this.parseInlineNode(r,[]))}else if(r.nodeType===Node.TEXT_NODE){const e=r.textContent??"";e&&n.push(H(e))}return this.flushPendingSegments(t,n),t}parseBlockElement(e){const t=ss.exec(e.tagName);if(t)return this.parseHeading(e,Number(t[1]));const n=this.blockTagHandlers.get(e.tagName);return n?n(e):this.parseUnknownBlock(e)}parseHeading(e,t){const n=this.resolveBlockType(de("heading"));return[{type:n,...n===de("heading")?{attrs:{level:t}}:{},segments:this.ensureSegments(this.parseInlineChildren(e,[]))}]}parseUnknownBlock(e){const t=this.matchBlockRule(e);return t?[{type:t.type,...t.attrs?{attrs:t.attrs}:{},segments:this.ensureSegments(this.parseInlineChildren(e,[]))}]:[{type:this.resolveBlockType(de("paragraph")),segments:this.ensureSegments(this.parseInlineChildren(e,[]))}]}parseBlockquote(e){const t=this.resolveBlockType(de("blockquote"));return Array.from(e.childNodes).some(e=>e.nodeType===Node.ELEMENT_NODE&&this.isBlockElement(e))?this.parseContainer(e).map(e=>({type:t,segments:e.segments})):[{type:t,segments:this.ensureSegments(this.parseInlineChildren(e,[]))}]}parseList(e,t,n){const r=[];for(const s of Array.from(e.children)){const e=s;"LI"===e.tagName?r.push(...this.parseListItem(e,t,n)):"UL"===e.tagName?r.push(...this.parseList(e,"bullet",n+1)):"OL"===e.tagName&&r.push(...this.parseList(e,"ordered",n+1))}return r}parseListItem(e,t,n){const r=[],s=this.resolveBlockType(de("list_item")),i=this.hasCheckbox(e),o=i?"checklist":t,a=!!i&&this.isCheckboxChecked(e),l=[],c=[];for(const d of Array.from(e.childNodes))if(d.nodeType===Node.ELEMENT_NODE){const e=d;"UL"===e.tagName||"OL"===e.tagName?c.push(e):"INPUT"===e.tagName&&"checkbox"===e.getAttribute("type")||(this.isBlockElement(e)?l.push(...this.parseInlineChildren(e,[])):l.push(...this.parseInlineNode(d,[])))}else if(d.nodeType===Node.TEXT_NODE){const e=d.textContent??"";e&&l.push(H(e))}r.push({type:s,attrs:{listType:o,indent:n,..."checklist"===o?{checked:a}:{}},segments:this.ensureSegments(this.normalizeSegments(l))});for(const d of c){const e="OL"===d.tagName?"ordered":"bullet";r.push(...this.parseList(d,e,n+1))}return r}parseInlineChildren(e,t){const n=[];for(const r of Array.from(e.childNodes))n.push(...this.parseInlineNode(r,t));return this.normalizeSegments(n)}parseInlineNode(e,t){if(e.nodeType===Node.TEXT_NODE){const n=e.textContent??"";return n?[H(n,this.resolveMarks(t))]:[]}if(e.nodeType!==Node.ELEMENT_NODE)return[];const n=e,r=n.tagName;if("BR"===r)return[H("\n",this.resolveMarks(t))];const s=this.matchInlineNodeRule(n);if(s)return[u(s)];if(this.isBlockElement(n)&&!rs.has(r))return this.parseInlineChildren(n,t);const i=this.mergeMarks(t,this.marksFromElement(n));return this.parseInlineChildren(n,i)}matchInlineNodeRule(e){if(0===this.inlineParseRules.length)return null;const t=e.tagName.toLowerCase();for(const n of this.inlineParseRules)if(n.rule.tag===t){if(n.rule.getAttrs){const t=n.rule.getAttrs(e);if(!1===t)continue;return P(ue(n.type),t)}return P(ue(n.type))}return null}parsePreContent(e){const t=e.textContent??"";return t?[H(t)]:[]}parseTableAsParagraphs(e){const t=[],n=e.querySelectorAll("td, th");for(const r of Array.from(n)){const e=this.parseInlineChildren(r,[]);e.some(e=>"inline"===e.kind||e.text.length>0)&&t.push({type:this.resolveBlockType(de("paragraph")),segments:this.ensureSegments(e)})}return t}marksFromElement(e){return this.matchMarkRules(e)||this.fallbackMarksFromElement(e)}matchMarkRules(e){if(0===this.markParseRules.length)return null;const t=e.tagName.toLowerCase(),n=[],r=/* @__PURE__ */new Set;for(const s of this.markParseRules)if(s.rule.tag===t&&!r.has(s.type)){if(s.rule.getAttrs){const t=s.rule.getAttrs(e);if(!1===t)continue;n.push({type:he(s.type),...Object.keys(t).length>0?{attrs:t}:{}})}else n.push({type:he(s.type)});r.add(s.type)}return r.size>0?n:null}fallbackMarksFromElement(e){const t=os.get(e.tagName);if(!t)return[];if(t.getAttrs){const n=t.getAttrs(e);return!1===n?[]:Object.keys(n).length>0?[{type:he(t.markName),attrs:n}]:[{type:he(t.markName)}]}return[{type:he(t.markName)}]}mergeMarks(e,t){const n=[...e];for(const r of t)n.some(e=>e.type===r.type)||n.push(r);return n}resolveMarks(e){return e.filter(e=>qe(this.schema,e.type))}resolveBlockType(e){return Ke(this.schema,e)?e:de("paragraph")}normalizeSegments(e){if(0===e.length)return[];const t=[];for(const n of e){if("inline"===n.kind){t.push(n);continue}const e=t[t.length-1];e&&"text"===e.kind&&d(e.marks,n.marks)?t[t.length-1]=H(e.text+n.text,e.marks):n.text.length>0&&t.push(n)}return t}ensureSegments(e){return 0===e.length?[H("")]:e}matchBlockRule(e){const t=e.tagName.toLowerCase();for(const n of this.blockParseRules)if(n.rule.tag===t){if(n.rule.getAttrs){const t=n.rule.getAttrs(e);if(!1===t)continue;return{type:de(n.type),attrs:t}}return{type:de(n.type)}}return null}isBlockElement(e){if(ns.has(e.tagName))return!0;const t=e.tagName.toLowerCase();return this.blockParseRules.some(e=>e.rule.tag===t)}hasCheckbox(e){return null!==e.querySelector('input[type="checkbox"]')}isCheckboxChecked(e){return e.querySelector('input[type="checkbox"]')?.hasAttribute("checked")??!1}containsBlockDescendants(e){for(const t of Array.from(e.children)){if(this.isBlockElement(t))return!0;if(this.containsBlockDescendants(t))return!0}return!1}parseContainerWithMarks(e,t){const n=this.parseContainer(e);return 0===t.length?n:n.map(e=>({...e,segments:this.prependMarks(e.segments,t)}))}prependMarks(e,t){return e.map(e=>"inline"===e.kind?e:H(e.text,this.mergeMarks(t,e.marks)))}parseBlockWithLineBreaks(e,t){const n=this.parseInlineChildren(e,[]);if(!n.some(e=>"text"===e.kind&&e.text.includes("\n")))return[{type:t,segments:this.ensureSegments(n)}];const r=[];let s=[];for(const i of n){if("inline"===i.kind){s.push(i);continue}const e=i.text.split("\n");for(let n=0;n<e.length;n++){n>0&&(r.push({type:t,segments:this.ensureSegments(this.normalizeSegments(s))}),s=[]);const o=e[n]??"";o&&s.push(H(o,i.marks))}}return r.push({type:t,segments:this.ensureSegments(this.normalizeSegments(s))}),r}flushPendingSegments(e,t){const n=this.normalizeSegments(t);0!==n.length&&(n.every(e=>"text"===e.kind&&""===e.text.trim())||e.push({type:this.resolveBlockType(de("paragraph")),segments:n}))}},ls={1:"x-small",2:"small",3:"medium",4:"large",5:"x-large",6:"xx-large",7:"xxx-large"};function cs(e){return e.toLowerCase().includes("font-size")}function ds(e,t){for(;e.firstChild;)t.appendChild(e.firstChild)}function hs(e){const t=e.parentNode;if(t){for(;e.firstChild;)t.insertBefore(e.firstChild,e);t.removeChild(e)}}var us=["script","style","iframe","object","embed","form","noscript"],ps=/* @__PURE__ */new Set(["p","div","h1","h2","h3","h4","h5","h6","li","blockquote","table","tr","td","th","pre","figure","hr"]),ms=class{getState;dispatch;schemaRegistry;tryRichPasteFromJson;constructor(e,t,n,r){this.getState=e,this.dispatch=t,this.schemaRegistry=n,this.tryRichPasteFromJson=r}handleHTMLOrTextPaste(e,t,n){const r=this.stateAtSelection(n),s=e.getData("text/html");s?this.handleHTML(s,r):t&&this.pastePlainText(t,n)}pastePlainText(e,t){if(!e)return;const n=function(e){return{blocks:e.split(/\r?\n/).map(e=>({type:de("paragraph"),segments:[H(e)]}))}}(e);this.dispatch(Xr(this.stateAtSelection(t),n))}pasteHTMLString(e,t){return this.handleHTML(e,this.stateAtSelection(t))}handleHTML(e,t){const n=bt(e,{FORBID_TAGS:us,ADD_TAGS:this.schemaRegistry?this.schemaRegistry.getAllowedTags():[],ADD_ATTR:this.schemaRegistry?this.schemaRegistry.getAllowedAttrs():[],ALLOWED_URI_REGEXP:r,...It()},this.schemaRegistry),s=this.extractRichData(n);if(s&&this.tryRichPasteFromJson(s,t))return!0;const i=document.createElement("template");i.innerHTML=n,function(e){const t=Array.from(e.querySelectorAll("font"));for(const n of t){const e=n.getAttribute("color"),t=n.getAttribute("face"),r=n.getAttribute("size"),s=n.getAttribute("style")??"";if(!(null!==e||null!==t||null!==r||s.length>0)){hs(n);continue}const i=document.createElement("span"),o=[];if(s&&o.push(s.endsWith(";")?s:`${s};`),e&&o.push(`color: ${e};`),t&&o.push(`font-family: ${t};`),r&&!cs(s)){const e=ls[r];e&&o.push(`font-size: ${e};`)}Ut(i,o.join(" ")),ds(n,i),n.parentNode?.replaceChild(i,n)}}(i.content);const o=i.innerHTML,a=this.schemaRegistry?this.schemaRegistry.getAllowedTags():["strong","em","u","b","i","p","br","div","span"],l=this.schemaRegistry?this.schemaRegistry.getAllowedAttrs():[],c=bt(o,{ALLOWED_TAGS:a,ALLOWED_ATTR:l,ALLOWED_URI_REGEXP:r,...It()},this.schemaRegistry);if(this.schemaRegistry){const e=document.createElement("template");if(e.innerHTML=c,this.requiresDocumentParser(c,e.content))return this.handleDocumentPaste(c,t);const n=Ve(this.schemaRegistry),r=new as({schema:n,schemaRegistry:this.schemaRegistry}),s=null!==e.content.querySelector("br"),i=r.parse(e.content);return!(!function(e){return e.blocks.some(e=>e.type!==de("paragraph")||e.segments.some(Tn))}(i)&&!s||(this.dispatch(Xr(t,i)),0))}const d=this.extractTextFromHTML(c);return!!Pn(d)&&(this.dispatch(De(t,d,"paste")),!0)}extractRichData(e){const t=document.createElement("template");t.innerHTML=e;const n=t.content.querySelector("[data-notectl-rich]")?.getAttribute("data-notectl-rich");if(n)return this.decodeHTMLEntities(n)}decodeHTMLEntities(e){return e.replace(/"/g,'"').replace(/'/g,"'").replace(/>/g,">").replace(/</g,"<").replace(/&/g,"&")}requiresDocumentParser(e,t){return!!this.containsModelledBlockID(t)||!!/<table[\s>]/i.test(e)||!!/<blockquote[\s>]/i.test(e)||!(!/<li[\s>]/i.test(e)||!this.containsMultiBlockListItem(t))||this.containsVoidBlockElements(t)}containsModelledBlockID(e){const t=new Set(this.schemaRegistry?.getBlockParseRules().map(e=>e.rule.tag)??[]);for(const n of Array.from(e.querySelectorAll("[id]"))){const e=n.tagName.toLowerCase();if(ps.has(e)||t.has(e))return!0}return!1}containsMultiBlockListItem(e){const t=/* @__PURE__ */new Set(["PRE","BLOCKQUOTE","TABLE","HR","H1","H2","H3","H4","H5","H6"]);for(const n of Array.from(e.querySelectorAll("li"))){let e=0,r=!1;for(const s of Array.from(n.childNodes))if(s.nodeType===Node.ELEMENT_NODE){const n=s.tagName;if("UL"===n||"OL"===n||"INPUT"===n||"LI"===n)continue;if(t.has(n))return!0;if("P"===n||"DIV"===n){e++;continue}r=!0}else s.nodeType===Node.TEXT_NODE&&""!==(s.textContent??"").trim()&&(r=!0);if(e>=2||e>=1&&r)return!0}return!1}containsVoidBlockElements(e){if(!this.schemaRegistry)return!1;const t=this.schemaRegistry.getBlockParseRules();for(const n of t){if(!this.schemaRegistry.getNodeSpec(n.type)?.isVoid)continue;const t=e.querySelectorAll(n.rule.tag);for(const e of Array.from(t)){if(!n.rule.getAttrs)return!0;if(!1!==n.rule.getAttrs(e))return!0}}return!1}handleDocumentPaste(e,t){if(!this.schemaRegistry)return!1;const n=fn(xt(e,this.schemaRegistry),this.schemaRegistry);if(0===n.children.length)return!1;const r=t.selection,s=t.transaction("paste");let i;ee(r)&&!Y(r)&&(i=$e(t,s));const o=i??(Z(r)?r.nodeId:ce(r)?r.blockId:r.anchor.blockId),a=xe(t,o,this.schemaRegistry);if(!a)return!1;const c=a.parentPath[a.parentPath.length-1],d=c?t.getBlock(c)?.type:void 0,h=Me(this.schemaRegistry,d,n.children)?a:ke(t,o);if(!h)return!1;const u=ce(r)&&"before"===r.side?0:1;let p,m,f=h.anchorIndex+u;for(const g of n.children){const e=l(),t=Se(g,e);s.insertNode(h.parentPath,f,t),f++,p=Te(t),m=t}if(h.isAnchorEmpty&&!ce(r)&&s.removeNode(h.parentPath,h.anchorIndex),p&&m){const e=be(m,p),t=e?B(e).length:0;s.setSelection(re(p,t))}return this.dispatch(s.build()),!0}extractTextFromHTML(e){const t=document.createElement("template");return t.innerHTML=e,t.content.textContent??""}stateAtSelection(e){const t=this.getState();return e?t.withSelection(e):t}},fs=class{getState;dispatch;schemaRegistry;constructor(e,t,n){this.getState=e,this.dispatch=t,this.schemaRegistry=n}handleBlockPaste(e){let n;try{n=JSON.parse(e)}catch{return}const r=n.type;if(!r)return;const s=this.schemaRegistry?.getNodeSpec(r);if(this.schemaRegistry&&!s)return;const i=this.getState(),o=i.selection,a=Ce(o),c=l(),d=ve(n.attrs,s?.attrs),h=L(de(r),void 0,c,d,t(n.htmlId)),u=ge(i,a);if(u){const e=i.getBlock(u);if(this.cellRejects(e,[h])){const e=ke(i,a);if(!e)return;return void this.dispatchNodeInsert(i,e.parentPath,e.anchorIndex+1,h)}const t=ye(i,a,u,this.schemaRegistry);if(!t||!e)return;return void this.dispatchNodeInsert(i,t.parentPath,e.children.length,h)}const p=xe(i,a,this.schemaRegistry);if(!p)return;const m=ce(o)&&"before"===o.side?0:1;this.dispatchNodeInsert(i,p.parentPath,p.anchorIndex+m,h)}dispatchNodeInsert(e,t,n,r){const s=e.transaction("paste");s.insertNode(t,n,r),s.setSelection(te(r.id,[...t,r.id])),this.dispatch(s.build())}cellRejects(e,t){return!(!e||!this.schemaRegistry||Me(this.schemaRegistry,e.type,t))}handleRichPasteFromJson(e,t){let n;try{n=JSON.parse(e)}catch{return!1}return!(!Array.isArray(n)||0===n.length)&&this.handleRichPaste(n,t)}handleRichPaste(e,n){if(0===e.length)return!1;const r=[];for(const t of e){const e=we(t,this.schemaRegistry);e&&r.push(e)}if(0===r.length)return!1;if(!r.some(e=>void 0!==e.htmlId||void 0!==e.type&&"paragraph"!==e.type||e.segments?.some(e=>"inline"===e.kind))&&r.length<=1)return!1;let s=n??this.getState();const i=s.selection,o=Ce(i),a=s.getBlock(o),l=s.doc.children.some(e=>e.id===o);if(!r.some(e=>t(e.htmlId))&&ee(i)&&Y(i)&&l&&void 0!==a&&A(a)>0)return this.dispatch(Xr(s,Ie(r))),!0;if(ee(i)&&!Y(i)){const e=s.transaction("paste"),t=$e(s,e),n=e.build();if(this.dispatch(n),s=s.apply(n),t)return this.resolveAndInsertRichBlocks(r,s,t)}return this.resolveAndInsertRichBlocks(r,s,o)}resolveAndInsertRichBlocks(e,t,n){const r=e.map(Re),s=t.selection,i=ge(t,n);if(i){const e=t.getBlock(i);if(this.cellRejects(e,r)){const e=ke(t,n);return!!e&&this.insertNodes(r,t,e,e.anchorIndex+1,!1)}const s=ye(t,n,i,this.schemaRegistry);if(!s)return!1;const o=s.anchorIndex>=0?s.anchorIndex+1:e?.children.length??0;return this.insertNodes(r,t,s,o,!0)}const o=xe(t,n,this.schemaRegistry);if(!o)return!1;const a=ce(s)&&"before"===s.side?0:1;return this.insertNodes(r,t,o,o.anchorIndex+a,!ce(s))}insertNodes(e,t,n,r,s){const i=t.transaction("paste");let o,a=r;for(const l of e)i.insertNode(n.parentPath,a,l),a++,o=l;return s&&n.isAnchorEmpty&&n.anchorIndex>=0&&i.removeNode(n.parentPath,n.anchorIndex),o&&i.setSelection(re(o.id,A(o))),this.dispatch(i.build()),!0}};function gs(e){return""!==e.trim()&&/<\w/.test(e)}var ys=class{element;getState;dispatch;schemaRegistry;fileHandlerRegistry;isReadOnly;getPasteInterceptors;pasteMarkdown;getMarkdownSyntaxExtensions;announce;markdownImportedMessage;callbackExecutor;loadMarkdownParser;handlePaste;htmlHandler;richBlockHandler;pendingBookmarks=/* @__PURE__ */new Set;active=!0;constructor(e,t){this.element=e,this.getState=t.getState,this.dispatch=t.dispatch,this.schemaRegistry=t.schemaRegistry,this.fileHandlerRegistry=t.fileHandlerRegistry,this.isReadOnly=t.isReadOnly??(()=>!1),this.getPasteInterceptors=t.getPasteInterceptors??(()=>[]),this.pasteMarkdown=t.pasteMarkdown??"auto",this.getMarkdownSyntaxExtensions=t.getMarkdownSyntaxExtensions??(()=>[]),this.announce=t.announce,this.markdownImportedMessage=t.markdownImportedMessage??"Markdown imported",this.callbackExecutor=t.callbackExecutor??Or.silent,this.loadMarkdownParser=t.loadMarkdownParser??(()=>import("./MarkdownParser-D1d9zB0R.mjs").then(e=>e.t)),this.richBlockHandler=new fs(t.getState,e=>this.dispatchPasteTransaction(e),t.schemaRegistry),this.htmlHandler=new ms(t.getState,e=>this.dispatchPasteTransaction(e),t.schemaRegistry,(e,t)=>this.richBlockHandler.handleRichPasteFromJson(e,t)),this.handlePaste=this.onPaste.bind(this),e.addEventListener("paste",this.handlePaste)}onPaste(e){if(!_t(e,this.element))return;if(e.preventDefault(),this.isReadOnly())return;const t=e.clipboardData;if(!t)return;const n=this.captureClipboard(t);if(n.blockJson)return void this.richBlockHandler.handleBlockPaste(n.blockJson);const r=this.createBookmark(),s=function(e,t){if(0===t.length||t.some(e=>!e.type.startsWith("image/")))return!1;if(!gs(e))return!1;const n=(new DOMParser).parseFromString(e,"text/html").body,r=n.querySelectorAll("img, picture, svg, canvas"),s=r.length>0;for(const i of r)i.remove();return""!==(n.textContent??"").trim()||!s}(n.html,n.files),i=this.fileHandlerRegistry&&n.files.length>0&&!s?Vr({registry:this.fileHandlerRegistry,executor:this.callbackExecutor,files:n.files,getPosition:()=>null,isActive:()=>this.isBookmarkActive(r)}):{handled:!1,cancelled:!1};i instanceof Promise?this.continueAfterFileHandlers(i,n,r):i.handled||i.cancelled?this.releaseBookmark(r):this.processClipboardSnapshot(n,r,s?n.files:[])}processClipboardSnapshot(e,t,n){if(!this.isBookmarkActive(t))return void this.releaseBookmark(t);if(e.plainText&&this.tryPasteInterceptors(e.plainText,e.html,t))return;if(e.plainText&&"never"!==this.pasteMarkdown&&!gs(e.html)&&function(e){if(0===e.length)return!1;if(Gr.test(e))return!0;if(e.includes("|")&&Qr.test(e))return!0;const t=e.match(Jr);return null!==t&&t.length>=2}(e.plainText))return void this.handleMarkdownPaste(e.plainText,t);const r=this.consumeBookmark(t);r&&(e.html?this.htmlHandler.pasteHTMLString(e.html,r)||this.handleContentlessHTMLFallback(n,e.plainText,r):e.plainText&&this.htmlHandler.pastePlainText(e.plainText,r))}handleContentlessHTMLFallback(e,t,n){const r=this.fileHandlerRegistry;if(!r||0===e.length)return void(this.active&&!this.isReadOnly()&&t&&this.htmlHandler.pastePlainText(t,n));const s=this.createBookmark(n),i=Vr({registry:r,executor:this.callbackExecutor,files:e,getPosition:()=>null,isActive:()=>this.isBookmarkActive(s)});i instanceof Promise?this.continueContentlessHTMLFallback(i,t,s):this.finishContentlessHTMLFallback(i,t,s)}async continueContentlessHTMLFallback(e,t,n){try{this.finishContentlessHTMLFallback(await e,t,n)}catch(r){this.callbackExecutor.reportFailure({pluginId:"core",name:"Deferred file paste",kind:"file-handler"},r),this.releaseBookmark(n)}}finishContentlessHTMLFallback(e,t,n){if(e.handled||e.cancelled||!this.isBookmarkActive(n))return void this.releaseBookmark(n);const r=this.consumeBookmark(n);r&&t&&this.htmlHandler.pastePlainText(t,r)}async handleMarkdownPaste(e,t){const n=await this.callbackExecutor.executeMaybeAsync({pluginId:"core",name:"Markdown conversion",kind:"markdown-paste"},async()=>{const{parseMarkdownToDocument:t}=await this.loadMarkdownParser(),n=t(e,this.schemaRegistry,{syntaxExtensions:this.getMarkdownSyntaxExtensions()});return kt(n,this.schemaRegistry,{includeBlockIds:!1})});if(!this.isBookmarkActive(t))return void this.releaseBookmark(t);const r=this.consumeBookmark(t);if(!r)return;if(!n.ok)return void this.commitMarkdownPlainTextFallback(e,r);const s=this.callbackExecutor.execute({pluginId:"core",name:"Markdown HTML commit",kind:"markdown-paste"},()=>this.htmlHandler.pasteHTMLString(n.value,r));s.ok&&s.value?this.active&&!this.isReadOnly()&&this.callbackExecutor.execute({pluginId:"core",name:"Markdown announcement",kind:"markdown-paste"},()=>this.announce?.(this.markdownImportedMessage)):this.active&&!this.isReadOnly()&&this.commitMarkdownPlainTextFallback(e,r)}commitMarkdownPlainTextFallback(e,t){this.callbackExecutor.execute({pluginId:"core",name:"Markdown plain-text fallback",kind:"markdown-paste"},()=>this.htmlHandler.pastePlainText(e,t))}tryPasteInterceptors(e,t,n){const r=this.getPasteInterceptors(),s=this.getState().withSelection(n.selection);for(const i of r){const r=this.callbackExecutor.execute({pluginId:i.pluginId,name:i.name,kind:"paste-interceptor"},()=>i.interceptor(e,t,s));if(r.ok&&r.value)return this.consumeBookmark(n),this.dispatchPasteTransaction(r.value),!0}return!1}captureClipboard(e){const t=Array.from(e.files);if(0===t.length)for(let n=0;n<e.items.length;n++){const r=e.items[n];if(r&&"file"===r.kind){const e=r.getAsFile();e&&t.push(e)}}return{blockJson:e.getData("application/x-notectl-block"),files:t,plainText:e.getData("text/plain"),html:e.getData("text/html")}}async continueAfterFileHandlers(e,t,n){try{const r=await e;if(r.cancelled||!this.isBookmarkActive(n))return void this.releaseBookmark(n);if(r.handled)return void this.releaseBookmark(n);this.processClipboardSnapshot(t,n,[])}catch(r){this.callbackExecutor.reportFailure({pluginId:"core",name:"File paste continuation",kind:"file-handler"},r),this.releaseBookmark(n)}}onStateChange(e,t,n){for(const r of this.pendingBookmarks){if(e.doc!==t.doc&&0===n.steps.length){r.cancelled=!0,this.pendingBookmarks.delete(r);continue}const s=qr(r.selection,n.mapping);s&&ks(t,s)?r.selection=s:(r.cancelled=!0,this.pendingBookmarks.delete(r))}}createBookmark(e=this.getState().selection){const t={selection:e,cancelled:!1};return this.pendingBookmarks.add(t),t}consumeBookmark(e){return this.isBookmarkActive(e)?(this.pendingBookmarks.delete(e),e.selection):(this.releaseBookmark(e),null)}releaseBookmark(e){this.pendingBookmarks.delete(e)}isBookmarkActive(e){return this.active&&!this.isReadOnly()&&!e.cancelled&&this.pendingBookmarks.has(e)}dispatchPasteTransaction(e){const t=this.getState();if(ne(t.selection,e.selectionBefore))return void this.dispatch(e);const n=qr(t.selection,e.mapping);this.dispatch({...e,selectionBefore:t.selection,selectionAfter:n??e.selectionAfter,storedMarksAfter:t.storedMarks})}destroy(){if(this.active){this.active=!1,this.element.removeEventListener("paste",this.handlePaste);for(const e of this.pendingBookmarks)e.cancelled=!0;this.pendingBookmarks.clear()}}};function ks(e,t){return Z(t)?void 0!==e.getBlock(t.nodeId):ce(t)?void 0!==e.getBlock(t.blockId):!!ee(t)&&void 0!==e.getBlock(t.anchor.blockId)&&void 0!==e.getBlock(t.head.blockId)}var ws=class{compositionTracker;inputHandler;keyboardHandler;pasteHandler;clipboardHandler;constructor(e,t){this.compositionTracker=new Nr,this.inputHandler=new Dr(e,{getState:t.getState,dispatch:t.dispatch,syncSelection:t.syncSelection,inputRuleRegistry:t.inputRuleRegistry,isReadOnly:t.isReadOnly,shouldApplyInputRules:t.shouldApplyInputRules,compositionTracker:this.compositionTracker,getTextInputInterceptors:t.getTextInputInterceptors,callbackExecutor:t.callbackExecutor,resolveTargetRange:t.resolveTargetRange}),this.keyboardHandler=new Kr(e,{getState:t.getState,dispatch:t.dispatch,undo:t.undo,redo:t.redo,keymapRegistry:t.keymapRegistry,isReadOnly:t.isReadOnly,compositionTracker:this.compositionTracker,getTextDirection:t.getTextDirection,navigateFromGapCursor:t.navigateFromGapCursor,callbackExecutor:t.callbackExecutor}),this.pasteHandler=new ys(e,{getState:t.getState,dispatch:t.dispatch,schemaRegistry:t.schemaRegistry,fileHandlerRegistry:t.fileHandlerRegistry,isReadOnly:t.isReadOnly,getPasteInterceptors:t.getPasteInterceptors,pasteMarkdown:t.pasteMarkdown,getMarkdownSyntaxExtensions:t.getMarkdownSyntaxExtensions,announce:t.announce,markdownImportedMessage:t.markdownImportedMessage,callbackExecutor:t.callbackExecutor}),this.clipboardHandler=new Ar(e,{getState:t.getState,dispatch:t.dispatch,schemaRegistry:t.schemaRegistry,syncSelection:t.syncSelection,isReadOnly:t.isReadOnly})}onStateChange(e,t,n){this.pasteHandler.onStateChange(e,t,n)}destroy(){this.inputHandler.destroy(),this.keyboardHandler.destroy(),this.pasteHandler.destroy(),this.clipboardHandler.destroy()}},vs=class{_fileHandlers=[];registerFileHandler(e,t,n){this._fileHandlers.push({pattern:e,handler:t,pluginId:n?.pluginId??"unattributed",name:n?.name??(t.name||e)})}getFileHandlers(){return this._fileHandlers}matchFileHandlers(e){return this.matchFileHandlerEntries(e).map(e=>e.handler)}matchFileHandlerEntries(e){return this._fileHandlers.filter(t=>function(e,t){if("*"===e||"*/*"===e)return!0;if(e===t)return!0;if(e.endsWith("/*")){const n=e.slice(0,-1);return t.startsWith(n)}return!1}(t.pattern,e))}removeFileHandler(e){const t=this._fileHandlers.findIndex(t=>t.handler===e);-1!==t&&this._fileHandlers.splice(t,1)}clear(){this._fileHandlers.length=0}},bs=class{_inputRules=[];registerInputRule(e,t){this._inputRules.push({rule:e,pluginId:t?.pluginId??"unattributed",name:t?.name??(e.handler.name||e.pattern.toString())})}getInputRules(){return this._inputRules.map(e=>e.rule)}getInputRuleEntries(){return this._inputRules}removeInputRule(e){const t=this._inputRules.findIndex(t=>t.rule===e);-1!==t&&this._inputRules.splice(t,1)}clear(){this._inputRules.length=0}},Is=class{_contextKeymaps=[];_navigationKeymaps=[];_defaultKeymaps=[];registerKeymap(e,t,n){const r=t?.priority??"default";this.keymapArrayForPriority(r).push({keymap:e,pluginId:n?.pluginId??"unattributed",name:n?.name??(Object.keys(e).join(", ")||"anonymous-keymap")})}getKeymaps(){return[...this._contextKeymaps,...this._navigationKeymaps,...this._defaultKeymaps].map(e=>e.keymap)}getKeymapsByPriority(){return{context:this._contextKeymaps.map(e=>e.keymap),navigation:this._navigationKeymaps.map(e=>e.keymap),default:this._defaultKeymaps.map(e=>e.keymap)}}getKeymapEntriesByPriority(){return{context:[...this._contextKeymaps],navigation:[...this._navigationKeymaps],default:[...this._defaultKeymaps]}}removeKeymap(e){for(const t of[this._contextKeymaps,this._navigationKeymaps,this._defaultKeymaps]){const n=t.findIndex(t=>t.keymap===e);if(-1!==n)return void t.splice(n,1)}}clear(){this._contextKeymaps.length=0,this._navigationKeymaps.length=0,this._defaultKeymaps.length=0}keymapArrayForPriority(e){switch(e){case"context":return this._contextKeymaps;case"navigation":return this._navigationKeymaps;case"default":return this._defaultKeymaps}}},Ss=class{_extensions=[];register(e){this._extensions.push(e)}remove(e){const t=this._extensions.indexOf(e);-1!==t&&this._extensions.splice(t,1)}getExtensions(){return this._extensions}clear(){this._extensions.length=0}};function xs(e,t){if(function(e){return Kn.has(e)}(e))return e;const n=[],r=[];let s=t;for(const i of e.steps){const e=qn(i);n.push(e),r.push(Tt(ir(s,e))),s=rr(s,e)}return Wn({steps:n,selectionBefore:Vn(e.selectionBefore),selectionAfter:Vn(e.selectionAfter),storedMarksAfter:Un(e.storedMarksAfter),forwardStepMaps:r,metadata:e.metadata})}var Rs=class{_nodeViews=/* @__PURE__ */new Map;registerNodeView(e,t,n={pluginId:"unattributed",name:e}){if(this._nodeViews.has(e))throw new Error(`NodeView for type "${e}" is already registered.`);this._nodeViews.set(e,{...n,factory:t})}getNodeViewFactory(e){return this._nodeViews.get(e)?.factory}getNodeViewEntry(e){return this._nodeViews.get(e)}removeNodeView(e){this._nodeViews.delete(e)}clear(){this._nodeViews.clear()}},Ms=class{commands=/* @__PURE__ */new Map;readonlyBypassActive=!1;log;constructor(e=Mr){this.log=Pr(e,"CommandRegistry")}register(e,t,n,r){if(this.commands.has(e)){const t=this.commands.get(e);throw new Error(`Command "${e}" is already registered by plugin "${t?.pluginId}".`)}const s=r?.readonlyAllowed??!1;this.commands.set(e,{name:e,handler:t,pluginId:n,readonlyAllowed:s})}canExecute(e,t){const n=this.commands.get(e);return!(!n||t&&!n.readonlyAllowed)}execute(e,t){const n=this.commands.get(e);if(!n)return!1;if(t&&!n.readonlyAllowed)return!1;const r=t&&n.readonlyAllowed;r&&(this.readonlyBypassActive=!0);try{return n.handler()}catch(s){return this.log.error(`Command "${e}" error`,s),!1}finally{r&&(this.readonlyBypassActive=!1)}}isReadonlyBypassed(){return this.readonlyBypassActive}has(e){return this.commands.has(e)}remove(e){this.commands.delete(e)}clear(){this.commands.clear(),this.readonlyBypassActive=!1}get rawMap(){return this.commands}},Cs=class{listeners=/* @__PURE__ */new Map;log;constructor(e=Mr){this.log=Pr(e,"EventBus")}emit(e,t){const n=this.listeners.get(e.id);if(n)for(const s of n)try{s(t)}catch(r){this.log.error(`Listener error on "${e.id}"`,r)}}on(e,t){const n=e.id;this.listeners.has(n)||this.listeners.set(n,/* @__PURE__ */new Set);const r=this.listeners.get(n)??/* @__PURE__ */new Set;return r.add(t),()=>{r.delete(t),0===r.size&&this.listeners.delete(n)}}off(e,t){const n=this.listeners.get(e.id);n&&(n.delete(t),0===n.size&&this.listeners.delete(e.id))}clear(){this.listeners.clear()}},Ps=class{middlewares=[];middlewareSorted=null;pasteInterceptors=[];pasteInterceptorsSorted=null;textInputInterceptors=[];textInputInterceptorsSorted=null;log;constructor(e=Mr){this.log=Pr(e,"MiddlewareChain")}addMiddleware(e){this.middlewares.push(e),this.middlewareSorted=null}removeMiddleware(e){const t=this.middlewares.indexOf(e);-1!==t&&this.middlewares.splice(t,1),this.middlewareSorted=null}invalidateMiddlewareSort(){this.middlewareSorted=null}dispatch(e,t,n){if(0===this.middlewares.length)return void n(e);const r=this.getSortedMiddleware();let s=0,i=!1;const o=e=>{if(s<r.length){const n=r[s++];if(!n)return;let i=!1;const l=e=>{i||(i=!0,o(e))};try{n.middleware(e,t,l)}catch(a){this.log.error(`Middleware "${n.name}" error`,a),l(e)}}else i||(i=!0,n(e))};o(e)}getChain(){return this.getSortedMiddleware().map(e=>({name:e.name,priority:e.priority,pluginId:e.pluginId}))}addPasteInterceptor(e){this.pasteInterceptors.push(e),this.pasteInterceptorsSorted=null}removePasteInterceptor(e){const t=this.pasteInterceptors.indexOf(e);-1!==t&&this.pasteInterceptors.splice(t,1),this.pasteInterceptorsSorted=null}invalidatePasteSort(){this.pasteInterceptorsSorted=null}getPasteInterceptors(){return this.getSortedPasteInterceptors()}addTextInputInterceptor(e){this.textInputInterceptors.push(e),this.textInputInterceptorsSorted=null}removeTextInputInterceptor(e){const t=this.textInputInterceptors.indexOf(e);-1!==t&&this.textInputInterceptors.splice(t,1),this.textInputInterceptorsSorted=null}invalidateTextInputSort(){this.textInputInterceptorsSorted=null}getTextInputInterceptors(){return this.getSortedTextInputInterceptors()}get rawMiddlewares(){return this.middlewares}get rawPasteInterceptors(){return this.pasteInterceptors}get rawTextInputInterceptors(){return this.textInputInterceptors}clear(){this.middlewares.length=0,this.middlewareSorted=null,this.pasteInterceptors.length=0,this.pasteInterceptorsSorted=null,this.textInputInterceptors.length=0,this.textInputInterceptorsSorted=null}getSortedMiddleware(){return this.middlewareSorted||(this.middlewareSorted=[...this.middlewares].sort((e,t)=>e.priority-t.priority)),this.middlewareSorted}getSortedPasteInterceptors(){return this.pasteInterceptorsSorted||(this.pasteInterceptorsSorted=[...this.pasteInterceptors].sort((e,t)=>e.priority-t.priority)),this.pasteInterceptorsSorted}getSortedTextInputInterceptors(){return this.textInputInterceptorsSorted||(this.textInputInterceptorsSorted=[...this.textInputInterceptors].sort((e,t)=>e.priority-t.priority)),this.textInputInterceptorsSorted}},Ts=/* @__PURE__ */new WeakSet;function Es(e,t,n,r){return{registerCommand:(r,s,i)=>{if(t.has(r)){const e=t.get(r);throw new Error(`Command "${r}" is already registered by plugin "${e?.pluginId}".`)}const o=i?.readonlyAllowed??!1;t.set(r,{name:r,handler:s,pluginId:e,readonlyAllowed:o}),n.commands.push(r)},executeCommand:r}}function Bs(e,t){return{registerService:(n,r)=>{if(e.has(n.id))throw new Error(`Service "${n.id}" is already registered by another plugin.`);e.set(n.id,r),t.services.push(n.id)},getService:t=>e.get(t.id)}}function As(e,t){const{pluginId:n,middlewares:r,pasteInterceptors:s,textInputInterceptors:i,invalidateMiddlewareSort:o,invalidatePasteSort:a,invalidateTextInputSort:l}=e;return{registerMiddleware:(e,s)=>{const i={name:s?.name??(e.name||"anonymous"),pluginId:n,middleware:e,priority:s?.priority??100};r.push(i),t.middlewares.push(i),o()},registerPasteInterceptor:(e,r)=>{const i={name:r?.name??"anonymous",pluginId:n,interceptor:e,priority:r?.priority??100};s.push(i),t.pasteInterceptors.push(i),a()},registerTextInputInterceptor:(e,r)=>{const s={name:r?.name??"anonymous",pluginId:n,interceptor:e,priority:r?.priority??100};i.push(s),t.textInputInterceptors.push(s),l()}}}function Ns(e,t){return{registerNodeSpec:n=>{e.schemaRegistry.registerNodeSpec(Os(n,e.pluginId,e.callbackExecutor)),t.nodeSpecs.push(n.type)},registerNodeSpecExtension:(n,r)=>{const s=t=>{const s=e.callbackExecutor.execute({pluginId:e.pluginId,name:`${n}:extension`,kind:"schema-extension"},()=>r(t));return s.ok?Os(s.value,e.pluginId,e.callbackExecutor):t};e.schemaRegistry.registerNodeSpecExtension(n,s),t.nodeSpecExtensions.push({type:n,extension:s})},registerMarkSpec:n=>{e.schemaRegistry.registerMarkSpec(function(e,t,n){const r=Ls(e.type,e.parseHTML,t,n),s=e.toDOM,i=Ts.has(s)?s:r=>{const i=n.execute({pluginId:t,name:`${e.type}:toDOM`,kind:"schema-render"},()=>Ds(s(r),`${e.type}.toDOM`));return i.ok?i.value:document.createElement("span")};return Ts.add(i),{...e,toDOM:i,parseHTML:r}}(n,e.pluginId,e.callbackExecutor)),t.markSpecs.push(n.type)},registerInlineNodeSpec:n=>{e.schemaRegistry.registerInlineNodeSpec(function(e,t,n){const r=Ls(e.type,e.parseHTML,t,n),s=e.toDOM,i=Ts.has(s)?s:r=>{const i=n.execute({pluginId:t,name:`${e.type}:toDOM`,kind:"schema-render"},()=>Ds(s(r),`${e.type}.toDOM`));if(i.ok)return i.value;const o=document.createElement("span");return o.setAttribute("data-inline-type",r.inlineType),o};return Ts.add(i),{...e,toDOM:i,parseHTML:r}}(n,e.pluginId,e.callbackExecutor)),t.inlineNodeSpecs.push(n.type)}}}function Os(e,t,n){const r=Ls(e.type,e.parseHTML,t,n),s=e.toDOM,i=Ts.has(s)?s:r=>{const i=n.execute({pluginId:t,name:`${e.type}:toDOM`,kind:"schema-render"},()=>Ds(s(r),`${e.type}.toDOM`));if(i.ok)return i.value;const o=document.createElement("div");return o.setAttribute("data-block-id",r.id),o};return Ts.add(i),{...e,toDOM:i,parseHTML:r}}function Ds(e,t){if(e instanceof HTMLElement)return e;throw new TypeError(`${t} must return an HTMLElement.`)}function Ls(e,t,n,r){return t?.some(e=>e.getAttrs)?t.map(t=>{const s=t.getAttrs;return s?{...t,getAttrs(i){const o=r.execute({pluginId:n,name:`${e}:${t.tag}`,kind:"schema-parse"},()=>s(i));return!!o.ok&&o.value}}:t}):t}function Hs(e,t,n){return{registerNodeView:(r,s)=>{t.nodeViewRegistry.registerNodeView(r,s,{pluginId:e,name:r}),n.nodeViews.push(r)},registerKeymap:(r,s)=>{t.keymapRegistry.registerKeymap(r,s,{pluginId:e,name:Object.keys(r).join(", ")||"anonymous-keymap"}),n.keymaps.push(r)},registerInputRule:r=>{t.inputRuleRegistry.registerInputRule(r,{pluginId:e,name:r.handler.name||r.pattern.toString()}),n.inputRules.push(r)},registerMarkdownSyntax:r=>{const s=function(e,t,n){const r=e.matchInline,s=e.matchBlock;return{...e,...r?{matchInline(s,i){const o=n.execute({pluginId:t,name:`${e.id}:matchInline`,kind:"markdown-syntax"},()=>function(e,t){const n=zs(e,"length",t);return n?{type:n.type,attrs:n.attrs,length:n.consumed}:null}(r(s,i),s.length-i));return o.ok?o.value:null}}:{},...s?{matchBlock(r,i){const o=n.execute({pluginId:t,name:`${e.id}:matchBlock`,kind:"markdown-syntax"},()=>function(e,t){const n=zs(e,"linesConsumed",t);return n?{type:n.type,attrs:n.attrs,linesConsumed:n.consumed}:null}(s(r,i),r.length-i));return o.ok?o.value:null}}:{}}}(r,e,t.callbackExecutor);t.markdownSyntaxRegistry.register(s),n.markdownSyntaxExtensions.push(s)},registerToolbarItem:r=>{t.toolbarRegistry.registerToolbarItem(r,e),n.toolbarItems.push(r.id)},registerBlockTypePickerEntry:e=>{t.blockTypePickerRegistry.registerBlockTypePickerEntry(e),n.blockTypePickerEntries.push(e.id)},registerFileHandler:(r,s)=>{t.fileHandlerRegistry.registerFileHandler(r,s,{pluginId:e,name:s.name||r}),n.fileHandlers.push(s)},registerStyleSheet:e=>{const r=new CSSStyleSheet;r.replaceSync(e),t.pluginStyleSheets.push(r),n.stylesheets.push(r)}}}function zs(e,t,n){if(null===e)return null;if(!js(e))throw new TypeError("Markdown match must be null or an object descriptor.");const r=e.type;if("string"!=typeof r||0===r.trim().length)throw new TypeError("Markdown match type must be a non-empty string.");const s=function(e){if(!js(e))throw new TypeError("Markdown match attrs must be an object.");const t=[];for(const[n,r]of Object.entries(e)){if(!Fs(r))throw new TypeError("Markdown match attrs must contain only primitive finite values.");t.push([n,r])}return Object.fromEntries(t)}(e.attrs),i=e[t];if("number"!=typeof i||!Number.isFinite(i)||!Number.isInteger(i)||i<=0||i>n)throw new TypeError(`Markdown match ${t} must be a positive integer within the remaining input.`);return{type:r,attrs:s,consumed:i}}function Fs(e){return"string"==typeof e||"boolean"==typeof e||"number"==typeof e&&Number.isFinite(e)}function js(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}function $s(e){return{getSchemaRegistry:()=>e.schemaRegistry,getKeymapRegistry:()=>e.keymapRegistry,getInputRuleRegistry:()=>e.inputRuleRegistry,getFileHandlerRegistry:()=>e.fileHandlerRegistry,getNodeViewRegistry:()=>e.nodeViewRegistry,getToolbarRegistry:()=>e.toolbarRegistry,getBlockTypePickerRegistry:()=>e.blockTypePickerRegistry}}var _s=class{tracker;plugins=/* @__PURE__ */new Map;initOrder=[];startedInitOrder=[];initialized=!1;initializing=!1;destroying=!1;lifecycleVersion=0;pendingInit=null;pendingDestroy=null;readOnly=!1;log;constructor(e,t=Mr){this.tracker=e,this.log=Pr(t,"PluginLifecycle")}register(e){if(this.initialized||this.initializing||this.destroying)throw new Error(`Cannot register plugin "${e.id}" after initialization.`);if(this.plugins.has(e.id))throw new Error(`Plugin "${e.id}" is already registered.`);this.plugins.set(e.id,e)}get(e){return this.plugins.get(e)}getPluginIds(){return[...this.plugins.keys()]}init(e,t){if(this.destroying)return Promise.reject(/* @__PURE__ */new Error("Cannot initialize plugins while destruction is in progress."));if(this.initialized)return Promise.resolve();if(this.pendingInit)return this.pendingInit;this.initializing=!0;const n=this.lifecycleVersion,r=Promise.resolve().then(()=>this.runInitialization(e,t,n)).finally(()=>{this.pendingInit===r&&(this.pendingInit=null,this.initializing=!1)});return this.pendingInit=r,r}async runInitialization(e,t,n){const r=()=>n!==this.lifecycleVersion||!0===e.isCancelled?.();try{this.initOrder=this.resolveOrder();for(const n of this.initOrder){if(r())return void(await this.rollbackStartedPlugins());const s=this.plugins.get(n);if(!s)continue;this.startedInitOrder.push(n);const i=t(n,e);if(await s.init(i),r())return void(await this.rollbackStartedPlugins())}if(r())return void(await this.rollbackStartedPlugins());if(e.onBeforeReady&&await e.onBeforeReady(),r())return void(await this.rollbackStartedPlugins());for(const e of this.initOrder){if(r())return void(await this.rollbackStartedPlugins());const t=this.plugins.get(e);if(t?.onReady){try{await t.onReady()}catch(s){this.log.error(`Plugin "${e}" error in onReady`,s)}if(r())return void(await this.rollbackStartedPlugins())}}if(r())return void(await this.rollbackStartedPlugins());this.initialized=!0}catch(s){throw await this.rollbackStartedPlugins(),s}}destroy(){if(this.pendingDestroy)return this.pendingDestroy;this.destroying=!0,this.lifecycleVersion+=1;const e=this.pendingInit,t=Promise.resolve().then(()=>this.runDestruction(e)).finally(()=>{this.pendingDestroy===t&&(this.pendingDestroy=null,this.destroying=!1)});return this.pendingDestroy=t,t}async runDestruction(e){if(e)try{await e}catch{}const t=[...this.startedInitOrder].reverse();for(const n of t)await this.destroyPlugin(n);this.plugins.clear(),this.initOrder=[],this.startedInitOrder=[],this.initialized=!1,this.initializing=!1}notifyStateChange(e,t,n){for(const s of this.initOrder){const i=this.plugins.get(s);if(i?.onStateChange)try{i.onStateChange(e,t,n)}catch(r){this.log.error(`Plugin "${s}" error in onStateChange`,r)}}}collectDecorations(e,t){let n=Lt.empty;for(const s of this.initOrder){const i=this.plugins.get(s);if(i?.decorations)try{const r=i.decorations(e,t).withWidgetOwner(s);r.isEmpty||(n=n.merge(r))}catch(r){this.log.error(`Plugin "${s}" error in decorations()`,r)}}return n}configurePlugin(e,t){const n=this.plugins.get(e);if(!n)throw new Error(`Plugin "${e}" not found.`);if(n.onConfigure)try{n.onConfigure(t)}catch(r){this.log.error(`Plugin "${e}" error in onConfigure`,r)}}isReadOnly(){return this.readOnly}setReadOnly(e){if(this.readOnly!==e){this.readOnly=e;for(const n of this.initOrder){const r=this.plugins.get(n);if(r?.onReadOnlyChange)try{r.onReadOnlyChange(e)}catch(t){this.log.error(`Plugin "${n}" error in onReadOnlyChange`,t)}}}}get rawPlugins(){return this.plugins}get isInitialized(){return this.initialized}async destroyPlugin(e){const t=this.plugins.get(e);if(t?.destroy)try{await t.destroy()}catch(n){this.log.error(`Plugin "${e}" error in destroy`,n)}this.tracker.cleanup(e)}async rollbackStartedPlugins(){const e=[...this.startedInitOrder].reverse();for(const t of e)await this.destroyPlugin(t);this.startedInitOrder=[],this.initOrder=[],this.initialized=!1}resolveOrder(){const e=[...this.plugins.keys()];for(const i of e){const e=this.plugins.get(i);if(e)for(const t of e.dependencies??[])if(!this.plugins.has(t))throw new Error(`Plugin "${i}" depends on "${t}", which is not registered.`)}const t=/* @__PURE__ */new Map,n=/* @__PURE__ */new Map;for(const i of e)t.set(i,0),n.set(i,[]);for(const i of e){const e=this.plugins.get(i)?.dependencies??[];t.set(i,e.length);for(const t of e){const e=n.get(t);e&&e.push(i)}}const r=[];for(const[i,o]of t)0===o&&r.push(i);const s=[];for(;r.length>0;){r.sort((e,t)=>(this.plugins.get(e)?.priority??100)-(this.plugins.get(t)?.priority??100));const e=r.shift();if(!e)break;s.push(e);for(const s of n.get(e)??[]){const e=(t.get(s)??0)-1;t.set(s,e),0===e&&r.push(s)}}if(s.length!==e.length){const t=e.filter(e=>!s.includes(e));throw new Error(`Circular dependency detected among plugins: ${t.join(", ")}`)}return s}},Ks=class{deps;registrations=/* @__PURE__ */new Map;pluginStyleSheets=[];constructor(e){this.deps=e}track(e,t){this.registrations.set(e,t)}cleanup(e){const t=this.registrations.get(e);if(t){for(const e of t.commands)this.deps.commandRegistry.remove(e);for(const e of t.services)this.deps.serviceRegistry.remove(e);for(const e of t.middlewares)this.deps.middlewareChain.removeMiddleware(e);for(const e of t.pasteInterceptors)this.deps.middlewareChain.removePasteInterceptor(e);for(const e of t.textInputInterceptors)this.deps.middlewareChain.removeTextInputInterceptor(e);for(const e of t.unsubscribers)e();for(const{type:e,extension:n}of t.nodeSpecExtensions)this.deps.schemaRegistry.removeNodeSpecExtension(e,n);for(const e of t.nodeSpecs)this.deps.schemaRegistry.removeNodeSpec(e);for(const e of t.markSpecs)this.deps.schemaRegistry.removeMarkSpec(e);for(const e of t.inlineNodeSpecs)this.deps.schemaRegistry.removeInlineNodeSpec(e);for(const e of t.nodeViews)this.deps.nodeViewRegistry.removeNodeView(e);for(const e of t.keymaps)this.deps.keymapRegistry.removeKeymap(e);for(const e of t.inputRules)this.deps.inputRuleRegistry.removeInputRule(e);for(const e of t.markdownSyntaxExtensions)this.deps.markdownSyntaxRegistry.remove(e);for(const e of t.toolbarItems)this.deps.toolbarRegistry.removeToolbarItem(e);for(const e of t.fileHandlers)this.deps.fileHandlerRegistry.removeFileHandler(e);for(const e of t.blockTypePickerEntries)this.deps.blockTypePickerRegistry.removeBlockTypePickerEntry(e);for(const e of t.stylesheets){const t=this.pluginStyleSheets.indexOf(e);-1!==t&&this.pluginStyleSheets.splice(t,1)}this.registrations.delete(e)}}clear(){this.registrations.clear(),this.pluginStyleSheets.length=0}get rawStyleSheets(){return this.pluginStyleSheets}},Vs=class{services=/* @__PURE__ */new Map;register(e,t){if(this.services.has(e.id))throw new Error(`Service "${e.id}" is already registered.`);this.services.set(e.id,t)}get(e){return this.services.get(e.id)}has(e){return this.services.has(e)}remove(e){this.services.delete(e)}clear(){this.services.clear()}get rawMap(){return this.services}},Us=class{schemaRegistry=new Jt;keymapRegistry=new Is;inputRuleRegistry=new bs;markdownSyntaxRegistry=new Ss;fileHandlerRegistry=new vs;nodeViewRegistry=new Rs;toolbarRegistry=new Yt;blockTypePickerRegistry=new Xt;logger;commandRegistry;serviceRegistry=new Vs;middlewareChain;eventBus;registrationTracker;lifecycle;callbackExecutor;pendingDestroy=null;constructor(e={}){this.logger=e.logger??Mr,this.callbackExecutor=new Or(e=>{this.logger.error(`[PluginCallback] Plugin "${e.pluginId}" ${e.kind} "${e.name}" error`,e.cause)}),this.commandRegistry=new Ms(this.logger),this.middlewareChain=new Ps(this.logger),this.eventBus=new Cs(this.logger),this.registrationTracker=new Ks({commandRegistry:this.commandRegistry,serviceRegistry:this.serviceRegistry,middlewareChain:this.middlewareChain,schemaRegistry:this.schemaRegistry,keymapRegistry:this.keymapRegistry,inputRuleRegistry:this.inputRuleRegistry,markdownSyntaxRegistry:this.markdownSyntaxRegistry,nodeViewRegistry:this.nodeViewRegistry,toolbarRegistry:this.toolbarRegistry,fileHandlerRegistry:this.fileHandlerRegistry,blockTypePickerRegistry:this.blockTypePickerRegistry}),this.lifecycle=new _s(this.registrationTracker,this.logger)}registerService(e,t){this.serviceRegistry.register(e,t)}register(e){if(this.pendingDestroy)throw new Error(`Cannot register plugin "${e.id}" while destruction is in progress.`);this.lifecycle.register(e)}init(e){if(this.pendingDestroy)return Promise.reject(/* @__PURE__ */new Error("Cannot initialize PluginManager while destruction is in progress."));const t={...e,onBeforeReady:async()=>{this.schemaRegistry.finalize(),await(e.onBeforeReady?.())}};return this.lifecycle.init(t,(e,t)=>this.createContext(e,t))}notifyStateChange(e,t,n){this.lifecycle.notifyStateChange(e,t,n)}collectDecorations(e,t){return this.lifecycle.collectDecorations(e,t)}dispatchWithMiddleware(e,t,n){this.middlewareChain.dispatch(e,t,e=>{n(xs(e,t.doc))})}canExecuteCommand(e){return this.commandRegistry.canExecute(e,this.lifecycle.isReadOnly())}executeCommand(e){return this.commandRegistry.execute(e,this.lifecycle.isReadOnly())}isReadonlyBypassed(){return this.commandRegistry.isReadonlyBypassed()}configurePlugin(e,t){this.lifecycle.configurePlugin(e,t)}isReadOnly(){return this.lifecycle.isReadOnly()}setReadOnly(e){this.lifecycle.setReadOnly(e)}getPluginIds(){return this.lifecycle.getPluginIds()}getMiddlewareChain(){return this.middlewareChain.getChain()}getPasteInterceptors(){return this.middlewareChain.getPasteInterceptors()}getTextInputInterceptors(){return this.middlewareChain.getTextInputInterceptors()}getCallbackExecutor(){return this.callbackExecutor}get(e){return this.lifecycle.get(e)}getService(e){return this.serviceRegistry.get(e)}onEvent(e,t){return this.eventBus.on(e,t)}getPluginStyleSheets(){return this.registrationTracker.rawStyleSheets}destroy(){if(this.pendingDestroy)return this.pendingDestroy;const e=this.lifecycle.destroy().then(()=>this.clearRegistries()).finally(()=>{this.pendingDestroy===e&&(this.pendingDestroy=null)});return this.pendingDestroy=e,e}clearRegistries(){this.commandRegistry.clear(),this.serviceRegistry.clear(),this.middlewareChain.clear(),this.registrationTracker.clear(),this.eventBus.clear(),this.schemaRegistry.clear(),this.keymapRegistry.clear(),this.inputRuleRegistry.clear(),this.markdownSyntaxRegistry.clear(),this.fileHandlerRegistry.clear(),this.nodeViewRegistry.clear(),this.toolbarRegistry.clear(),this.blockTypePickerRegistry.clear()}createContext(e,t){const n=t.getCompositionState??(()=>qs),r={pluginId:e,logger:this.logger,getState:t.getState,dispatch:t.dispatch,getContainer:t.getContainer,getPluginContainer:t.getPluginContainer,announce:t.announce,hasAnnouncement:t.hasAnnouncement,commands:this.commandRegistry.rawMap,services:this.serviceRegistry.rawMap,middlewares:this.middlewareChain.rawMiddlewares,pasteInterceptors:this.middlewareChain.rawPasteInterceptors,textInputInterceptors:this.middlewareChain.rawTextInputInterceptors,pluginStyleSheets:this.registrationTracker.rawStyleSheets,plugins:this.lifecycle.rawPlugins,eventBus:this.eventBus,callbackExecutor:this.callbackExecutor,schemaRegistry:this.schemaRegistry,keymapRegistry:this.keymapRegistry,inputRuleRegistry:this.inputRuleRegistry,markdownSyntaxRegistry:this.markdownSyntaxRegistry,toolbarRegistry:this.toolbarRegistry,blockTypePickerRegistry:this.blockTypePickerRegistry,fileHandlerRegistry:this.fileHandlerRegistry,nodeViewRegistry:this.nodeViewRegistry,getCompositionState:n,isReadOnly:()=>this.lifecycle.isReadOnly(),invalidateMiddlewareSort:()=>this.middlewareChain.invalidateMiddlewareSort(),invalidatePasteSort:()=>this.middlewareChain.invalidatePasteSort(),invalidateTextInputSort:()=>this.middlewareChain.invalidateTextInputSort(),executeCommand:e=>this.executeCommand(e)},{context:s,registrations:i}=function(e){const t={commands:[],services:[],middlewares:[],pasteInterceptors:[],textInputInterceptors:[],unsubscribers:[],nodeSpecs:[],nodeSpecExtensions:[],markSpecs:[],inlineNodeSpecs:[],nodeViews:[],keymaps:[],inputRules:[],markdownSyntaxExtensions:[],toolbarItems:[],fileHandlers:[],blockTypePickerEntries:[],stylesheets:[]},n=function(e,t){return{emit:(t,n)=>e.emit(t,n),on:(n,r)=>{const s=e.on(n,r);return t.unsubscribers.push(s),s},off:(t,n)=>e.off(t,n)}}(e.eventBus,t);return{context:{getState:e.getState,dispatch:e.dispatch,getContainer:e.getContainer,getPluginContainer:e.getPluginContainer,isReadOnly:e.isReadOnly,getEventBus:()=>n,...Es(e.pluginId,e.commands,t,e.executeCommand),...Bs(e.services,t),...As(e,t),...Ns(e,t),...Hs(e.pluginId,e,t),...$s(e),updateConfig:t=>{const n=e.plugins.get(e.pluginId);if(n?.onConfigure)try{n.onConfigure(t)}catch(r){const t=`[PluginContext] Plugin "${e.pluginId}" error in onConfigure`;e.logger.error(t,r)}},announce:t=>{e.announce?.(t)},hasAnnouncement:()=>e.hasAnnouncement?.()??!1,getCompositionState:()=>e.getCompositionState()},registrations:t}}(r);return this.registrationTracker.track(e,i),s}},qs={isComposing:!1,activeBlockId:null},Ws=class{undoStack=[];redoStack=[];groupTimeoutMs;maxDepth;lastOrigin=null;constructor(e){this.groupTimeoutMs=e?.groupTimeoutMs??500,this.maxDepth=e?.maxDepth??100}push(e){if("history"===e.metadata.origin)return;if(!e.steps.some(e=>"setStoredMarks"!==e.type))return void(this.lastOrigin=null);const t=e.metadata.timestamp,n=this.undoStack[this.undoStack.length-1];for(n&&"input"===e.metadata.origin&&"input"===this.lastOrigin&&t-n.timestamp<this.groupTimeoutMs&&this.isSameInputType(n.transactions,e)&&n?this.undoStack[this.undoStack.length-1]={...n,transactions:[...n.transactions,e],timestamp:t}:this.undoStack.push({transactions:[e],timestamp:t,interveningMapping:Mt.empty}),this.lastOrigin=e.metadata.origin,this.redoStack=[];this.undoStack.length>this.maxDepth;)this.undoStack.shift()}recordIntervening(e){e.isEmpty||(Js(this.undoStack,e),Js(this.redoStack,e))}undo(e){const t=this.undoStack.pop();if(!t)return null;const n=Gs(t,e,"undo");return null===n?(this.lastOrigin=null,null):(this.redoStack.push({transactions:[n.transaction],timestamp:Date.now(),interveningMapping:Mt.empty}),this.lastOrigin=null,{state:n.newState,transaction:n.transaction})}redo(e){const t=this.redoStack.pop();if(!t)return null;const n=Gs(t,e,"redo");return null===n?(this.lastOrigin=null,null):(this.undoStack.push({transactions:[n.transaction],timestamp:Date.now(),interveningMapping:Mt.empty}),this.lastOrigin=null,{state:n.newState,transaction:n.transaction})}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0}clear(){this.undoStack=[],this.redoStack=[],this.lastOrigin=null}isSameInputType(e,t){const n=e[e.length-1];return!!n&&n.steps[0]?.type===t.steps[0]?.type}};function Gs(e,t,n){let r=e.interveningMapping,s=t.doc;const i=[],o=[];for(let h=e.transactions.length-1;h>=0;h--){const t=e.transactions[h];if(t)for(let e=t.steps.length-1;e>=0;e--){const n=t.steps[e],a=t.forwardStepMaps[e];if(!n||!a)continue;const l=or(sr(n),r,s);if(null===l)return null;const c=ir(s,l);i.push(l),o.push(c),s=rr(s,l),r=Qs(a,r,c)}}const a=function(e){const t=e.transactions[0];return t?Fn(t):null}(e),l=xs({steps:i,selectionBefore:t.selection,selectionAfter:t.selection,storedMarksAfter:a,mapping:Mt.from(o),forwardStepMaps:o,metadata:{origin:"history",timestamp:Date.now(),historyDirection:n}},t.doc);let c=t.apply(l);const d=e.transactions[0];if(d){const e=qr(d.selectionBefore,r);null!==e&&(c=c.withSelection(e))}return{newState:c,transaction:Wn({steps:l.steps,selectionBefore:l.selectionBefore,selectionAfter:Vn(c.selection),storedMarksAfter:l.storedMarksAfter,forwardStepMaps:l.forwardStepMaps,metadata:l.metadata})}}function Qs(e,t,n){return t.isEmpty&&Rt(Ht(e),n)?t:Mt.from([e]).appendMapping(t).appendMap(n)}function Js(e,t){for(let n=0;n<e.length;n++){const r=e[n];r&&(e[n]={...r,interveningMapping:r.interveningMapping.appendMapping(t)})}}function Xs(e){for(const t of e.steps)if("setStoredMarks"!==t.type)return!1;return!0}function Ys(e){return!!e.metadata.readonlyAllowed||Xs(e)}function Zs(e,t){if(t){const n=t.getMarkSpec(e.type);if(n)return n.rank??100}switch(e.type){case"bold":return 0;case"italic":return 1;case"underline":return 2;default:return 100}}function ei(e,t,n){if(0===t.length)return e;const r=[...t].sort((e,t)=>Zs(e,n)-Zs(t,n));let s=e;for(let i=r.length-1;i>=0;i--){const e=r[i];if(!e)continue;const t=ti(e,n);t.appendChild(s),s=t}return s}function ti(e,t){if(t){const n=t.getMarkSpec(e.type);if(n)return n.toDOM(e)}switch(e.type){case"bold":return document.createElement("strong");case"italic":return document.createElement("em");case"underline":return document.createElement("u");default:return document.createElement("span")}}var ni=class{wrapperElement=null;container;registry;constructor(e,t){this.container=e,this.registry=t}get isActive(){return null!==this.wrapperElement}onCompositionStart(e){this.cleanup();const t=e.storedMarks;if(!t||0===t.length)return;const n=e.selection;if(!ee(n))return;if(!Y(n))return;const r=document.createElement("span");r.setAttribute("data-cursor-wrapper","");const s=document.createTextNode(""),i=ei(s,t,this.registry);r.appendChild(i);const o=on();if(!o||0===o.rangeCount)return;let a;const l=nn(this.container,o);if(l){const e=document.createRange();try{e.setStart(l.anchorNode,l.anchorOffset),e.setEnd(l.focusNode,l.focusOffset)}catch{return}a=e}else a=o.getRangeAt(0);a.insertNode(r);try{o.collapse(s,s.length)}catch{}this.wrapperElement=r}cleanup(){this.wrapperElement&&(this.wrapperElement.remove(),this.wrapperElement=null)}};function ri(e){return e.shiftKey||e.ctrlKey||e.altKey||e.metaKey}function si(e,t){return Math.abs(t.clientX-e.clientX)>4||Math.abs(t.clientY-e.clientY)>4}var ii=class{deps;handleSelectionChange;handleMousedown;handleMousemove;handleMouseup;handleDragover;handleDrop;handleCompositionStart;handleCompositionEnd;pendingNodeSelectionClear=!1;pendingGapCursorClear=!1;pendingBelowContentPress=null;pendingDropBookmarks=/* @__PURE__ */new Set;callbackExecutor;active=!0;constructor(e){this.deps=e,this.callbackExecutor=e.callbackExecutor??Or.silent,this.handleCompositionStart=t=>{_t(t,e.contentElement)&&e.cursorWrapper.onCompositionStart(e.getState())},this.handleCompositionEnd=t=>{_t(t,e.contentElement)&&e.cursorWrapper.cleanup()},e.contentElement.addEventListener("compositionstart",this.handleCompositionStart),e.contentElement.addEventListener("compositionend",this.handleCompositionEnd),this.handleSelectionChange=this.onSelectionChange.bind(this),document.addEventListener("selectionchange",this.handleSelectionChange),this.handleMousedown=this.onMousedown.bind(this),e.contentElement.addEventListener("mousedown",this.handleMousedown),this.handleMousemove=this.onMousemove.bind(this),this.handleMouseup=this.onMouseup.bind(this),document.addEventListener("mouseup",this.handleMouseup),this.handleDragover=this.onDragover.bind(this),e.contentElement.addEventListener("dragover",this.handleDragover),this.handleDrop=this.onDrop.bind(this),e.contentElement.addEventListener("drop",this.handleDrop)}syncSelectionFromDOM(){if(this.deps.compositionState.isComposing)return;this.deps.cursorWrapper.isActive&&this.deps.cursorWrapper.cleanup();const e=this.deps.getState();if(Z(e.selection)&&!this.pendingNodeSelectionClear)return;if(ce(e.selection)&&!this.pendingGapCursorClear)return;this.pendingNodeSelectionClear=!1,this.pendingGapCursorClear=!1;const t=sn(this.deps.contentElement);if(!t)return;if(ne(t,e.selection))return;const n=e.transaction("input").setSelection(t).setStoredMarks(null,e.storedMarks).build(),r=e.apply(n);this.deps.applyUpdate(r,n,!0)}destroy(){if(!this.active)return;this.active=!1;const e=this.deps.contentElement;e.removeEventListener("compositionstart",this.handleCompositionStart),e.removeEventListener("compositionend",this.handleCompositionEnd),document.removeEventListener("selectionchange",this.handleSelectionChange),document.removeEventListener("mouseup",this.handleMouseup),e.removeEventListener("mousedown",this.handleMousedown),this.clearBelowContentPress(),e.removeEventListener("dragover",this.handleDragover),e.removeEventListener("drop",this.handleDrop);for(const t of this.pendingDropBookmarks)t.cancelled=!0;this.pendingDropBookmarks.clear()}onStateChange(e,t,n){e.doc!==t.doc&&(this.clearBelowContentPress(),this.pendingNodeSelectionClear=!1,this.pendingGapCursorClear=!1),Z(t.selection)||(this.pendingNodeSelectionClear=!1),ce(t.selection)||(this.pendingGapCursorClear=!1);for(const r of this.pendingDropBookmarks){if(!r.position)continue;if(e.doc!==t.doc&&0===n.steps.length){r.cancelled=!0,this.pendingDropBookmarks.delete(r);continue}const s=n.mapping.mapResult(r.position,-1);!s.deleted&&t.getBlock(s.pos.blockId)?r.position=s.pos:(r.cancelled=!0,this.pendingDropBookmarks.delete(r))}}onSelectionChange(){if(this.deps.isUpdating())return;const e=this.deps.contentElement.getRootNode(),t="activeElement"in e?e.activeElement:document.activeElement;(this.deps.contentElement.contains(t)||t===this.deps.contentElement)&&$t(t,this.deps.contentElement)&&this.syncSelectionFromDOM()}onMousedown(e){if(this.clearBelowContentPress(),this.deps.isUpdating())return;if(!_t(e,this.deps.contentElement))return;this.deps.onMousedown?.();const t=e.target;if(!(t instanceof HTMLElement))return;const n=t.closest("[data-block-id]");if(!(n instanceof HTMLElement&&this.deps.contentElement.contains(n)))return void((this.deps.contentElement.contains(t)||t===this.deps.contentElement)&&this.trackBelowContentPress(e));if(!n.hasAttribute("data-void")&&!n.hasAttribute("data-selectable"))return void this.markPendingSelectionClear();if(n.querySelector("[data-content-dom]")?.contains(t))return void this.markPendingSelectionClear();e.preventDefault(),this.deps.contentElement.focus();const r=pe(n.getAttribute("data-block-id")??""),s=tn(this.deps.contentElement,n),i=te(r,s),o=this.deps.getState(),a=o.transaction("input").setSelection(i).setStoredMarks(null,o.storedMarks).build(),l=o.apply(a);this.deps.applyUpdate(l,a)}trackBelowContentPress(e){this.deps.isReadOnly()||e.defaultPrevented||0!==e.button||ri(e)||this.isBelowLastRootBlock(e.clientY)&&(this.markPendingSelectionClear(),this.pendingBelowContentPress={clientX:e.clientX,clientY:e.clientY,dragged:!1},document.addEventListener("mousemove",this.handleMousemove))}onMousemove(e){const t=this.pendingBelowContentPress;t&&(1&e.buttons?si(t,e)&&(t.dragged=!0,document.removeEventListener("mousemove",this.handleMousemove)):this.clearBelowContentPress())}onMouseup(e){const t=this.clearBelowContentPress();t&&(this.deps.isUpdating()||e.defaultPrevented||0!==e.button||0!==e.buttons||ri(e)||t.dragged||si(t,e)||this.isBelowLastRootBlock(e.clientY)&&this.handleClickBelowContent())}clearBelowContentPress(){const e=this.pendingBelowContentPress;return this.pendingBelowContentPress=null,document.removeEventListener("mousemove",this.handleMousemove),e}isBelowLastRootBlock(e){const t=this.deps.getState(),n=t.doc.children[t.doc.children.length-1];if(!n)return!1;const r=this.deps.contentElement.querySelector(`[data-block-id="${n.id}"]`);return!!r&&e>r.getBoundingClientRect().bottom}handleClickBelowContent(){if(this.deps.isReadOnly())return;const e=this.deps.getState(),t=e.doc.children[e.doc.children.length-1];if(!t)return;const n=t.id,r=e.getBlock(n);if("paragraph"===r?.type&&0===A(r)){const t=e.transaction("input").setSelection(re(n,0)).build();return void this.deps.dispatch(t)}this.deps.contentElement.focus();const s=l(),i=e.transaction("input").insertNode([],e.doc.children.length,T(s)).setSelection(re(s,0)).build();this.deps.dispatch(i)}onDragover(e){this.deps.fileHandlerRegistry&&e.dataTransfer&&e.dataTransfer.types.includes("Files")&&e.preventDefault()}onDrop(e){if(this.deps.isReadOnly())return;if(!this.deps.fileHandlerRegistry)return;if(!e.dataTransfer)return;const t=Array.from(e.dataTransfer.files);if(0===t.length)return;const n={position:this.getPositionFromPoint(e.clientX,e.clientY),cancelled:!1};this.pendingDropBookmarks.add(n);const r=Vr({registry:this.deps.fileHandlerRegistry,executor:this.callbackExecutor,files:t,getPosition:()=>n.position,isActive:()=>this.active&&!this.deps.isReadOnly()&&!n.cancelled});if(r instanceof Promise)return e.preventDefault(),void this.finishAsyncFileDrop(r,n);this.pendingDropBookmarks.delete(n),r.handled&&e.preventDefault()}async finishAsyncFileDrop(e,t){try{await e}catch(n){this.callbackExecutor.reportFailure({pluginId:"core",name:"File drop continuation",kind:"file-handler"},n)}finally{this.pendingDropBookmarks.delete(t)}}getPositionFromPoint(e,t){const n=this.deps.contentElement.getRootNode(),r=Qe(n,e,t);return r&&this.deps.contentElement.contains(r.node)?ln(this.deps.contentElement,r.node,r.offset):null}markPendingSelectionClear(){const e=this.deps.getState();Z(e.selection)&&(this.pendingNodeSelectionClear=!0),ce(e.selection)&&(this.pendingGapCursorClear=!0)}},oi=class{deps;navigationKeymap=null;goalColumn=null;preserveGoalColumn=!1;constructor(e){this.deps=e,this.registerKeymaps()}resetAfterUpdate(){this.preserveGoalColumn||(this.goalColumn=null)}clearGoalColumn(){this.goalColumn=null}destroy(){this.navigationKeymap&&this.deps.keymapRegistry&&(this.deps.keymapRegistry.removeKeymap(this.navigationKeymap),this.navigationKeymap=null)}registerKeymaps(){if(!this.deps.keymapRegistry)return;const e={ArrowLeft:"left",ArrowRight:"right",ArrowUp:"up",ArrowDown:"down"},t={};for(const[n,r]of Object.entries(e))t[n]=()=>this.handleArrow(r);this.navigationKeymap=t,this.deps.keymapRegistry.registerKeymap(t,{priority:"navigation"})}handleArrow(e){const t=this.deps.getState();return!Z(t.selection)&&!ce(t.selection)&&!!Y(t.selection)&&("left"===e||"right"===e?this.handleHorizontalArrow(e):this.handleVerticalArrow(e))}handleHorizontalArrow(e){this.goalColumn=null;const t=this.deps.getState(),n=this.resolveLogicalDirection(t,e),r=et(t,n);if(r)return this.deps.dispatch(r),this.validateSelectionAfterInlineSkip(),!0;if(!Ge(this.deps.contentElement,t,e))return!1;const s=Ye(t,n);return!!s&&(this.deps.dispatch(s),!0)}resolveLogicalDirection(e,t){const n=e.selection;if(!ee(n))return t;const r=this.deps.contentElement.querySelector(`[data-block-id="${n.anchor.blockId}"]`);return r instanceof HTMLElement&&"rtl"===Qt(r)?"left"===t?"right":"left":t}handleVerticalArrow(e){const t=this.deps.getState(),n=this.deps.contentElement.ownerDocument.getSelection?.()??null,r=n?nt(n,this.deps.contentElement):null;if(!Ge(this.deps.contentElement,t,e,r))return!1;null===this.goalColumn&&r&&(this.goalColumn=r.left),this.preserveGoalColumn=!0;const s=Ze(this.deps.contentElement,t,e,this.goalColumn);return s?(this.deps.dispatch(s),this.preserveGoalColumn=!1,!0):(this.preserveGoalColumn=!1,!1)}validateSelectionAfterInlineSkip(){const e=this.deps.getState(),t=sn(this.deps.contentElement);t&&ne(t,e.selection)||an(this.deps.contentElement,e.selection)}};function ai(e,t,n){if(!t)return;const r=/* @__PURE__ */new Set,s=n?.includeRoot??!0,i=(e,o)=>{for(const t of a(e))i(t,!1);if(o&&!s)return;const l=t.get(e.id);l&&(n?.ownerDOM&&l.dom!==n.ownerDOM&&!n.ownerDOM.contains(l.dom)||(li(t,l),r.has(l)||(r.add(l),l.destroy?.())))};i(e,!0)}function li(e,t){for(const[n,r]of e)r===t&&e.delete(n)}function ci(e,t){const n=[];let r=null,s=[];for(const i of e){const e=t.getNodeSpec(i.type)?.wrapper?.(i);e&&r&&e.key===r.key?s.push(i.id):e?(r&&s.length>0&&n.push({spec:r,blockIds:s}),r=e,s=[i.id]):(r&&s.length>0&&n.push({spec:r,blockIds:s}),r=null,s=[])}return r&&s.length>0&&n.push({spec:r,blockIds:s}),n}function di(e,t){if(t.className&&e.className!==t.className&&(e.className=t.className),t.attrs)for(const[n,r]of Object.entries(t.attrs))e.getAttribute(n)!==r&&e.setAttribute(n,r)}function hi(e){const t=document.createElement(e.tag);if(t.setAttribute("data-block-wrapper",e.key),e.className&&(t.className=e.className),e.attrs)for(const[n,r]of Object.entries(e.attrs))t.setAttribute(n,r);return t}function ui(e,t,n){t!==(n?n.nextSibling:e.firstChild)&&(n||t.parentNode!==e||t!==e.firstChild)&&(n?n.after(t):e.insertBefore(t,e.firstChild))}function pi(e,t,n){for(let s=0;s<t.length;s++){const r=t[s];if(!r)continue;const i=n.querySelector(`[data-block-id="${r}"]`);if(!i)continue;const o=e.children[s]??null;i!==o&&(o?e.insertBefore(i,o):e.appendChild(i))}const r=new Set(t);for(const s of Array.from(e.children)){const t=s.getAttribute("data-block-id");t&&!r.has(t)&&n.insertBefore(s,e)}}function mi(e,t,n){if(!n)return;const r=ci(t,n);for(const s of r){const t=e.querySelector(`[data-block-id="${s.blockIds[0]}"]`);if(!t)continue;const n=hi(s.spec);t.before(n);for(const r of s.blockIds){const t=e.querySelector(`[data-block-id="${r}"]`);t&&n.appendChild(t)}}}function fi(e){e.parentElement?.removeChild(e)}function gi(e,t,n){const r=e.parentElement;r?r.replaceChild(t,e):n.replaceChild(t,e)}function yi(e,t,n){if(t?.parentElement){const e=t.parentElement;return void(t.nextSibling?e.insertBefore(n,t.nextSibling):e.appendChild(n))}e.firstChild?e.insertBefore(n,e.firstChild):e.appendChild(n)}function ki(e,t){if(t){const n=t.getInlineNodeSpec(e.inlineType);if(n){const t=n.toDOM(e);return t.setAttribute("contenteditable","false"),t}}const n=document.createElement("span");return n.setAttribute("data-inline-type",e.inlineType),n.setAttribute("contenteditable","false"),n}function wi(e){let t=e.replace(/ {2}/g," ");return t.endsWith(" ")&&(t=`${t.slice(0,-1)} `),t.startsWith(" ")&&(t=` ${t.slice(1)}`),t}var vi=/* @__PURE__ */new WeakMap;function bi(e){const t=/* @__PURE__ */new Map;for(const n of e.querySelectorAll("[data-decoration-widget][data-widget-key][data-widget-block-id]")){const e=n.getAttribute("data-widget-block-id"),r=n.getAttribute("data-widget-key");if(null===e||null===r)continue;const s=pe(e),i=t.get(s)??/* @__PURE__ */new Map,o=i.get(r)??[];o.push(n),i.set(r,o),t.set(s,i)}return t}function Ii(e,t,n,r){let s;if(void 0!==e.key&&(s=function(e,t,n){if(!e||void 0===t)return;const r=e.get(t),s=r?.get(n),i=s?.shift();return 0===s?.length&&r?.delete(n),0===r?.size&&e.delete(t),i}(r?.pool,r?.blockId,e.key),!s)){const t=n.get(e.key);s=t?.shift(),0===t?.length&&n.delete(e.key)}return s??=function(e,t=Or.silent){const n=Ot(e)??{pluginId:"unattributed",name:"widget"},r=t.execute({pluginId:n.pluginId,name:`${n.name}:toDOM`,kind:"widget-render"},()=>{const t=e.toDOM();if(!(t instanceof HTMLElement))throw new TypeError("WidgetDecoration.toDOM must return an HTMLElement.");return t});if(r.ok)return r.value;const s=document.createElement("span");return s.setAttribute("data-widget-render-fallback","true"),s}(e,r?.callbackExecutor),s.setAttribute("data-widget","true"),s.setAttribute("data-decoration-widget","true"),s.setAttribute("data-widget-offset",String(t)),s.setAttribute("data-widget-side",String(e.side)),s.setAttribute("contenteditable","false"),void 0===e.key?s.removeAttribute("data-widget-key"):s.setAttribute("data-widget-key",e.key),r&&s.setAttribute("data-widget-block-id",r.blockId),s}function Si(e){const t=e.nodeName??"span",n=document.createElement(t);if(n.setAttribute("data-decoration","true"),e.class)for(const r of e.class.split(" "))r&&n.classList.add(r);e.style&&Ut(n,e.style);for(const[r,s]of Object.entries(e))"class"!==r&&"style"!==r&&"nodeName"!==r&&void 0!==s&&n.setAttribute(r,s);return n}function xi(e,t,n){Ri(e,t,n)}function Ri(e,t,n){const r=n?.decorations?.findNode(t)??[],s=vi.get(e);if(s&&At(s.decorations,r))return;Ci(e,s);const i=/* @__PURE__ */new Set,o=/* @__PURE__ */new Map;for(const d of r){for(const e of d.attrs.class?.split(/\s+/)??[])e&&i.add(e);for(const[e,t]of Pi(d.attrs.style??""))o.set(e,t)}if(0===i.size&&0===o.size)return void vi.delete(e);const a=/* @__PURE__ */new Set;for(const d of i)e.classList.contains(d)?a.add(d):e.classList.add(d);const l=Pi(qt(e)),c=/* @__PURE__ */new Map;for(const[d,h]of o)c.set(d,l.get(d)??null),l.set(d,h);o.size>0&&Ut(e,Ei(l)),vi.set(e,{decorations:[...r],managed:i,preexisting:a,previousStyles:c})}function Mi(e){Ci(e,vi.get(e)),vi.delete(e)}function Ci(e,t){if(!t)return;for(const r of t.managed)t.preexisting.has(r)||e.classList.remove(r);if(0===t.previousStyles.size)return;const n=Pi(qt(e));for(const[r,s]of t.previousStyles)null===s?n.delete(r):n.set(r,s);Ut(e,Ei(n))}function Pi(e){const t=/* @__PURE__ */new Map;for(const n of e.split(";")){const e=n.trim();if(!e)continue;const r=e.indexOf(":");if(r<=0)continue;const s=Ti(e.slice(0,r)),i=e.slice(r+1).trim();s&&i&&t.set(s,i)}return t}function Ti(e){const t=e.trim();return t.startsWith("--")?t:t.includes("-")?t.toLowerCase():t.replace(/[A-Z]/g,e=>`-${e.toLowerCase()}`).toLowerCase()}function Ei(e){return[...e.entries()].sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>`${e}: ${t}`).join("; ")}var Bi=/* @__PURE__ */new WeakSet;function Ai(e,t){if(e instanceof HTMLElement)return e;throw new TypeError(`${t} must be an HTMLElement.`)}var Ni=/* @__PURE__ */new WeakMap;function Oi(e,t,n,r){const s=r?.decorations?.findInline(e.id),o=r?.decorations?.findWidget(e.id),a=r?.nodeViewRegistry;if(a&&t&&n&&r?.getState&&r?.dispatch){const l=a.getNodeViewEntry(e.type);if(l){const a=function(e,t,n,r,s=Or.silent){const i=s.execute({pluginId:e.pluginId,name:`${e.name}:factory`,kind:"node-view"},()=>function(e,t,n){if("object"!=typeof t&&"function"!=typeof t||null===t)throw new TypeError(`${e.name} NodeView factory must return a NodeView object.`);const r=Ai(t.dom,`${e.name}.dom`),s=t.contentDOM;if(null!==s&&!(s instanceof HTMLElement))throw new TypeError(`${e.name}.contentDOM must be an HTMLElement or null.`);const i=s,o=t.getContentDOM,a=t.update,l=t.destroy,c=t.selectNode,d=t.deselectNode;return{dom:r,contentDOM:i,...o?{getContentDOM(r){const s=n.execute({pluginId:e.pluginId,name:`${e.name}:getContentDOM`,kind:"node-view"},()=>{const n=o.call(t,r);return null===n?null:Ai(n,`${e.name}.getContentDOM`)});return s.ok?s.value:null}}:{},...a?{update(r){const s=n.execute({pluginId:e.pluginId,name:`${e.name}:update`,kind:"node-view"},()=>{const n=a.call(t,r);if("boolean"!=typeof n)throw new TypeError(`${e.name}.update must return a boolean.`);return n});return!!s.ok&&s.value}}:{},...l?{destroy(){Bi.has(t)||(Bi.add(t),n.execute({pluginId:e.pluginId,name:`${e.name}:destroy`,kind:"node-view"},()=>l.call(t)))}}:{},...c?{selectNode(){n.execute({pluginId:e.pluginId,name:`${e.name}:selectNode`,kind:"node-view"},()=>c.call(t)).ok||r.classList.add("notectl-node-selected")}}:{},...d?{deselectNode(){n.execute({pluginId:e.pluginId,name:`${e.name}:deselectNode`,kind:"node-view"},()=>d.call(t)).ok||r.classList.remove("notectl-node-selected")}}:{}}}(e,e.factory(t,n,r),s));return i.ok?i.value:null}(l,e,r.getState,r.dispatch,r.callbackExecutor);if(!a)return Di(e,t,n,r);const c=t.getNodeSpec(e.type);return c?.isVoid&&a.dom.setAttribute("data-void","true"),c?.selectable&&a.dom.setAttribute("data-selectable","true"),a.contentDOM&&a.contentDOM!==a.dom&&a.contentDOM.setAttribute("data-content-dom","true"),i(e)&&a.contentDOM?Hi(a.contentDOM,e,t,s,o,r?.widgetDOMPool,r?.callbackExecutor):$i(e,e=>a.getContentDOM?.(e.id)??a.contentDOM,t,n,r),Li(a.dom,e),a.dom.setAttribute("data-block-type",e.type),xi(a.dom,e.id,r),function(e,t,n){const r=e.get(t);r&&r!==n&&(li(e,r),r.destroy?.()),e.set(t,n)}(n,e.id,a),a.dom}}return Di(e,t,n,r)}function Di(e,t,n,r){const s=r?.decorations?.findInline(e.id),o=r?.decorations?.findWidget(e.id);if(t){const a=t.getNodeSpec(e.type);if(a){const l=a.toDOM(e);return a.isVoid&&l.setAttribute("data-void","true"),a.selectable&&l.setAttribute("data-selectable","true"),a.isVoid||(i(e)?Hi(l,e,t,s,o,r?.widgetDOMPool,r?.callbackExecutor):$i(e,()=>l,t,n,r)),Li(l,e),l.setAttribute("data-block-type",e.type),xi(l,e.id,r),l}}return function(e,t,n,r,s,i){const o=en("p",e.id);return Li(o,e),o.setAttribute("data-block-type",e.type),Hi(o,e,t,n,r,s,i),o}(e,t,s,o,r?.widgetDOMPool,r?.callbackExecutor)}function Li(e,n,r){const s=t(n.htmlId);if(s)return void e.setAttribute("id",s);const i=t(r?.htmlId);i&&e.getAttribute("id")===i&&e.removeAttribute("id")}function Hi(e,t,n,r,s,i,o){const a=[...r??[],...s??[]];(function(e,t,n,r,s=[],i){const o=t.reduce((e,t)=>e+(q(t)?1:t.text.length),0),a=function(e,t){const n=/* @__PURE__ */new Map;for(let s=0;s<e.length;s++){const r=e[s];if(!r)continue;const i=Number.isFinite(r.offset)?r.offset:0,o=Math.max(0,Math.min(t,Math.trunc(i))),a=n.get(o)??[];a.push({decoration:r,index:s}),n.set(o,a)}const r=/* @__PURE__ */new Map;for(const[s,i]of n)i.sort((e,t)=>e.decoration.side-t.decoration.side||e.index-t.index),r.set(s,i.map(e=>e.decoration));return r}(s,o),l=i?.pool?/* @__PURE__ */new Map:function(e){const t=/* @__PURE__ */new Map;for(const n of Array.from(e.children)){if(!(n instanceof HTMLElement&&n.hasAttribute("data-decoration-widget")))continue;const e=n.getAttribute("data-widget-key");if(null===e)continue;const r=t.get(e)??[];r.push(n),t.set(e,r)}return t}(e);e.replaceChildren();const c=t=>{const n=a.get(t);if(n)for(const r of n)e.appendChild(Ii(r,t,l,i))};if(1===t.length&&!q(t[0])&&""===t[0]?.text)return c(0),void e.appendChild(document.createElement("br"));let d=0;for(const u of t){if(q(u)){c(d),e.appendChild(ei(ki(u,r),u.marks,r)),d+=1;continue}const t=d,s=d+u.text.length;if(0===u.text.length){d=s;continue}const i=/* @__PURE__ */new Set;i.add(t),i.add(s);for(const e of n){const n=Math.max(t,e.from),r=Math.min(s,e.to);n>t&&n<s&&i.add(n),r>t&&r<s&&i.add(r)}for(const e of a.keys())e>t&&e<s&&i.add(e);const o=[...i].sort((e,t)=>e-t);for(let a=0;a<o.length-1;a++){const s=o[a],i=o[a+1];if(void 0===s||void 0===i||s>=i)continue;c(s);const l=s-t,d=i-t,h=u.text.slice(l,d),p=[];for(const e of n)e.from<=s&&e.to>=i&&p.push(e);let m=ei(document.createTextNode(wi(h)),u.marks,r);for(const e of p){const t=Si(e.attrs);t.appendChild(m),m=t}e.appendChild(m)}d=s}c(o);const h=t[t.length-1];h&&q(h)&&"hard_break"===h.inlineType&&e.appendChild(document.createElement("br"))})(e,f(t),r??[],n,s??[],{blockId:t.id,pool:i,callbackExecutor:o}),Ni.set(e,a)}function zi(e,t,n,r,s,i){const o=[...r,...s],a=Ni.get(e);a&&At(a,o)||Hi(e,t,n,r,s,void 0,i)}function Fi(e,t){const n=/* @__PURE__ */new Set;e.contentDOM&&n.add(e.contentDOM);for(const r of a(t)){const t=e.getContentDOM?.(r.id);t&&n.add(t)}return[...n]}function ji(e,t,n,r,s,i){const o=/* @__PURE__ */new Set([...n,...Fi(e,t)]);for(const a of o)a.replaceChildren();$i(t,t=>e.getContentDOM?.(t.id)??e.contentDOM,r,s,i)}function $i(e,t,n,r,s){const i=/* @__PURE__ */new Map;for(const o of a(e)){const e=t(o);if(!e)continue;e.appendChild(Oi(o,n,r,s));const a=i.get(e)??[];a.push(o),i.set(e,a)}for(const[o,a]of i)mi(o,a,n)}function _i(e,t,n,r){const s=t?.doc.children??[],o=n.doc.children,a=r?.registry,l=r?.nodeViews,c={...r,widgetDOMPool:bi(e)},d=/* @__PURE__ */new Map;for(const i of s)d.set(i.id,i);const h=null!=r?.compositionBlockId,u=/* @__PURE__ */new Map;for(const i of function(e){const t=[];for(const n of Array.from(e.children))if(n instanceof HTMLElement)if(n.hasAttribute("data-block-id"))t.push(n);else if(n.hasAttribute("data-block-wrapper"))for(const e of Array.from(n.children))e instanceof HTMLElement&&e.hasAttribute("data-block-id")&&t.push(e);return t}(e)){const e=i.getAttribute("data-block-id");e&&u.set(pe(e),i)}const p=new Set(o.map(e=>e.id));for(const[i,y]of u)if(!p.has(i)){const e=d.get(i);e?ai(e,l,{ownerDOM:y}):((l?.get(i))?.destroy?.(),l?.delete(i)),fi(y),u.delete(i)}let m=null;const f=r?.selectedNodeId,g=r?.previousSelectedNodeId;for(const y of o){const t=u.get(y.id),n=d.get(y.id);if(r?.compositionBlockId===y.id&&t)m=t;else{if(t&&n&&!Vi(n,y))m=t;else if(t){const s=l?.get(y.id);let o=!1;if(s&&n){const e=Fi(s,n);if(Mi(s.dom),s.update?.(y)){Li(s.dom,y,n);const d=Ui(n,y);if(d&&ai(n,l,{includeRoot:!1,ownerDOM:t}),i(y)&&s.contentDOM){if(!i(n))for(const n of e)n.replaceChildren();const t=r?.decorations?.findInline(y.id),o=r?.decorations?.findWidget(y.id);Hi(s.contentDOM,y,a,t,o,c.widgetDOMPool,c.callbackExecutor)}else d&&ji(s,y,e,a,l,c);m=s.dom,o=!0}}if(!o){n?ai(n,l,{ownerDOM:t}):s&&(s.destroy?.(),l?.delete(y.id));const r=Oi(y,a,l,c);gi(t,r,e),m=r}}else{const t=Oi(y,a,l,c);yi(e,m,t),m=t}if(f===y.id){const e=l?.get(y.id);if(e)e.selectNode?.();else{const e=u.get(y.id)??m;e instanceof HTMLElement&&e.classList.add("notectl-node-selected")}}else if(g===y.id){const e=l?.get(y.id);if(e)e.deselectNode?.();else{const e=u.get(y.id)??m;e instanceof HTMLElement&&e.classList.remove("notectl-node-selected")}}}}if(g&&g!==f){const e=l?.get(g);e&&!p.has(g)&&e.deselectNode?.()}if(f&&!p.has(f)){const e=l?.get(f);e&&e.selectNode?.()}!h&&a&&function(e,t,n){const r=ci(t,n),s=function(e,t){const n=[],r=/* @__PURE__ */new Set;for(const i of t)for(const e of i.blockIds)r.add(e);let s=0;for(const i of e){if(!r.has(i.id)){n.push({type:"bare",blockId:i.id});continue}const e=t[s];e&&e.blockIds[0]===i.id&&(n.push({type:"wrapper",key:e.spec.key,blockIds:e.blockIds}),s++)}return n}(t,r),i=function(e){const t=[];for(const n of Array.from(e.children))if(n instanceof HTMLElement)if(n.hasAttribute("data-block-wrapper")){const e=n.getAttribute("data-block-wrapper")??"",r=[];for(const t of Array.from(n.children)){if(!(t instanceof HTMLElement))continue;const e=t.getAttribute("data-block-id");e&&r.push(pe(e))}t.push({type:"wrapper",element:n,key:e,blockIds:r})}else if(n.hasAttribute("data-block-id")){const e=n.getAttribute("data-block-id")??"";t.push({type:"bare",element:n,blockId:pe(e)})}return t}(e);if(function(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++){const r=e[n],s=t[n];if(!r||!s)return!1;if(r.type!==s.type)return!1;if("bare"===r.type&&"bare"===s.type){if(r.blockId!==s.blockId)return!1}else if("wrapper"===r.type&&"wrapper"===s.type){if(r.key!==s.key)return!1;if(r.blockIds.length!==s.blockIds.length)return!1;for(let e=0;e<r.blockIds.length;e++)if(r.blockIds[e]!==s.blockIds[e])return!1}}return!0}(s,i)){let e=0;for(const t of i)if("wrapper"===t.type){const n=r[e];n&&di(t.element,n.spec),e++}return}const o=/* @__PURE__ */new Map;for(const d of i){if("wrapper"!==d.type)continue;let e=o.get(d.key);e||(e=[],o.set(d.key,e)),e.push(d.element)}const a=/* @__PURE__ */new Set;let l=null,c=0;for(const d of s){if("bare"===d.type){const t=e.querySelector(`[data-block-id="${d.blockId}"]`);if(!t)continue;t.parentNode!==e?l?l.after(t):e.insertBefore(t,e.firstChild):ui(e,t,l),l=t;continue}const t=r[c];if(!t)continue;c++;const n=o.get(d.key);let s=null;if(n&&n.length>0){const e=n.shift();e&&(s=e.tagName.toLowerCase()===t.spec.tag?e:hi(t.spec))}s||(s=hi(t.spec)),a.add(s),di(s,t.spec),s.parentNode!==e?l?l.after(s):e.insertBefore(s,e.firstChild):ui(e,s,l),pi(s,d.blockIds,e),l=s}for(const d of i)if("wrapper"===d.type&&!a.has(d.element)){for(;d.element.firstChild;)e.insertBefore(d.element.firstChild,d.element);d.element.remove()}}(e,o,a);for(const y of e.querySelectorAll("[data-block-id]")){const e=y.getAttribute("data-block-id");if(!e)continue;const t=pe(e);Ri(y,t,r);const s=n.getBlock(t);if(!s||!i(s))continue;if(r?.compositionBlockId===t)continue;const o=Ki(y,s,a,l);o&&zi(o,s,a,r?.decorations?.findInline(t)??[],r?.decorations?.findWidget(t)??[],r?.callbackExecutor)}}function Ki(e,t,n,r){const s=r?.get(t.id);return s?s.contentDOM:n?.getNodeSpec(t.type)?.isVoid?null:e}function Vi(e,t){return e.id!==t.id||e.type!==t.type||e.htmlId!==t.htmlId||e.children.length!==t.children.length||!z(e.attrs,t.attrs)||Ui(e,t)}function Ui(e,t){if(e.children.length!==t.children.length)return!0;for(let n=0;n<e.children.length;n++){const r=e.children[n],s=t.children[n];if(!r||!s)return!0;if(qi(r,s))return!0}return!1}function qi(e,t){return v(e)&&v(t)?e.text!==t.text||!d(e.marks,t.marks):q(e)&&q(t)?e.inlineType!==t.inlineType||!function(e,t){const n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(const s of n)if(e[s]!==t[s])return!1;return!0}(e.attrs,t.attrs)||!d(e.marks,t.marks):!!(v(e)||v(t)||q(e)||q(t))||Vi(e,t)}var Wi=class{state;contentElement;history;stateChangeCallbacks=[];isUpdating=!1;schemaRegistry;nodeViewRegistry;callbackExecutor;nodeViews=/* @__PURE__ */new Map;decorations=Lt.empty;getDecorations;isReadOnly;isReadonlyBypassed;compositionState;cursorWrapper;navigation;events;constructor(e,t){this.state=t.state,this.contentElement=e,this.schemaRegistry=t.schemaRegistry,this.nodeViewRegistry=t.nodeViewRegistry,this.callbackExecutor=t.callbackExecutor??Or.silent,this.getDecorations=t.getDecorations,this.isReadOnly=t.isReadOnly??(()=>!1),this.isReadonlyBypassed=t.isReadonlyBypassed??(()=>!1),this.compositionState=t.compositionState??{isComposing:!1,activeBlockId:null},this.history=new Ws({maxDepth:t.maxHistoryDepth??100}),t.onStateChange&&this.stateChangeCallbacks.push(t.onStateChange),this.cursorWrapper=new ni(e,this.schemaRegistry),this.navigation=new oi({contentElement:e,getState:()=>this.state,dispatch:e=>this.dispatch(e),keymapRegistry:t.keymapRegistry}),this.events=new ii({contentElement:e,getState:()=>this.state,dispatch:e=>this.dispatch(e),applyUpdate:(e,t,n)=>this.applyUpdate(e,t,{skipSelectionSync:n}),isUpdating:()=>this.isUpdating,compositionState:this.compositionState,cursorWrapper:this.cursorWrapper,isReadOnly:this.isReadOnly,fileHandlerRegistry:t.fileHandlerRegistry,callbackExecutor:this.callbackExecutor,onMousedown:()=>this.navigation.clearGoalColumn()}),this.decorations=this.getDecorations?.(this.state)??Lt.empty,_i(e,null,this.state,{...this.reconcileOptions(),decorations:this.decorations}),an(e,this.state.selection)}getState(){return this.state}applyUpdate(e,t,n){if(!this.isUpdating){this.isUpdating=!0;try{const r=this.state,s=xs(t,r.doc);this.state=e,this.events.onStateChange(r,e,s),this.cursorWrapper.isActive&&!e.storedMarks?.length&&this.cursorWrapper.cleanup(),(n?.pushHistory&&"history"!==s.metadata.origin||Xs(s))&&this.history.push(s);const i=this.getDecorations?.(e,s)??Lt.empty;this.reconcileAndSync(r,e,i,n?.skipSelectionSync);for(const t of this.stateChangeCallbacks)t(r,e,s);this.navigation.resetAfterUpdate()}finally{this.isUpdating=!1}}}dispatch(e){const t=xs(e,this.state.doc);if(this.isReadOnly()&&!Ys(t)&&!this.isReadonlyBypassed())return;const n=this.state.apply(t);this.applyUpdate(n,t,{pushHistory:!0})}undo(){if(this.isUpdating||this.isReadOnly())return;const e=this.history.undo(this.state);e&&this.applyUpdate(e.state,e.transaction)}redo(){if(this.isUpdating||this.isReadOnly())return;const e=this.history.redo(this.state);e&&this.applyUpdate(e.state,e.transaction)}onStateChange(e){return this.stateChangeCallbacks.push(e),()=>{const t=this.stateChangeCallbacks.indexOf(e);-1!==t&&this.stateChangeCallbacks.splice(t,1)}}replaceState(e){if(!this.isUpdating){this.isUpdating=!0;try{const t=this.state,n=e.withSelection(t.selection);this.state=n,this.history.clear(),this.cursorWrapper.isActive&&!n.storedMarks?.length&&this.cursorWrapper.cleanup();const r=Wn({steps:[],selectionBefore:t.selection,selectionAfter:n.selection,storedMarksAfter:n.storedMarks,forwardStepMaps:[],metadata:{origin:"api",timestamp:Date.now()}});this.events.onStateChange(t,n,r);const s=this.getDecorations?.(n,r)??Lt.empty;this.reconcileAndSync(t,n,s);for(const e of this.stateChangeCallbacks)e(t,n,r);this.navigation.resetAfterUpdate()}finally{this.isUpdating=!1}}}syncSelection(){this.events.syncSelectionFromDOM()}resolveDOMRange(e){return rn(this.contentElement,e)}reconcileAndSync(e,t,n,r){const s=this.decorations;this.decorations=n,_i(this.contentElement,e,t,{...this.reconcileOptions(e.selection),decorations:n,oldDecorations:s,compositionBlockId:this.compositionState.isComposing?this.compositionState.activeBlockId??void 0:void 0}),this.compositionState.isComposing||r||an(this.contentElement,t.selection)}reconcileOptions(e){const t=Z(this.state.selection)?this.state.selection.nodeId:void 0,n=e&&Z(e)?e.nodeId:void 0;return{registry:this.schemaRegistry,nodeViewRegistry:this.nodeViewRegistry,nodeViews:this.nodeViews,getState:()=>this.state,dispatch:e=>this.dispatch(e),callbackExecutor:this.callbackExecutor,selectedNodeId:t,previousSelectedNodeId:n}}destroy(){this.cursorWrapper.cleanup(),this.events.destroy(),this.navigation.destroy(),function(e){const t=/* @__PURE__ */new Set;for(const n of e.values())t.has(n)||(t.add(n),n.destroy?.());e.clear()}(this.nodeViews)}},Gi={paragraph:"Paragraph",heading:"Heading",code_block:"Code Block",blockquote:"Block Quote",list_item:"List Item",horizontal_rule:"Horizontal Rule",image:"Image",table:"Table"};function Qi(e,t){return"heading"===e&&t?.level?`Heading ${t.level}`:Gi[e]??e}function Ji(e){e.registerNodeSpec({type:"paragraph",group:"block",content:{allow:["text"]},toDOM:e=>en("p",e.id),toHTML:(e,t)=>`<p>${t||"<br>"}</p>`,parseHTML:[{tag:"p"},{tag:"div",priority:10}],sanitize:{tags:["p"]}})}var Xi={ariaLabel:"Rich text editor",ariaDescription:"Press Escape to exit the editor",defaultPlaceholder:"Start typing...",markdownImported:"Markdown imported"},Yi=/* #__PURE__ */Object.assign({"./locales/ar.ts":()=>import("./ar-eOA3UmiE.mjs"),"./locales/de.ts":()=>import("./de-DRbhnS4T.mjs"),"./locales/es.ts":()=>import("./es-BQ9dox_E.mjs"),"./locales/fr.ts":()=>import("./fr-NVOinLyF.mjs"),"./locales/hi.ts":()=>import("./hi-DrC2H81d.mjs"),"./locales/pt.ts":()=>import("./pt-CFrcl1v_.mjs"),"./locales/ru.ts":()=>import("./ru-gxbzqLL8.mjs"),"./locales/zh.ts":()=>import("./zh-BFZOM3lF.mjs")}),Zi=["\n/**\n * Public theme tokens.\n *\n * Declared via @property so that:\n * - DevTools surfaces them as first-class CSS variables,\n * - invalid values are rejected at the engine level instead of breaking\n * downstream rules silently,\n * - the values are interpolatable for animations.\n *\n * The registration is scoped to this shadow root. Consumers override these\n * by setting the same custom properties on a parent (e.g. ::host).\n *\n * Components use the three-tier cascade:\n * var(--notectl-<component>-<prop>, var(--notectl-<prop>, <fallback>))\n */\n@property --notectl-bg { syntax: '<color>'; initial-value: #ffffff; inherits: true; }\n@property --notectl-fg { syntax: '<color>'; initial-value: #1f2328; inherits: true; }\n@property --notectl-fg-muted { syntax: '<color>'; initial-value: #6e7781; inherits: true; }\n@property --notectl-border { syntax: '<color>'; initial-value: #d0d7de; inherits: true; }\n@property --notectl-border-focus { syntax: '<color>'; initial-value: #0969da; inherits: true; }\n@property --notectl-primary { syntax: '<color>'; initial-value: #0969da; inherits: true; }\n@property --notectl-primary-fg { syntax: '<color>'; initial-value: #ffffff; inherits: true; }\n@property --notectl-accent-fg { syntax: '<color>'; initial-value: #0969da; inherits: true; }\n@property --notectl-focus-ring { syntax: '<color>'; initial-value: rgba(9, 105, 218, 0.3); inherits: true; }\n\n:host {\n\tdisplay: block;\n\tfont-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;\n\tfont-size: 16px;\n\tline-height: 1.6;\n\tcolor: var(--notectl-fg);\n}\n\n.notectl-editor {\n\tdisplay: flex;\n\tflex-direction: column;\n\tborder: 1px solid var(--notectl-border);\n\tborder-radius: var(--notectl-border-radius, 6px);\n\toverflow: hidden;\n\tbackground: var(--notectl-bg);\n\t/* Fill any explicit host height so embedders can size <notectl-editor>\n\t (e.g. height: 500px) and have the toolbar/content/footer fit inside.\n\t border-box keeps the 1px border within the host's height; min-height: 0\n\t lets the flex content shrink below its intrinsic size so internal\n\t scrolling can engage. */\n\tbox-sizing: border-box;\n\theight: 100%;\n\tmin-height: 0;\n}\n\n.notectl-editor:focus-within {\n\tborder-color: var(--notectl-border-focus);\n\tbox-shadow: 0 0 0 2px var(--notectl-focus-ring);\n}\n\n/* Content Area */\n.notectl-content {\n\tflex: 1;\n\tpadding: 12px 16px;\n\toutline: none;\n\tmin-height: var(--notectl-content-min-height, 400px);\n\tmax-height: var(--notectl-content-max-height, none);\n\toverflow-y: auto;\n\tcursor: text;\n\tposition: relative;\n\twhite-space: pre-wrap;\n\tword-wrap: break-word;\n\t-webkit-user-select: text;\n\tuser-select: text;\n\t-moz-tab-size: 4;\n\ttab-size: 4;\n}\n\n.notectl-content p {\n\tmargin: 0;\n\tpadding: 2px 0;\n\tmin-height: 1.6em;\n}\n\n.notectl-content p + p {\n\tmargin-top: 0;\n}\n\n/* Horizontal Rule */\n.notectl-content hr {\n\tborder: none;\n\tborder-top: 1px solid var(--notectl-border);\n\tmargin: 8px 0;\n\tpadding: 0;\n\tcursor: default;\n\tuser-select: none;\n}\n\n/* Placeholder */\n.notectl-content.notectl-content--empty::before {\n\tcontent: attr(data-placeholder);\n\tcolor: var(--notectl-fg-muted);\n\tpointer-events: none;\n\tposition: absolute;\n\ttop: 12px;\n\tinset-inline-start: 16px;\n}\n\n/* Plugin container bottom */\n.notectl-plugin-container--bottom {\n\tborder-top: 1px solid var(--notectl-border);\n\tflex-shrink: 0;\n}\n\n/* Screen reader announcements */\n.notectl-sr-only {\n\tposition: absolute;\n\twidth: 1px;\n\theight: 1px;\n\tmargin: -1px;\n\tpadding: 0;\n\toverflow: hidden;\n\tclip: rect(0, 0, 0, 0);\n\twhite-space: nowrap;\n\tborder: 0;\n}\n\n/* Node selection */\n.notectl-node-selected {\n\toutline: 2px solid var(--notectl-primary);\n\toutline-offset: 2px;\n}\n\n/* High-contrast / forced-colors mode (Windows High Contrast, etc.) */\n@media (forced-colors: active) {\n\t.notectl-editor {\n\t\tborder-color: CanvasText;\n\t}\n\t.notectl-editor:focus-within {\n\t\tborder-color: Highlight;\n\t\tbox-shadow: 0 0 0 2px Highlight;\n\t}\n\t.notectl-content {\n\t\tcolor: CanvasText;\n\t}\n\t.notectl-plugin-container--top,\n\t.notectl-plugin-container--bottom {\n\t\tborder-color: CanvasText;\n\t}\n\t.notectl-node-selected {\n\t\toutline-color: Highlight;\n\t}\n}\n","\n@media (prefers-reduced-motion: reduce) {\n\t.notectl-toolbar-btn,\n\t.notectl-image__resize-handle,\n\t.notectl-image__size-indicator,\n\t.notectl-color-picker__swatch,\n\t.notectl-font-picker__item,\n\t.notectl-heading-picker__item,\n\t.notectl-font-size-picker__item,\n\t.ntbl-handle,\n\t.ntbl-handle-delete,\n\t.ntbl-insert-line,\n\t.ntbl-insert-btn,\n\t.ntbl-add-zone,\n\t.ntbl-add-icon,\n\t.ntbl-col-bar,\n\t.ntbl-row-bar,\n\t.ntbl-delete-table-btn,\n\t.notectl-code-block__copy {\n\t\ttransition: none !important;\n\t}\n}\n",'\n/* Paper viewport: scroll container with centered gray background */\n.notectl-paper-viewport {\n\tflex: 1;\n\toverflow-y: auto;\n\toverflow-x: hidden;\n\tbackground: var(--notectl-paper-viewport-bg, #e8e8e8);\n\tpadding: 24px 0;\n}\n\n/* Paper surface: white page with shadow, centered */\n.notectl-paper-surface {\n\tmargin: 0 auto;\n\tbackground: var(--notectl-bg);\n\tborder-radius: 2px;\n\tbox-shadow: 0 2px 8px var(--notectl-shadow, rgba(0, 0, 0, 0.15));\n\ttransform-origin: top center;\n\ttransition: transform 0.15s ease-out;\n}\n\n/* Content overrides in paper mode: wider document margins */\n.notectl-editor[data-paper-mode] .notectl-content {\n\tflex: none;\n\tpadding: 48px 56px;\n\tmin-height: auto;\n}\n\n/* Placeholder position override for paper mode */\n.notectl-editor[data-paper-mode] .notectl-content.notectl-content--empty::before {\n\ttop: 48px;\n\tinset-inline-start: 56px;\n}\n\n/* Dark mode: darker viewport background */\n:host([theme="dark"]) .notectl-paper-viewport {\n\t--notectl-paper-viewport-bg: #181825;\n}\n\n@media (prefers-reduced-motion: reduce) {\n\t.notectl-paper-surface {\n\t\ttransition: none !important;\n\t}\n}\n'].join("\n"),eo=null,to=class{themeStyleSheet=new CSSStyleSheet;systemThemeQuery=null;systemThemeHandler=null;pluginSheets=[];runtimeSheets=[];shadow;constructor(e){this.shadow=e}apply(e){if(this.cleanupSystemThemeListener(),e===at.System){this.setupSystemThemeListener();const e=mt(this.getSystemTheme());this.setThemeStyleSheet(e)}else this.setThemeStyleSheet(mt(e))}setPluginStyleSheets(e){this.pluginSheets=e,this.refreshAdoptedStyleSheets()}setRuntimeStyleSheets(e){this.runtimeSheets=e,this.refreshAdoptedStyleSheets()}destroy(){this.cleanupSystemThemeListener()}setThemeStyleSheet(e){this.themeStyleSheet.replaceSync(ut(e)),this.refreshAdoptedStyleSheets()}refreshAdoptedStyleSheets(){this.shadow.adoptedStyleSheets=[this.themeStyleSheet,(eo||(eo=new CSSStyleSheet).replaceSync(Zi),eo),...this.pluginSheets,...this.runtimeSheets]}setupSystemThemeListener(){this.systemThemeQuery=window.matchMedia("(prefers-color-scheme: dark)"),this.systemThemeHandler=e=>{const t=mt(this.getSystemTheme());this.setThemeStyleSheet(t)},this.systemThemeQuery.addEventListener("change",this.systemThemeHandler)}cleanupSystemThemeListener(){this.systemThemeQuery&&this.systemThemeHandler&&this.systemThemeQuery.removeEventListener("change",this.systemThemeHandler),this.systemThemeQuery=null,this.systemThemeHandler=null}getSystemTheme(){return(this.systemThemeQuery??window.matchMedia("(prefers-color-scheme: dark)")).matches?at.Dark:at.Light}},no=class{wrapper;content;viewport=null;surface=null;viewportObserver=null;surfaceObserver=null;currentSize=null;currentPaperWidthPx=0;currentPaperHeightPx=0;currentScale=1;compensationFrameId=null;constructor(e,t){this.wrapper=e,this.content=t}apply(e){if(null===e)return void this.disable();const t=dt(e);this.currentPaperWidthPx=t.widthPx,this.currentPaperHeightPx=t.heightPx,this.currentSize=e,this.viewport||this.enable(),this.updateSurfaceDimensions(),this.wrapper.setAttribute("data-paper-mode",e)}destroy(){this.disable()}getPaperSize(){return this.currentSize}enable(){this.viewport=document.createElement("div"),this.viewport.className="notectl-paper-viewport",this.surface=document.createElement("div"),this.surface.className="notectl-paper-surface",this.wrapper.removeChild(this.content),this.surface.appendChild(this.content),this.viewport.appendChild(this.surface);const e=this.wrapper.querySelector(".notectl-plugin-container--bottom");e?this.wrapper.insertBefore(this.viewport,e):this.wrapper.appendChild(this.viewport),this.viewportObserver=new ResizeObserver(e=>{for(const t of e)this.onViewportResize(t.contentRect.width)}),this.viewportObserver.observe(this.viewport),this.surfaceObserver=new ResizeObserver(e=>{for(const t of e)this.onSurfaceResize(t.contentRect.height)}),this.surfaceObserver.observe(this.surface)}disable(){if(null!==this.compensationFrameId&&(cancelAnimationFrame(this.compensationFrameId),this.compensationFrameId=null),this.viewportObserver?.disconnect(),this.viewportObserver=null,this.surfaceObserver?.disconnect(),this.surfaceObserver=null,this.viewport&&this.surface){this.surface.removeChild(this.content);const e=this.wrapper.querySelector(".notectl-plugin-container--bottom");e?this.wrapper.insertBefore(this.content,e):this.wrapper.appendChild(this.content),this.wrapper.removeChild(this.viewport)}this.viewport=null,this.surface=null,this.currentSize=null,this.currentPaperWidthPx=0,this.currentPaperHeightPx=0,this.currentScale=1,this.wrapper.removeAttribute("data-paper-mode")}updateSurfaceDimensions(){this.surface&&(Vt(this.surface,"width",`${this.currentPaperWidthPx}px`),Vt(this.surface,"minHeight",`${this.currentPaperHeightPx}px`))}onViewportResize(e){if(!this.surface||0===this.currentPaperWidthPx)return;const t=e-48,n=Math.min(1,t/this.currentPaperWidthPx);this.currentScale=n,Vt(this.surface,"transform",n<1?`scale(${n})`:""),this.scheduleHeightCompensation(n)}onSurfaceResize(e){this.surface&&this.viewport&&this.scheduleHeightCompensation(this.currentScale)}scheduleHeightCompensation(e){null!==this.compensationFrameId&&cancelAnimationFrame(this.compensationFrameId),this.compensationFrameId=requestAnimationFrame(()=>{this.compensationFrameId=null,this.updateHeightCompensation(e)})}updateHeightCompensation(e){if(!this.surface)return;if(e>=1)return void Vt(this.surface,"marginBottom","");const t=this.surface.scrollHeight,n=t*e-t;Vt(this.surface,"marginBottom",`${n}px`)}};function ro(e){return!Array.isArray(e)}function so(e){if(Array.isArray(e))return{plugins:e,label:void 0};const t=e;return{plugins:t.plugins,label:t.label}}var io=class{deps;cfg;themeController=null;styleLease=null;domElements=null;paperLayout=null;pluginManager=null;inputManager=null;view=null;locale=Xi;domEventTarget=null;autofocusFrameId=null;cleanedUp=!1;handleFocus=()=>this.deps.events.emit("focus",void 0);handleBlur=()=>this.deps.events.emit("blur",void 0);constructor(e){this.deps=e,this.cfg=e.config}announce(e){const t=this.domElements?.announcer;t&&(t.textContent=e)}async run(){try{if(this.setupTheme(),this.isCancelled())return this.abort();const e=await async function(e){const t=new Ft(e.locale??"browser").getLocale();return"en"===t?Xi:await async function(e){return zt(Yi,e,Xi)}(t)}(this.cfg);return this.isCancelled()?this.abort():(this.locale=e,this.setupDOM(e),this.setupPlugins(),await this.initPluginsAndView(),!this.isCancelled()&&this.view&&this.inputManager&&this.pluginManager&&this.domElements&&this.themeController&&this.styleLease?(this.finalizeSetup(this.pluginManager,this.domElements),this.release()):this.abort())}catch(e){throw await this.cleanup(),e}}setupTheme(){this.themeController=new to(this.deps.shadow),this.styleLease=this.deps.styleCoordinator.setup(this.deps.shadow,this.cfg.styleNonce,this.themeController),this.themeController.apply(this.cfg.theme??at.Light)}setupDOM(e){this.domElements=function(e){const t=e.locale??Xi,n=t.defaultPlaceholder,r=document.createElement("div");r.className="notectl-editor",r.setAttribute("part","editor");const s=document.createElement("div");s.className="notectl-plugin-container--top",s.setAttribute("part","plugin-container plugin-container-top"),s.setAttribute("data-notectl-no-print","");const i=document.createElement("div");i.className="notectl-content",i.setAttribute("part","content"),i.contentEditable=e.readonly?"false":"true",i.setAttribute("role","textbox"),i.setAttribute("aria-multiline","true"),i.setAttribute("aria-label",t.ariaLabel),e.readonly&&i.setAttribute("aria-readonly","true"),i.setAttribute("aria-description",t.ariaDescription),i.setAttribute("data-default-placeholder",n),i.setAttribute("data-placeholder",e.placeholder??n),e.dir&&(r.setAttribute("dir",e.dir),i.setAttribute("dir",e.dir));const o=document.createElement("div");o.className="notectl-plugin-container--bottom",o.setAttribute("part","plugin-container plugin-container-bottom"),o.setAttribute("data-notectl-no-print","");const a=document.createElement("div");return a.className="notectl-sr-only",a.setAttribute("data-notectl-no-print",""),a.setAttribute("aria-live","polite"),a.setAttribute("aria-atomic","true"),r.appendChild(s),r.appendChild(i),r.appendChild(o),r.appendChild(a),{wrapper:r,content:i,topPluginContainer:s,bottomPluginContainer:o,announcer:a}}({readonly:this.cfg.readonly,placeholder:this.cfg.placeholder,dir:this.cfg.dir??this.deps.hostDir,locale:e}),this.deps.shadow.appendChild(this.domElements.wrapper),this.cfg.paperSize&&(this.paperLayout=new no(this.domElements.wrapper,this.domElements.content),this.paperLayout.apply(this.cfg.paperSize))}setupPlugins(){if(this.domElements){this.pluginManager=new Us({logger:this.cfg.logger}),this.pluginManager.registerService(jt,new Ft(this.cfg.locale??"browser")),Ji(this.pluginManager.schemaRegistry),function(e,t){if(!t)return;const n=ro(t)?t.groups:t,r=ro(t)?t.overflow:void 0,s=[];for(const o of n){const{plugins:t,label:n}=so(o),r=[];for(const s of t)r.push(s.id),e.register(s);s.push(void 0!==n?{plugins:r,label:n}:r)}const i={groups:s,overflow:r};e.register(new Zt(i))}(this.pluginManager,this.cfg.toolbar);for(const e of this.cfg.plugins??[])this.pluginManager.register(e);for(const e of this.deps.preInitPlugins)this.pluginManager.register(e);e=this.pluginManager,t=this.cfg.features,function(e,t){if(void 0!==e.get("text-formatting"))return;const n={bold:t?.bold??!0,italic:t?.italic??!0,underline:t?.underline??!0};e.register(new hn(n))}(e,t),function(e){void 0===e.get("caret-navigation")&&e.register(new rt)}(e),function(e){void 0===e.get("gap-cursor")&&e.register(new dn)}(e),this.domEventTarget=this.domElements.content,this.domEventTarget.addEventListener("focus",this.handleFocus),this.domEventTarget.addEventListener("blur",this.handleBlur)}var e,t}async initPluginsAndView(){if(!this.pluginManager||!this.domElements||!this.themeController)return;const e=this.domElements,t=this.pluginManager,n=this.themeController;await t.init({isCancelled:()=>this.isCancelled(),getState:()=>{if(!this.view)throw new Error("View not initialized");return this.view.getState()},dispatch:e=>this.dispatch(e),getContainer:()=>e.content,getPluginContainer:t=>"top"===t?e.topPluginContainer:e.bottomPluginContainer,announce:e=>this.announce(e),hasAnnouncement:()=>!!e.announcer?.textContent,getCompositionState:()=>{const e=this.inputManager?.compositionTracker;return e||oo},onBeforeReady:()=>this.createInputAndView(e,t,n)})}createInputAndView(e,t,n){if(this.isCancelled()||!this.pluginManager||!this.themeController)return;const r=Ve(t.schemaRegistry),s=dr.create({schema:r}),i=this.deps.configController.markdownShorthand;this.inputManager=new ws(e.content,{getState:()=>{if(!this.view)throw new Error("View not initialized");return this.view.getState()},dispatch:e=>this.dispatch(e),syncSelection:()=>this.view?.syncSelection(),undo:()=>this.view?.undo(),redo:()=>this.view?.redo(),schemaRegistry:t.schemaRegistry,keymapRegistry:t.keymapRegistry,inputRuleRegistry:t.inputRuleRegistry,fileHandlerRegistry:t.fileHandlerRegistry,isReadOnly:()=>this.deps.configController.isReadOnly,shouldApplyInputRules:()=>i,getPasteInterceptors:()=>t.getPasteInterceptors(),pasteMarkdown:this.deps.configController.pasteMarkdown,getMarkdownSyntaxExtensions:()=>t.markdownSyntaxRegistry.getExtensions(),getTextInputInterceptors:()=>t.getTextInputInterceptors(),getTextDirection:Qt,navigateFromGapCursor:cn,announce:e=>this.announce(e),markdownImportedMessage:this.locale.markdownImported,callbackExecutor:t.getCallbackExecutor(),resolveTargetRange:e=>this.view?.resolveDOMRange(e)??null}),this.view=new Wi(e.content,{state:s,schemaRegistry:t.schemaRegistry,keymapRegistry:t.keymapRegistry,fileHandlerRegistry:t.fileHandlerRegistry,callbackExecutor:t.getCallbackExecutor(),nodeViewRegistry:t.nodeViewRegistry,maxHistoryDepth:this.cfg.maxHistoryDepth,getDecorations:(e,n)=>t.collectDecorations(e,n)??Lt.empty,onStateChange:(n,r,s)=>{this.inputManager?.onStateChange(n,r,s),function(e,t,n,r,s,i){const o=r.announcer;if(o&&(o.textContent=""),s.notifyStateChange(e,t,n),ao(r.content,t.doc),i.emit("stateChange",{oldState:e,newState:t,transaction:n}),ne(e.selection,t.selection)||i.emit("selectionChange",{selection:t.selection}),!o?.textContent){const r=function(e,t,n){if("undo"===n.metadata.historyDirection)return"Undo";if("redo"===n.metadata.historyDirection)return"Redo";for(const r of n.steps)if("setBlockType"===r.type)return Qi(r.nodeType,r.attrs);for(const r of t.schema.markTypes){const n=he(r),s=We(e,n),i=We(t,n);if(s!==i)return`${r} ${i?"on":"off"}`}return null}(e,t,n);r&&o&&(o.textContent=r)}}(n,r,s,e,t,this.deps.events)},isReadOnly:()=>this.deps.configController.isReadOnly,isReadonlyBypassed:()=>t.isReadonlyBypassed(),compositionState:this.inputManager.compositionTracker}),ao(e.content,this.view.getState().doc);const o=t.getPluginStyleSheets();o.length>0&&n.setPluginStyleSheets(o)}finalizeSetup(e,t){if(this.cfg.readonly&&e.setReadOnly(!0),e.onEvent(ht,e=>{!e.options.paperSize&&this.deps.configController.getPaperSize()&&(e.options={...e.options,paperSize:this.deps.configController.getPaperSize()})}),this.cfg.autofocus){const e=t.content;this.autofocusFrameId=requestAnimationFrame(()=>{this.autofocusFrameId=null,this.cleanedUp||e.focus()})}}dispatch(e){this.view&&this.pluginManager&&this.pluginManager.dispatchWithMiddleware(e,this.view.getState(),e=>this.view?.dispatch(e))}isCancelled(){return this.deps.isCancelled?.()??!1}release(){const e=this.view,t=this.inputManager,n=this.pluginManager,r=this.domElements,s=this.themeController,i=this.styleLease;if(!(e&&t&&n&&r&&s&&i))throw new Error("Cannot release an incomplete editor initialization session.");return{view:e,pluginManager:n,domElements:r,themeController:s,paperLayout:this.paperLayout,announce:e=>this.announce(e),markdownImportedMessage:this.locale.markdownImported,dispose:()=>this.cleanup()}}async abort(){return await this.cleanup(),null}async cleanup(){if(this.cleanedUp)return;this.cleanedUp=!0,null!==this.autofocusFrameId&&(cancelAnimationFrame(this.autofocusFrameId),this.autofocusFrameId=null),this.domEventTarget?.removeEventListener("focus",this.handleFocus),this.domEventTarget?.removeEventListener("blur",this.handleBlur),this.domEventTarget=null;const e=this.view;this.view=null,this.paperLayout?.destroy(),this.paperLayout=null,this.deps.styleCoordinator.teardown(this.styleLease),this.styleLease=null,this.themeController?.destroy(),this.themeController=null,this.inputManager?.destroy(),this.inputManager=null,e?.destroy();const t=this.pluginManager;this.pluginManager=null;const n=t?.destroy()??Promise.resolve();this.domElements?.wrapper.remove(),this.domElements=null,await n}},oo={isComposing:!1,activeBlockId:null};function ao(e,t){e.classList.toggle("notectl-content--empty",br(t))}var lo=class extends Error{constructor(){super("Editor initialization was aborted because the editor was destroyed."),this.name="AbortError"}},co=class{state="idle";readyPromiseResolve=null;readyPromiseReject=null;readyPromise;preInitPlugins=[];constructor(){this.readyPromise=this.createReadyPromise()}isInitialized(){return"initializing"===this.state||"ready"===this.state}markInitialized(){return"initializing"!==this.state&&"ready"!==this.state&&("failed"===this.state&&(this.readyPromise=this.createReadyPromise()),this.state="initializing",!0)}whenReady(){return this.readyPromise}resolveReady(){"initializing"===this.state&&(this.state="ready",this.readyPromiseResolve?.(),this.readyPromiseResolve=null,this.readyPromiseReject=null)}failReady(e){"initializing"===this.state&&(this.state="failed",this.readyPromiseReject?.(e),this.readyPromiseResolve=null,this.readyPromiseReject=null)}registerPreInitPlugin(e){if("initializing"===this.state||"ready"===this.state)throw new Error("Cannot register plugins after initialization. Register before calling init() or adding to DOM.");this.preInitPlugins.push(e)}consumePreInitPlugins(){const e=this.preInitPlugins;return this.preInitPlugins=[],e}restorePreInitPlugins(e){0!==e.length&&(this.preInitPlugins=[...e,...this.preInitPlugins])}reset(){this.readyPromiseReject?.(new lo),this.state="idle",this.preInitPlugins=[],this.readyPromise=this.createReadyPromise()}createReadyPromise(){const e=new Promise((e,t)=>{this.readyPromiseResolve=e,this.readyPromiseReject=t});return e.catch(()=>{}),e}},ho=class{runtimeStyleSheet=null;activeLease=null;setup(e,t,n){this.activeLease?this.release(this.activeLease):Gt(e),this.runtimeStyleSheet=Wt();const r={id:Symbol("notectl-style-lease"),shadow:e,themeController:n};return this.activeLease=r,n?.setRuntimeStyleSheets(this.runtimeStyleSheet?[this.runtimeStyleSheet]:[]),Kt(e,{nonce:t,sheet:this.runtimeStyleSheet}),r}teardown(e){e&&this.activeLease===e&&this.release(e)}release(e){Gt(e.shadow),this.runtimeStyleSheet=null,e.themeController?.setRuntimeStyleSheets([]),this.activeLease===e&&(this.activeLease=null)}},uo=class extends HTMLElement{view=null;pluginManager=null;domElements=null;configController=new Rr;events=new Er;lifecycle=new co;styleCoordinator=new ho;themeController=null;paperLayout=null;activeInitResult=null;pendingInitPromise=null;pendingDestroyPromise=null;cancelPendingInit=null;autoInitToken=0;autoInitQueued=!1;initVersion=0;destroyVersion=0;announce=null;markdownImportedMessage="Markdown imported";static get observedAttributes(){return["placeholder","readonly","theme","paper-size","dir"]}connectedCallback(){ot(this)||this.lifecycle.isInitialized()||this.scheduleAutoInit()}disconnectedCallback(){setTimeout(()=>{this.isConnected||this.destroy()},0)}attributeChangedCallback(e,t,n){this.configController.applyAttribute(e,n,this.getConfigDeps())}registerPlugin(e){this.lifecycle.registerPreInitPlugin(e)}async init(e){if(ot(this))throw ft();this.cancelAutoInit();const t=this.destroyVersion,n=this.pendingDestroyPromise;if(n&&(await n,t!==this.destroyVersion))throw new lo;const r=this.pendingInitPromise;if(r){if(await r,e)throw new Error("Cannot apply init config while another initialization is in progress. Await the active init, then destroy and initialize a new generation.");return}if(!this.lifecycle.markInitialized()){if(e)throw new Error("Cannot apply init config after the editor is initialized. Use configure() for runtime options or destroy() before re-initializing.");return}let s;e&&this.configController.setConfig(e),this.events.setLogger(this.configController.getConfig().logger);try{s=this.ensureFreshShadowRoot()}catch(d){throw this.lifecycle.failReady(d),d}const i=++this.initVersion;let o=!1;this.cancelPendingInit=()=>{o=!0};const a=this.lifecycle.consumePreInitPlugins(),l=async function(e){return new io(e).run()}({shadow:s,config:this.configController.getConfig(),hostDir:this.getAttribute("dir")??void 0,configController:this.configController,styleCoordinator:this.styleCoordinator,events:this.events,preInitPlugins:a,isCancelled:()=>o||i!==this.initVersion}),c=this.completeInitialization(l,i,()=>o||i!==this.initVersion,a);this.pendingInitPromise=c;try{await c}finally{this.pendingInitPromise===c&&(this.pendingInitPromise=null,this.cancelPendingInit=null)}}async completeInitialization(e,t,n,r){let s=null;try{const r=await e;if(!r){if(n())throw new lo;throw new Error("Editor initialization completed without a result.")}if(t!==this.initVersion)throw await r.dispose(),new lo;if(this.activeInitResult=r,s=r,this.view=r.view,this.pluginManager=r.pluginManager,this.domElements=r.domElements,this.themeController=r.themeController,this.paperLayout=r.paperLayout,this.announce=r.announce,this.markdownImportedMessage=r.markdownImportedMessage,this.lifecycle.resolveReady(),this.events.emit("ready",void 0),t!==this.initVersion)throw new lo}catch(i){throw s&&this.activeInitResult===s&&(this.activeInitResult=null,this.clearPublishedRuntime(),await s.dispose()),t===this.initVersion&&(this.lifecycle.restorePreInitPlugins(r),this.lifecycle.failReady(i)),i}}get isReadOnly(){return this.configController.isReadOnly}getJSON(){if(!this.view)throw new Error("Editor not initialized");return e=this.view.getState(),R(e.doc);var e}setJSON(e){this.assertInitialized(),fr(e,this.pluginManager?.schemaRegistry,e=>this.replaceState(e))}async getContentHTML(t){if(!this.view)throw new Error("Editor not initialized");return function(t,n,r){const s=t.doc;if("classes"===r?.cssMode){const t=wt(s,n,r);return r.pretty?{html:e(t.html),css:t.css,styleMap:t.styleMap}:t}const i=kt(s,n,r);return r?.pretty?e(i):i}(this.view.getState(),this.pluginManager?.schemaRegistry,t)}async setContentHTML(e,t){return this.assertInitialized(),function(e,t,n,r){fr(xt(e,t,r),t,n)}(e,this.pluginManager?.schemaRegistry,e=>this.replaceState(e),t)}async getContentMarkdown(e){if(!this.view)throw new Error("Editor not initialized");return async function(e,t,n){const{serializeDocumentToMarkdown:r}=await import("./MarkdownSerializer-Oex2RzNw.mjs").then(e=>e.t);return r(e.doc,t,n)}(this.view.getState(),this.pluginManager?.schemaRegistry,e)}async setContentMarkdown(e,t){this.assertInitialized();const n=this.view,r=this.pluginManager,s=this.announce,i=this.markdownImportedMessage;if(!n)return;const o=this.initVersion,a=r?.markdownSyntaxRegistry.getExtensions(),l={...t,syntaxExtensions:t?.syntaxExtensions??a};let c=!1;await async function(e,t,n,r,s){const{parseMarkdownToDocument:i}=await import("./MarkdownParser-D1d9zB0R.mjs").then(e=>e.t),o=i(e,n,s),a=t.doc.children.map(e=>e.id);fr({children:o.children.map((e,t)=>{const n=a[t];return n?L(e.type,e.children,n,e.attrs,e.htmlId):e})},n,r)}(e,n.getState(),r?.schemaRegistry,e=>{o===this.initVersion&&this.view===n&&this.pluginManager===r&&(n.replaceState(e),c=!0)},l),c&&o===this.initVersion&&this.view===n&&this.pluginManager===r&&this.announce===s&&s?.(i)}getText(){if(!this.view)throw new Error("Editor not initialized");return wr(this.view.getState())}setText(e){this.assertInitialized(),this.view&&function(e,t,n,r){if(e===wr(t))return;const s=e.split("\n"),i=t.doc.children.map(e=>e.id),o=s.map((e,t)=>L(de("paragraph"),[I(e)],i[t])),a=n?Ve(n):void 0;r(dr.create({doc:{children:o},schema:a}))}(e,this.view.getState(),this.pluginManager?.schemaRegistry,e=>this.replaceState(e))}isEmpty(){return!this.view||br(this.view.getState().doc)}commands={toggleBold:()=>this.executeCommand("toggleBold"),toggleItalic:()=>this.executeCommand("toggleItalic"),toggleUnderline:()=>this.executeCommand("toggleUnderline"),undo:()=>{this.configController.isReadOnly||this.view?.undo()},redo:()=>{this.configController.isReadOnly||this.view?.redo()},selectAll:()=>{if(!this.view)return;const e=je(this.view.getState());this.dispatch(e)}};can(){const e=this.view?.getState().schema,t=this.configController.isReadOnly;return{toggleBold:()=>!t&&!!e&&qe(e,"bold"),toggleItalic:()=>!t&&!!e&&qe(e,"italic"),toggleUnderline:()=>!t&&!!e&&qe(e,"underline"),undo:()=>!t&&(this.view?.history.canUndo()??!1),redo:()=>!t&&(this.view?.history.canRedo()??!1),selectAll:()=>this.canExecuteCommand("selectAll")}}canExecuteCommand(e){return this.pluginManager?.canExecuteCommand(e)??!1}executeCommand(e){return this.pluginManager?.executeCommand(e)??!1}configurePlugin(e,t){this.pluginManager?.configurePlugin(e,t)}getService(e){return this.pluginManager?.getService(e)}onPluginEvent(e,t){return this.pluginManager?.onEvent(e,t)??(()=>{})}getState(){if(!this.view)throw new Error("Editor not initialized");return this.view.getState()}dispatch(e){this.view&&this.pluginManager&&this.pluginManager.dispatchWithMiddleware(e,this.view.getState(),e=>this.view?.dispatch(e))}on(e,t){this.events.on(e,t)}off(e,t){this.events.off(e,t)}whenReady(){return ot(this)?Promise.reject(ft()):this.lifecycle.whenReady()}configure(e){this.configController.applyRuntimeConfig(e,this.getConfigDeps()),"logger"in e&&this.events.setLogger(e.logger)}setTheme(e){this.configController.applyTheme(e,this.themeController)}getTheme(){return this.configController.getTheme()}getPaperSize(){return this.configController.getPaperSize()}destroy(){if(this.cancelAutoInit(),this.pendingDestroyPromise)return this.destroyVersion++,this.initVersion++,this.cancelPendingInit?.(),this.lifecycle.reset(),this.pendingDestroyPromise;this.destroyVersion++,this.initVersion++,this.cancelPendingInit?.(),this.cancelPendingInit=null;const e=this.pendingInitPromise?.then(()=>{},()=>{})??Promise.resolve();this.pendingInitPromise=null;const t=this.activeInitResult;this.activeInitResult=null,this.clearPublishedRuntime(),this.lifecycle.reset(),this.events.clear();const n=Promise.resolve().then(()=>{const n=t?.dispose()??Promise.resolve();return Promise.all([n,e]).then(()=>{})}).finally(()=>{this.pendingDestroyPromise===n&&(this.pendingDestroyPromise=null)});return this.pendingDestroyPromise=n,n}clearPublishedRuntime(){this.view=null,this.pluginManager=null,this.domElements=null,this.themeController=null,this.paperLayout=null,this.announce=null}ensureFreshShadowRoot(){const e=this.shadowRoot;return e?(e.replaceChildren(),e):this.attachShadow({mode:"open"})}getConfigDeps(){return{contentElement:this.domElements?.content??null,editorWrapper:this.domElements?.wrapper??null,pluginManager:this.pluginManager,themeController:this.themeController,applyPaperSize:e=>this.applyPaperSize(e)}}scheduleAutoInit(){const e=++this.autoInitToken;this.autoInitQueued=!0,queueMicrotask(()=>{this.isConnected&&this.autoInitQueued&&this.autoInitToken===e&&(this.autoInitQueued=!1,this.lifecycle.isInitialized()||this.init().catch(()=>{}))})}cancelAutoInit(){this.autoInitToken++,this.autoInitQueued=!1}applyPaperSize(e){this.domElements&&(e?(this.paperLayout||(this.paperLayout=new no(this.domElements.wrapper,this.domElements.content)),this.paperLayout.apply(e)):this.paperLayout?.apply(null))}replaceState(e){this.view&&this.view.replaceState(e)}assertInitialized(){if(!this.view)throw new Error("Editor not initialized")}};async function po(e){const t=document.createElement("notectl-editor");return await t.init(e),t}function mo(){"undefined"==typeof customElements||customElements.get("notectl-editor")||customElements.define("notectl-editor",uo)}mo();export{sr as A,Mr as C,lr as D,dr as E,pn as M,mn as N,rr as O,Ar as S,Cr as T,ws as _,Ji as a,jr as b,Ys as c,Us as d,Cs as f,vs as g,bs as h,lo as i,ar as j,ir as k,Xs as l,Is as m,uo as n,Qi as o,Rs as p,po as r,ni as s,mo as t,Ws as u,qr as v,Pr as w,Nr as x,Wr as y};
|
|
3
|
-
//# sourceMappingURL=register-ArnJV5vu.mjs.map
|