diff --git a/README.md b/README.md index 34b53ec..f9ac560 100644 --- a/README.md +++ b/README.md @@ -149,6 +149,31 @@ func (Post) TranslatableIndexes() []string { return []string{"slug"} } func (Post) MorphName() string { return `Golem15\Journal\Models\Post` } ``` +### Blog Editor + +`assets/src/blogeditor` is the Blog Editor admin element, the custom element `golem15-journal-blogeditor` (`BlogEditorElement`). It is a WYSIWYG HTML editor on TipTap (ProseMirror, MIT) with a Source tab that shows and edits the exact HTML string. The toolbar offers paragraphs and headings 2 to 4, bold, italic, bullet and ordered lists, links, blockquotes, tables, images, YouTube embeds, a raw HTML block, undo and redo. Labels follow the `ui-locale` attribute (`en`, `pl`). + +The element follows the admin field type element contract: the `value` property holds the HTML string; the attributes are `field-name`, `record-id`, `locale`, `ui-locale`, `options`, `disabled` and `invalid`; a bubbling `summer-change` event with `detail.value` fires on user edits only. It styles itself only through the admin `--c-*` variables, in `blogeditor.css` under its tag (TipTap's injected stylesheet is off), and never receives or sends credentials. + +- **Untouched values.** The element returns the exact string it was given until the user edits; an untouched imported post is saved byte for byte. Setting `value` to the string it currently returns is a no-op. After an edit, top-level blocks that are still equal to the loaded ones keep their original bytes, so editing one paragraph changes only that paragraph. Markup the schema does not model (`footer`, `section`, `aside`, `header`, `nav`, `details`, `style`, `div` and similar blocks, and a `figure` that is not an image with an optional caption) becomes a raw HTML card that shows its source as text and is written back verbatim. Unmodelled attributes on paragraphs, headings, lists, blockquotes, tables, cells, images and links, and `span` elements with attributes, survive an edit; event handler attributes (`on*`) are never kept. +- **Embeds.** The embed button takes a YouTube URL (`youtube.com/watch?v=`, `youtu.be/`, `youtube.com/shorts/`, `youtube.com/embed/`) and stores exactly `
`, where `ID` matches `^[A-Za-z0-9_-]{11}$`. The admin shows a card and never an iframe; the site layer expands the placeholder. Another provider is one entry in `EMBED_PROVIDERS` (`embed.ts`) and one in the layer. +- **Links.** The editor creates and keeps links only to `http`, `https`, `mailto` and relative URLs (`isPolicyUrl` in `extensions.ts`), the schemes both sanitizer policies keep; the scheme is read after removing control characters and spaces. A created link has `href` only; stored links keep their own `target` and `rel`, which the server strips on an edited save. +- **Images.** An image chosen with the file picker (JPEG, PNG, GIF, WebP) or dropped on the editor is handed to the admin page as a bubbling `summer-upload` event with `detail {id, file}`. The admin uploads it with its own session and answers on the element with `summer-upload-result` `{id, url}` or `{id, error}`. On a URL the editor asks for the alt text (required) and an optional caption and inserts ``, or `
` with `` and `
` when a caption is given. An error, or no answer within 60 seconds, is shown in the status line and nothing is inserted. +- **Sanitizing.** The element never sanitizes. Every admin save goes through `classes.SanitizeHTML`, which strips what the policy does not allow. + +The element is built by the plugin's own JS build into `assets/dist/blogeditor.js` and `assets/dist/blogeditor.css`. Both files are committed and embedded through `admin.go`, so a host application needs no Node: + +```sh +npm ci # exact versions from package-lock.json +npm run build # typecheck, then vite build into assets/dist +npm test # vitest on happy-dom +bash scripts/check-dist.sh # fails when assets/dist differs from a fresh build +``` + +After changing `assets/src`, run `npm run build` and commit `assets/dist`. + +`tests/blogeditor/fixtures/editor-corpus.json` holds the editor's own output, built through editor commands: an embed, images with and without a caption, a table with a header row, links, headings, lists (one starting at 3), a blockquote, inline marks, a code block, a horizontal rule, a hard break, and one document combining them. `tests/blogeditor/corpus.test.ts` rebuilds it and fails when the committed file differs; `UPDATE_CORPUS=1 npm test` rewrites it. The Go policy test and the site layer check the same entries against both sanitizer policies, so entry names stay stable. + ## API reference | Identifier | Description | @@ -201,6 +226,7 @@ Both commands write JSON files (one per post slug), matching the PHP `journal:ex - SummerCMS modules: backpack, beachcomber, bonfire, cabana, lagoon/attach, pact, party, surf. - Compiled plugin: `golem15.translate`. - Third-party: `gorm.io/gorm`, `github.com/go-gormigrate/gormigrate/v2`, `github.com/yuin/goldmark`, `github.com/microcosm-cc/bluemonday`, `golang.org/x/net/html`, `gocloud.dev`. Test-only: `github.com/testcontainers/testcontainers-go`. +- Blog Editor JS build (not needed by a host application): `@tiptap/core`, `@tiptap/pm`, `@tiptap/starter-kit`, `@tiptap/extension-table` and `@tiptap/extension-image` 3.31.4, bundled into `assets/dist`; dev-only `vite`, `vitest`, `happy-dom` and `typescript`, pinned exactly in `package.json`. ## Testing @@ -209,3 +235,10 @@ go test ./... ``` Postgres integration smokes start Docker unless `-short`. Missing Docker is a failure, not a skip, unless `-short`. + +The Blog Editor has its own suite and drift gate: + +```sh +npm test +bash scripts/check-dist.sh +``` diff --git a/assets/dist/blogeditor.css b/assets/dist/blogeditor.css index 572e2d0..fd0144f 100644 --- a/assets/dist/blogeditor.css +++ b/assets/dist/blogeditor.css @@ -1 +1 @@ -golem15-journal-blogeditor{display:block;border:1px solid var(--c-border);border-radius:12px;background:var(--c-surface);color:var(--c-text)}golem15-journal-blogeditor[invalid]{border-color:var(--c-danger)}golem15-journal-blogeditor .blogeditor__bar{display:flex;flex-wrap:wrap;align-items:center;gap:4px;padding:6px 8px;border-bottom:1px solid var(--c-border);background:var(--c-subtle);border-radius:12px 12px 0 0}golem15-journal-blogeditor .blogeditor__tabs{display:flex;gap:2px;margin-left:auto}golem15-journal-blogeditor button{font:inherit;font-size:13px;line-height:1.2;padding:4px 8px;border:1px solid transparent;border-radius:6px;background:transparent;color:var(--c-text);cursor:pointer}golem15-journal-blogeditor button:hover{background:var(--c-hover)}golem15-journal-blogeditor button:focus-visible{outline:2px solid var(--c-ring);outline-offset:1px}golem15-journal-blogeditor button[aria-selected=true],golem15-journal-blogeditor button[aria-pressed=true]{background:var(--c-sel)}golem15-journal-blogeditor button:disabled{color:var(--c-muted);cursor:default}golem15-journal-blogeditor .blogeditor__content{min-height:240px;max-height:70vh;overflow:auto}golem15-journal-blogeditor .blogeditor__source{display:block;box-sizing:border-box;width:100%;min-height:320px;padding:12px 16px;border:0;border-radius:0 0 12px 12px;background:var(--c-bg);color:var(--c-text);font-family:DM Mono,ui-monospace,monospace;font-size:13px;line-height:1.5;resize:vertical}golem15-journal-blogeditor .blogeditor__source:focus{outline:2px solid var(--c-ring);outline-offset:-2px}golem15-journal-blogeditor [hidden]{display:none!important}golem15-journal-blogeditor .ProseMirror{position:relative;word-wrap:break-word;white-space:pre-wrap;white-space:break-spaces;-webkit-font-variant-ligatures:none;font-variant-ligatures:none;font-feature-settings:"liga" 0;min-height:240px;padding:12px 16px;outline:none;font-size:15px;line-height:1.6}golem15-journal-blogeditor .ProseMirror[contenteditable=false]{color:var(--c-muted)}golem15-journal-blogeditor .ProseMirror [contenteditable=false]{white-space:normal}golem15-journal-blogeditor .ProseMirror [contenteditable=false] [contenteditable=true]{white-space:pre-wrap}golem15-journal-blogeditor .ProseMirror pre{white-space:pre-wrap}golem15-journal-blogeditor img.ProseMirror-separator{display:inline!important;border:none!important;margin:0!important;width:0!important;height:0!important}golem15-journal-blogeditor .ProseMirror-gapcursor{display:none;pointer-events:none;position:absolute;margin:0}golem15-journal-blogeditor .ProseMirror-gapcursor:after{content:"";display:block;position:absolute;top:-2px;width:20px;border-top:1px solid var(--c-text);animation:blogeditor-cursor-blink 1.1s steps(2,start) infinite}@keyframes blogeditor-cursor-blink{to{visibility:hidden}}golem15-journal-blogeditor .ProseMirror-hideselection *::selection{background:transparent}golem15-journal-blogeditor .ProseMirror-hideselection *{caret-color:transparent}golem15-journal-blogeditor .ProseMirror-focused .ProseMirror-gapcursor{display:block}golem15-journal-blogeditor .ProseMirror>*+*{margin-top:.75em}golem15-journal-blogeditor .ProseMirror :where(p,ul,ol,blockquote,table,figure,pre){margin-bottom:0}golem15-journal-blogeditor .ProseMirror h2{font-size:1.5em;font-weight:600;margin:1em 0 .5em}golem15-journal-blogeditor .ProseMirror h3{font-size:1.25em;font-weight:600;margin:1em 0 .5em}golem15-journal-blogeditor .ProseMirror h4{font-size:1.1em;font-weight:600;margin:1em 0 .5em}golem15-journal-blogeditor .ProseMirror ul{list-style:disc;padding-left:1.5em}golem15-journal-blogeditor .ProseMirror ol{list-style:decimal;padding-left:1.5em}golem15-journal-blogeditor .ProseMirror a{color:var(--c-primary);text-decoration:underline}golem15-journal-blogeditor .ProseMirror blockquote{margin-left:0;padding-left:1em;border-left:3px solid var(--c-border-strong);color:var(--c-muted)}golem15-journal-blogeditor .ProseMirror code{padding:0 4px;border-radius:4px;background:var(--c-subtle);font-family:DM Mono,ui-monospace,monospace;font-size:.9em}golem15-journal-blogeditor .ProseMirror pre{padding:8px 12px;border-radius:8px;background:var(--c-subtle)}golem15-journal-blogeditor .ProseMirror pre code{padding:0;background:transparent}golem15-journal-blogeditor .ProseMirror hr{border:0;border-top:1px solid var(--c-border-strong)}golem15-journal-blogeditor .ProseMirror img{max-width:100%;height:auto} +golem15-journal-blogeditor{display:block;border:1px solid var(--c-border);border-radius:12px;background:var(--c-surface);color:var(--c-text)}golem15-journal-blogeditor[invalid]{border-color:var(--c-danger)}golem15-journal-blogeditor .blogeditor__bar{display:flex;flex-wrap:wrap;align-items:center;gap:4px;padding:6px 8px;border-bottom:1px solid var(--c-border);background:var(--c-subtle);border-radius:12px 12px 0 0}golem15-journal-blogeditor .blogeditor__tools{display:flex;flex-wrap:wrap;gap:4px 12px}golem15-journal-blogeditor .blogeditor__group{display:flex;flex-wrap:wrap;gap:2px}golem15-journal-blogeditor .blogeditor__tabs{display:flex;gap:2px;margin-left:auto}golem15-journal-blogeditor .blogeditor__form{display:flex;flex-wrap:wrap;align-items:flex-end;gap:6px 8px;padding:8px;border-bottom:1px solid var(--c-border);background:var(--c-surface)}golem15-journal-blogeditor .blogeditor__form label{display:flex;flex:1 1 220px;flex-direction:column;gap:2px;font-size:12px;color:var(--c-muted)}golem15-journal-blogeditor .blogeditor__form input{box-sizing:border-box;width:100%;padding:5px 8px;border:1px solid var(--c-border-strong);border-radius:6px;background:var(--c-bg);color:var(--c-text);font:inherit;font-size:13px}golem15-journal-blogeditor .blogeditor__form input::placeholder{color:var(--c-placeholder)}golem15-journal-blogeditor .blogeditor__form input:focus{outline:2px solid var(--c-ring);outline-offset:-1px}golem15-journal-blogeditor .blogeditor__form button[data-action=apply],golem15-journal-blogeditor .blogeditor__form button[data-action=insert]{background:var(--c-primary);color:var(--c-on-primary)}golem15-journal-blogeditor .blogeditor__error{flex-basis:100%;margin:0;font-size:12px;color:var(--c-danger)}golem15-journal-blogeditor .blogeditor__error:empty,golem15-journal-blogeditor .blogeditor__status:empty{display:none}golem15-journal-blogeditor .blogeditor__status{margin:0;padding:6px 12px;border-top:1px solid var(--c-border);font-size:12px;color:var(--c-muted)}golem15-journal-blogeditor button{font:inherit;font-size:13px;line-height:1.2;padding:4px 8px;border:1px solid transparent;border-radius:6px;background:transparent;color:var(--c-text);cursor:pointer}golem15-journal-blogeditor button:hover{background:var(--c-hover)}golem15-journal-blogeditor button:focus-visible{outline:2px solid var(--c-ring);outline-offset:1px}golem15-journal-blogeditor button[aria-selected=true],golem15-journal-blogeditor button[aria-pressed=true]{background:var(--c-sel)}golem15-journal-blogeditor button:disabled{color:var(--c-muted);cursor:default}golem15-journal-blogeditor .blogeditor__content{min-height:240px;max-height:70vh;overflow:auto}golem15-journal-blogeditor .blogeditor__source{display:block;box-sizing:border-box;width:100%;min-height:320px;padding:12px 16px;border:0;border-radius:0 0 12px 12px;background:var(--c-bg);color:var(--c-text);font-family:DM Mono,ui-monospace,monospace;font-size:13px;line-height:1.5;resize:vertical}golem15-journal-blogeditor .blogeditor__source:focus{outline:2px solid var(--c-ring);outline-offset:-2px}golem15-journal-blogeditor [hidden]{display:none!important}golem15-journal-blogeditor .ProseMirror{position:relative;word-wrap:break-word;white-space:pre-wrap;white-space:break-spaces;-webkit-font-variant-ligatures:none;font-variant-ligatures:none;font-feature-settings:"liga" 0;min-height:240px;padding:12px 16px;outline:none;font-size:15px;line-height:1.6}golem15-journal-blogeditor .ProseMirror[contenteditable=false]{color:var(--c-muted)}golem15-journal-blogeditor .ProseMirror [contenteditable=false]{white-space:normal}golem15-journal-blogeditor .ProseMirror [contenteditable=false] [contenteditable=true]{white-space:pre-wrap}golem15-journal-blogeditor .ProseMirror pre{white-space:pre-wrap}golem15-journal-blogeditor img.ProseMirror-separator{display:inline!important;border:none!important;margin:0!important;width:0!important;height:0!important}golem15-journal-blogeditor .ProseMirror-gapcursor{display:none;pointer-events:none;position:absolute;margin:0}golem15-journal-blogeditor .ProseMirror-gapcursor:after{content:"";display:block;position:absolute;top:-2px;width:20px;border-top:1px solid var(--c-text);animation:blogeditor-cursor-blink 1.1s steps(2,start) infinite}@keyframes blogeditor-cursor-blink{to{visibility:hidden}}golem15-journal-blogeditor .ProseMirror-hideselection *::selection{background:transparent}golem15-journal-blogeditor .ProseMirror-hideselection *{caret-color:transparent}golem15-journal-blogeditor .ProseMirror-focused .ProseMirror-gapcursor{display:block}golem15-journal-blogeditor .ProseMirror>*+*{margin-top:.75em}golem15-journal-blogeditor .ProseMirror :where(p,ul,ol,blockquote,table,figure,pre){margin-bottom:0}golem15-journal-blogeditor .ProseMirror h2{font-size:1.5em;font-weight:600;margin:1em 0 .5em}golem15-journal-blogeditor .ProseMirror h3{font-size:1.25em;font-weight:600;margin:1em 0 .5em}golem15-journal-blogeditor .ProseMirror h4{font-size:1.1em;font-weight:600;margin:1em 0 .5em}golem15-journal-blogeditor .ProseMirror ul{list-style:disc;padding-left:1.5em}golem15-journal-blogeditor .ProseMirror ol{list-style:decimal;padding-left:1.5em}golem15-journal-blogeditor .ProseMirror a{color:var(--c-primary);text-decoration:underline}golem15-journal-blogeditor .ProseMirror blockquote{margin-left:0;padding-left:1em;border-left:3px solid var(--c-border-strong);color:var(--c-muted)}golem15-journal-blogeditor .ProseMirror code{padding:0 4px;border-radius:4px;background:var(--c-subtle);font-family:DM Mono,ui-monospace,monospace;font-size:.9em}golem15-journal-blogeditor .ProseMirror pre{padding:8px 12px;border-radius:8px;background:var(--c-subtle)}golem15-journal-blogeditor .ProseMirror pre code{padding:0;background:transparent}golem15-journal-blogeditor .ProseMirror hr{border:0;border-top:1px solid var(--c-border-strong)}golem15-journal-blogeditor .ProseMirror img{max-width:100%;height:auto}golem15-journal-blogeditor .ProseMirror table{border-collapse:collapse;width:100%}golem15-journal-blogeditor .ProseMirror :where(td,th){border:1px solid var(--c-border-strong);padding:4px 8px;vertical-align:top}golem15-journal-blogeditor .ProseMirror th{background:var(--c-subtle);font-weight:600;text-align:left}golem15-journal-blogeditor .ProseMirror :where(td,th)>p{margin:0}golem15-journal-blogeditor .ProseMirror .selectedCell{background:var(--c-sel)}golem15-journal-blogeditor .ProseMirror figure{margin-left:0;margin-right:0}golem15-journal-blogeditor .ProseMirror figcaption{margin-top:4px;font-size:13px;color:var(--c-muted)}golem15-journal-blogeditor .blogeditor__raw,golem15-journal-blogeditor .blogeditor__embed{border:1px dashed var(--c-border-strong);border-radius:8px;background:var(--c-subtle);color:var(--c-muted);font-size:13px}golem15-journal-blogeditor .blogeditor__embed{padding:16px;text-align:center}golem15-journal-blogeditor .blogeditor__card-head{display:flex;align-items:center;justify-content:space-between;gap:8px;padding:4px 4px 4px 10px;border-bottom:1px dashed var(--c-border)}golem15-journal-blogeditor .blogeditor__raw-source{max-height:160px;margin:0;padding:8px 10px;overflow:auto;background:transparent;font-family:DM Mono,ui-monospace,monospace;font-size:12px;white-space:pre-wrap}golem15-journal-blogeditor .ProseMirror-selectednode.blogeditor__raw,golem15-journal-blogeditor .ProseMirror-selectednode.blogeditor__embed,golem15-journal-blogeditor .ProseMirror img.ProseMirror-selectednode{outline:2px solid var(--c-ring)} diff --git a/assets/dist/blogeditor.js b/assets/dist/blogeditor.js index d9099b9..627c3a3 100644 --- a/assets/dist/blogeditor.js +++ b/assets/dist/blogeditor.js @@ -1,29 +1,29 @@ -var Vs=Object.defineProperty,gu=(n,e)=>{let t={};for(var r in n)Vs(t,r,{get:n[r],enumerable:!0});return Vs(t,Symbol.toStringTag,{value:"Module"}),t};function Q(n){this.content=n}Q.prototype={constructor:Q,find:function(n){for(var e=0;e>1}};Q.from=function(n){if(n instanceof Q)return n;var e=[];if(n)for(var t in n)e.push(t,n[t]);return new Q(e)};function Ml(n,e,t){for(let r=0;;r++){if(r==n.childCount||r==e.childCount)return n.childCount==e.childCount?null:t;let i=n.child(r),s=e.child(r);if(i==s){t+=i.nodeSize;continue}if(!i.sameMarkup(s))return t;if(i.isText&&i.text!=s.text){let o=i.text,l=s.text,a=0;for(;o[a]==l[a];a++)t++;return a&&a0&&f>0&&c[d-1]==u[f-1];)d--,f--,t--,r--;return d&&f&&d=56320&&n<57344}function Tl(n){return n>=55296&&n<56320}class b{constructor(e,t){if(this.content=e,this.size=t||0,t==null)for(let r=0;re&&r(a,i+l,s||null,o)!==!1&&a.content.size){let u=l+1;a.nodesBetween(Math.max(0,e-u),Math.min(a.content.size,t-u),r,i+u)}l=c}}descendants(e){this.nodesBetween(0,this.size,e)}textBetween(e,t,r,i){let s="",o=!0;return this.nodesBetween(e,t,(l,a)=>{let c=l.isText?l.text.slice(Math.max(e,a)-a,t-a):l.isLeaf?i?typeof i=="function"?i(l):i:l.type.spec.leafText?l.type.spec.leafText(l):"":"";l.isBlock&&(l.isLeaf&&c||l.isTextblock)&&r&&(o?o=!1:s+=r),s+=c},0),s}append(e){if(!e.size)return this;if(!this.size)return e;let t=this.lastChild,r=e.firstChild,i=this.content.slice(),s=0;for(t.isText&&t.sameMarkup(r)&&(i[i.length-1]=t.withText(t.text+r.text),s=1);se)for(let s=0,o=0;oe&&((ot)&&(l.isText?l=l.cut(Math.max(0,e-o),Math.min(l.text.length,t-o)):l=l.cut(Math.max(0,e-o-1),Math.min(l.content.size,t-o-1))),r.push(l),i+=l.nodeSize),o=a}return new b(r,i)}cutByIndex(e,t){return e==t?b.empty:e==0&&t==this.content.length?this:new b(this.content.slice(e,t))}replaceChild(e,t){let r=this.content[e];if(r==t)return this;let i=this.content.slice(),s=this.size+t.nodeSize-r.nodeSize;return i[e]=t,new b(i,s)}addToStart(e){return new b([e].concat(this.content),this.size+e.nodeSize)}addToEnd(e){return new b(this.content.concat(e),this.size+e.nodeSize)}eq(e){if(this.content.length!=e.content.length)return!1;for(let t=0;tthis.size||e<0)throw new RangeError(`Position ${e} outside of fragment (${this})`);for(let t=0,r=0;;t++){let i=this.child(t),s=r+i.nodeSize;if(s>=e)return s==e?Rn(t+1,s):Rn(t,r);r=s}}toString(){return"<"+this.toStringInner()+">"}toStringInner(){return this.content.join(", ")}toJSON(){return this.content.length?this.content.map(e=>e.toJSON()):null}static fromJSON(e,t){if(!t)return b.empty;if(!Array.isArray(t))throw new RangeError("Invalid input for Fragment.fromJSON");return b.fromArray(t.map(e.nodeFromJSON))}static fromArray(e){if(!e.length)return b.empty;let t,r=0;for(let i=0;ithis.type.rank&&(t||(t=e.slice(0,i)),t.push(this),r=!0),t&&t.push(s)}}return t||(t=e.slice()),r||t.push(this),t}removeFromSet(e){for(let t=0;tr.type.rank-i.type.rank),t}};B.none=[];class gn extends Error{}class w{constructor(e,t,r){this.content=e,this.openStart=t,this.openEnd=r}get size(){return this.content.size-this.openStart-this.openEnd}insertAt(e,t){let r=Ol(this.content,e+this.openStart,t,this.openStart+1,this.openEnd+1);return r&&new w(r,this.openStart,this.openEnd)}removeBetween(e,t){return new w(Al(this.content,e+this.openStart,t+this.openStart),this.openStart,this.openEnd)}eq(e){return this.content.eq(e.content)&&this.openStart==e.openStart&&this.openEnd==e.openEnd}toString(){return this.content+"("+this.openStart+","+this.openEnd+")"}toJSON(){if(!this.content.size)return null;let e={content:this.content.toJSON()};return this.openStart>0&&(e.openStart=this.openStart),this.openEnd>0&&(e.openEnd=this.openEnd),e}static fromJSON(e,t){if(!t)return w.empty;let r=t.openStart||0,i=t.openEnd||0;if(typeof r!="number"||typeof i!="number")throw new RangeError("Invalid input for Slice.fromJSON");return new w(b.fromJSON(e,t.content),r,i)}static maxOpen(e,t=!0){let r=0,i=0;for(let s=e.firstChild;s&&!s.isLeaf&&(t||!s.type.spec.isolating);s=s.firstChild)r++;for(let s=e.lastChild;s&&!s.isLeaf&&(t||!s.type.spec.isolating);s=s.lastChild)i++;return new w(e,r,i)}}w.empty=new w(b.empty,0,0);function Al(n,e,t){let{index:r,offset:i}=n.findIndex(e),s=n.maybeChild(r),{index:o,offset:l}=n.findIndex(t);if(i==e||s.isText){if(l!=t&&!n.child(o).isText)throw new RangeError("Removing non-flat range");return n.cut(0,e).append(n.cut(t))}if(r!=o)throw new RangeError("Removing non-flat range");return n.replaceChild(r,s.copy(Al(s.content,e-i-1,t-i-1)))}function Ol(n,e,t,r,i,s){let{index:o,offset:l}=n.findIndex(e),a=n.maybeChild(o);if(l==e||a.isText)return s&&r<=0&&i<=0&&!s.canReplace(o,o,t)?null:n.cut(0,e).append(t).append(n.cut(e));let c=Ol(a.content,e-l-1,t,o==0?r-1:0,o==n.childCount-1?i-1:0,a);return c&&n.replaceChild(o,a.copy(c))}function yu(n,e,t){if(t.openStart>n.depth)throw new gn("Inserted content deeper than insertion position");if(n.depth-t.openStart!=e.depth-t.openEnd)throw new gn("Inconsistent open depths");return Nl(n,e,t,0)}function Nl(n,e,t,r){let i=n.index(r),s=n.node(r);if(i==e.index(r)&&r=0&&n.isText&&n.sameMarkup(e[t])?e[t]=n.withText(e[t].text+n.text):e.push(n)}function nn(n,e,t,r){let i=(e||n).node(t),s=0,o=e?e.index(t):i.childCount;n&&(s=n.index(t),n.depth>t?s++:n.textOffset&&(gt(n.nodeAfter,r),s++));for(let l=s;li&&Ai(n,e,i+1),o=r.depth>i&&Ai(t,r,i+1),l=[];return nn(null,n,i,l),s&&o&&e.index(i)==t.index(i)?(Dl(s,o),gt(yt(s,Il(n,e,t,r,i+1)),l)):(s&>(yt(s,Qn(n,e,i+1)),l),nn(e,t,i,l),o&>(yt(o,Qn(t,r,i+1)),l)),nn(r,null,i,l),new b(l)}function Qn(n,e,t){let r=[];if(nn(null,n,t,r),n.depth>t){let i=Ai(n,e,t+1);gt(yt(i,Qn(n,e,t+1)),r)}return nn(e,null,t,r),new b(r)}function bu(n,e){let t=e.depth-n.openStart,i=e.node(t).copy(n.content);for(let s=t-1;s>=0;s--)i=e.node(s).copy(b.from(i));return{start:i.resolveNoCache(n.openStart+t),end:i.resolveNoCache(i.content.size-n.openEnd-t)}}class yn{constructor(e,t,r){this.pos=e,this.path=t,this.parentOffset=r,this.depth=t.length/3-1}resolveDepth(e){return e==null?this.depth:e<0?this.depth+e:e}get parent(){return this.node(this.depth)}get doc(){return this.node(0)}node(e){return this.path[this.resolveDepth(e)*3]}index(e){return this.path[this.resolveDepth(e)*3+1]}indexAfter(e){return e=this.resolveDepth(e),this.index(e)+(e==this.depth&&!this.textOffset?0:1)}start(e){return e=this.resolveDepth(e),e==0?0:this.path[e*3-1]+1}end(e){return e=this.resolveDepth(e),this.start(e)+this.node(e).content.size}before(e){if(e=this.resolveDepth(e),!e)throw new RangeError("There is no position before the top-level node");return e==this.depth+1?this.pos:this.path[e*3-1]}after(e){if(e=this.resolveDepth(e),!e)throw new RangeError("There is no position after the top-level node");return e==this.depth+1?this.pos:this.path[e*3-1]+this.path[e*3].nodeSize}get textOffset(){return this.pos-this.path[this.path.length-1]}get nodeAfter(){let e=this.parent,t=this.index(this.depth);if(t==e.childCount)return null;let r=this.pos-this.path[this.path.length-1],i=e.child(t);return r?e.child(t).cut(r):i}get nodeBefore(){let e=this.index(this.depth),t=this.pos-this.path[this.path.length-1];return t?this.parent.child(e).cut(0,t):e==0?null:this.parent.child(e-1)}posAtIndex(e,t){t=this.resolveDepth(t);let r=this.path[t*3],i=t==0?0:this.path[t*3-1]+1;for(let s=0;s0;t--)if(this.start(t)<=e&&this.end(t)>=e)return t;return 0}blockRange(e=this,t){if(e.pos=0;r--)if(e.pos<=this.end(r)&&(!t||t(this.node(r))))return new Zn(this,e,r);return null}sameParent(e){return this.pos-this.parentOffset==e.pos-e.parentOffset}max(e){return e.pos>this.pos?e:this}min(e){return e.pos=0&&t<=e.content.size))throw new RangeError("Position "+t+" out of range");let r=[],i=0,s=t;for(let o=e;;){let{index:l,offset:a}=o.content.findIndex(s),c=s-a;if(r.push(o,l,i+a),!c||(o=o.child(l),o.isText))break;s=c-1,i+=a+1}return new yn(t,r,s)}static resolveCached(e,t){let r=Hs.get(e);if(r)for(let s=0;se&&this.nodesBetween(e,t,s=>(r.isInSet(s.marks)&&(i=!0),!i)),i}get isBlock(){return this.type.isBlock}get isTextblock(){return this.type.isTextblock}get inlineContent(){return this.type.inlineContent}get isInline(){return this.type.isInline}get isText(){return this.type.isText}get isLeaf(){return this.type.isLeaf}get isAtom(){return this.type.isAtom}toString(){if(this.type.spec.toDebugString)return this.type.spec.toDebugString(this);let e=this.type.name;return this.content.size&&(e+="("+this.content.toStringInner()+")"),Rl(this.marks,e)}contentMatchAt(e){let t=this.type.contentMatch.matchFragment(this.content,0,e);if(!t)throw new Error("Called contentMatchAt on a node with invalid content");return t}canReplace(e,t,r=b.empty,i=0,s=r.childCount){let o=this.contentMatchAt(e).matchFragment(r,i,s),l=o&&o.matchFragment(this.content,t);if(!l||!l.validEnd)return!1;for(let a=i;at.type.name)}`);this.content.forEach(t=>t.check())}toJSON(){let e={type:this.type.name};for(let t in this.attrs){e.attrs=this.attrs;break}return this.content.size&&(e.content=this.content.toJSON()),this.marks.length&&(e.marks=this.marks.map(t=>t.toJSON())),e}static fromJSON(e,t){if(!t)throw new RangeError("Invalid input for Node.fromJSON");let r;if(t.marks){if(!Array.isArray(t.marks))throw new RangeError("Invalid mark data for Node.fromJSON");r=t.marks.map(e.markFromJSON)}if(t.type=="text"){if(typeof t.text!="string")throw new RangeError("Invalid text node in JSON");return e.text(t.text,r)}let i=b.fromJSON(e,t.content);return e.nodeType(t.type).create(t.attrs,i,r)}};bt.prototype.text=void 0;class er extends bt{constructor(e,t,r,i){if(super(e,t,null,i),!r)throw new RangeError("Empty text nodes are not allowed");this.text=r}toString(){return this.type.spec.toDebugString?this.type.spec.toDebugString(this):Rl(this.marks,JSON.stringify(this.text))}get textContent(){return this.text}textBetween(e,t){return this.text.slice(e,t)}get nodeSize(){return this.text.length}mark(e){return e==this.marks?this:new er(this.type,this.attrs,this.text,e)}withText(e){return e==this.text?this:new er(this.type,this.attrs,e,this.marks)}cut(e=0,t=this.text.length){return e==0&&t==this.text.length?this:this.withText(this.text.slice(e,t))}eq(e){return this.sameMarkup(e)&&this.text==e.text}toJSON(){let e=super.toJSON();return e.text=this.text,e}}function Rl(n,e){for(let t=n.length-1;t>=0;t--)e=n[t].type.name+"("+e+")";return e}function js(n,e,t,r){for(let i in e)if(!(i in n))throw new RangeError(`Unsupported attribute ${i} for ${t} of type ${r}`);for(let i in n)n[i].validate&&n[i].validate(e[i])}class xt{constructor(e){this.validEnd=e,this.next=[],this.wrapCache=[]}static parse(e,t){let r=new wu(e,t);if(r.next==null)return xt.empty;let i=Ll(r);r.next&&r.err("Unexpected trailing text");let s=Ou(Au(i));return Nu(s,r),s}matchType(e){for(let t=0;tc.createAndFill()));for(let c=0;c=this.next.length)throw new RangeError(`There's no ${e}th edge in this content match`);return this.next[e]}toString(){let e=[];function t(r){e.push(r);for(let i=0;i{let s=i+(r.validEnd?"*":" ")+" ";for(let o=0;o"+e.indexOf(r.next[o].next);return s}).join(` -`)}}xt.empty=new xt(!0);class wu{constructor(e,t){this.string=e,this.nodeTypes=t,this.inline=null,this.pos=0,this.tokens=e.split(/\s*(?=\b|\W|$)/),this.tokens[this.tokens.length-1]==""&&this.tokens.pop(),this.tokens[0]==""&&this.tokens.shift()}get next(){return this.tokens[this.pos]}eat(e){return this.next==e&&(this.pos++||!0)}err(e){throw new SyntaxError(e+" (in content expression '"+this.string+"')")}}function Ll(n){let e=[];do e.push(Cu(n));while(n.eat("|"));return e.length==1?e[0]:{type:"choice",exprs:e}}function Cu(n){let e=[];do e.push(Mu(n));while(n.next&&n.next!=")"&&n.next!="|");return e.length==1?e[0]:{type:"seq",exprs:e}}function Mu(n){let e=Tu(n);for(;;)if(n.eat("+"))e={type:"plus",expr:e};else if(n.eat("*"))e={type:"star",expr:e};else if(n.eat("?"))e={type:"opt",expr:e};else if(n.eat("{"))e=vu(n,e);else break;return e}function Ws(n){/\D/.test(n.next)&&n.err("Expected number, got '"+n.next+"'");let e=Number(n.next);return n.pos++,e}function vu(n,e){let t=Ws(n),r=t;return n.eat(",")&&(n.next!="}"?r=Ws(n):r=-1),n.eat("}")||n.err("Unclosed braced range"),{type:"range",min:t,max:r,expr:e}}function Eu(n,e){let t=n.nodeTypes,r=t[e];if(r)return[r];let i=[];for(let s in t){let o=t[s];o.isInGroup(e)&&i.push(o)}return i.length==0&&n.err("No node type or group '"+e+"' found"),i}function Tu(n){if(n.eat("(")){let e=Ll(n);return n.eat(")")||n.err("Missing closing paren"),e}else if(/\W/.test(n.next))n.err("Unexpected token '"+n.next+"'");else{let e=Eu(n,n.next).map(t=>(n.inline==null?n.inline=t.isInline:n.inline!=t.isInline&&n.err("Mixing inline and block content"),{type:"name",value:t}));return n.pos++,e.length==1?e[0]:{type:"choice",exprs:e}}}function Au(n){let e=[[]];return i(s(n,0),t()),e;function t(){return e.push([])-1}function r(o,l,a){let c={term:a,to:l};return e[o].push(c),c}function i(o,l){o.forEach(a=>a.to=l)}function s(o,l){if(o.type=="choice")return o.exprs.reduce((a,c)=>a.concat(s(c,l)),[]);if(o.type=="seq")for(let a=0;;a++){let c=s(o.exprs[a],l);if(a==o.exprs.length-1)return c;i(c,l=t())}else if(o.type=="star"){let a=t();return r(l,a),i(s(o.expr,a),a),[r(a)]}else if(o.type=="plus"){let a=t();return i(s(o.expr,l),a),i(s(o.expr,a),a),[r(a)]}else{if(o.type=="opt")return[r(l)].concat(s(o.expr,l));if(o.type=="range"){let a=l;for(let c=0;c{n[o].forEach(({term:l,to:a})=>{if(!l)return;let c;for(let u=0;u{c||i.push([l,c=[]]),c.indexOf(u)==-1&&c.push(u)})})});let s=e[r.join(",")]=new xt(r.indexOf(n.length-1)>-1);for(let o=0;o-1}get whitespace(){return this.spec.whitespace||(this.spec.code?"pre":"normal")}hasRequiredAttrs(){for(let e in this.attrs)if(this.attrs[e].isRequired)return!0;return!1}compatibleContent(e){return this==e||this.contentMatch.compatible(e.contentMatch)}computeAttrs(e){return!e&&this.defaultAttrs?this.defaultAttrs:zl(this.attrs,e)}create(e=null,t,r){if(this.isText)throw new Error("NodeType.create can't construct text nodes");return new bt(this,this.computeAttrs(e),b.from(t),B.setFrom(r))}createChecked(e=null,t,r){return t=b.from(t),this.checkContent(t),new bt(this,this.computeAttrs(e),t,B.setFrom(r))}createAndFill(e=null,t,r){if(e=this.computeAttrs(e),t=b.from(t),t.size){let o=this.contentMatch.fillBefore(t);if(!o)return null;t=o.append(t)}let i=this.contentMatch.matchFragment(t),s=i&&i.fillBefore(b.empty,!0);return s?new bt(this,e,t.append(s),B.setFrom(r)):null}validContent(e){let t=this.contentMatch.matchFragment(e);if(!t||!t.validEnd)return!1;for(let r=0;r-1}allowsMarks(e){if(this.markSet==null)return!0;for(let t=0;tr[s]=new Fl(s,t,o));let i=t.spec.topNode||"doc";if(!r[i])throw new RangeError("Schema is missing its top node type ('"+i+"')");if(!r.text)throw new RangeError("Every schema needs a 'text' type");for(let s in r.text.attrs)throw new RangeError("The text node type should not have attributes");return r}};function Du(n,e,t){let r=t.split("|");return i=>{let s=i===null?"null":typeof i;if(r.indexOf(s)<0)throw new RangeError(`Expected value of type ${r} for attribute ${e} on type ${n}, got ${s}`)}}class Iu{constructor(e,t,r){this.hasDefault=Object.prototype.hasOwnProperty.call(r,"default"),this.default=r.default,this.validate=typeof r.validate=="string"?Du(e,t,r.validate):r.validate}get isRequired(){return!this.hasDefault}}class Fr{constructor(e,t,r,i){this.name=e,this.rank=t,this.schema=r,this.spec=i,this.attrs=$l(e,i.attrs),this.excluded=null;let s=Bl(this.attrs);this.instance=s?new B(this,s):null}create(e=null){return!e&&this.instance?this.instance:new B(this,zl(this.attrs,e))}static compile(e,t){let r=Object.create(null),i=0;return e.forEach((s,o)=>r[s]=new Fr(s,i++,t,o)),r}removeFromSet(e){for(var t=0;t-1}}class Vl{constructor(e){this.linebreakReplacement=null,this.cached=Object.create(null);let t=this.spec={};for(let i in e)t[i]=e[i];t.nodes=Q.from(e.nodes),t.marks=Q.from(e.marks||{}),this.nodes=_s.compile(this.spec.nodes,this),this.marks=Fr.compile(this.spec.marks,this);let r=Object.create(null);for(let i in this.nodes){if(i in this.marks)throw new RangeError(i+" can not be both a node and a mark");let s=this.nodes[i],o=s.spec.content||"",l=s.spec.marks;if(s.contentMatch=r[o]||(r[o]=xt.parse(o,this.nodes)),s.inlineContent=s.contentMatch.inlineContent,s.spec.linebreakReplacement){if(this.linebreakReplacement)throw new RangeError("Multiple linebreak nodes defined");if(!s.isInline||!s.isLeaf)throw new RangeError("Linebreak replacement nodes must be inline leaf nodes");this.linebreakReplacement=s}s.markSet=l=="_"?null:l?Us(this,l.split(" ")):l==""||!s.inlineContent?[]:null}for(let i in this.marks){let s=this.marks[i],o=s.spec.excludes;s.excluded=o==null?[s]:o==""?[]:Us(this,o.split(" "))}this.nodeFromJSON=i=>bt.fromJSON(this,i),this.markFromJSON=i=>B.fromJSON(this,i),this.topNodeType=this.nodes[this.spec.topNode||"doc"],this.cached.wrappings=Object.create(null)}node(e,t=null,r,i){if(typeof e=="string")e=this.nodeType(e);else if(e instanceof _s){if(e.schema!=this)throw new RangeError("Node type from different schema used ("+e.name+")")}else throw new RangeError("Invalid node type: "+e);return e.createChecked(t,r,i)}text(e,t){let r=this.nodes.text;return new er(r,r.defaultAttrs,e,B.setFrom(t))}mark(e,t){return typeof e=="string"&&(e=this.marks[e]),e.create(t)}nodeType(e){let t=this.nodes[e];if(!t)throw new RangeError("Unknown node type: "+e);return t}}function Us(n,e){let t=[];for(let r=0;r-1)&&t.push(o=a)}if(!o)throw new SyntaxError("Unknown mark type: '"+e[r]+"'")}return t}function Ru(n){return n.tag!=null}function Lu(n){return n.style!=null}class Xe{constructor(e,t){this.schema=e,this.rules=t,this.tags=[],this.styles=[];let r=this.matchedStyles=[];t.forEach(i=>{if(Ru(i))this.tags.push(i);else if(Lu(i)){let s=/[^=]*/.exec(i.style)[0];r.indexOf(s)<0&&r.push(s),this.styles.push(i)}}),this.normalizeLists=!this.tags.some(i=>{if(!/^(ul|ol)\b/.test(i.tag)||!i.node)return!1;let s=e.nodes[i.node];return s.contentMatch.matchType(s)})}parse(e,t={}){let r=new Js(this,t,!1);return r.addAll(e,B.none,t.from,t.to),r.finish()}parseSlice(e,t={}){let r=new Js(this,t,!0);return r.addAll(e,B.none,t.from,t.to),w.maxOpen(r.finish())}matchTag(e,t,r){for(let i=r?this.tags.indexOf(r)+1:0;ie.length&&(l.charCodeAt(e.length)!=61||l.slice(e.length+1)!=t))){if(o.getAttrs){let a=o.getAttrs(t);if(a===!1)continue;o.attrs=a||void 0}return o}}}static schemaRules(e){let t=[];function r(i){let s=i.priority==null?50:i.priority,o=0;for(;o{r(o=Gs(o)),o.mark||o.ignore||o.clearMark||(o.mark=i)})}for(let i in e.nodes){let s=e.nodes[i].spec.parseDOM;s&&s.forEach(o=>{r(o=Gs(o)),o.node||o.ignore||o.mark||(o.node=i)})}return t}static fromSchema(e){return e.cached.domParser||(e.cached.domParser=new Xe(e,Xe.schemaRules(e)))}}const Hl={address:!0,article:!0,aside:!0,blockquote:!0,body:!0,canvas:!0,dd:!0,div:!0,dl:!0,fieldset:!0,figcaption:!0,figure:!0,footer:!0,form:!0,h1:!0,h2:!0,h3:!0,h4:!0,h5:!0,h6:!0,header:!0,hgroup:!0,hr:!0,li:!0,noscript:!0,ol:!0,output:!0,p:!0,pre:!0,section:!0,table:!0,tfoot:!0,ul:!0},Pu={head:!0,noscript:!0,object:!0,script:!0,style:!0,title:!0},jl={ol:!0,ul:!0},bn=1,Ni=2,rn=4;function qs(n,e,t){return e!=null?(e?bn:0)|(e==="full"?Ni:0):n&&n.whitespace=="pre"?bn|Ni:t&~rn}class Ln{constructor(e,t,r,i,s,o){this.type=e,this.attrs=t,this.marks=r,this.solid=i,this.options=o,this.content=[],this.activeMarks=B.none,this.match=s||(o&rn?null:e.contentMatch)}findWrapping(e){if(!this.match){if(!this.type)return[];let t=this.type.contentMatch.fillBefore(b.from(e));if(t)this.match=this.type.contentMatch.matchFragment(t);else{let r=this.type.contentMatch,i;return(i=r.findWrapping(e.type))?(this.match=r,i):null}}return this.match.findWrapping(e.type)}finish(e){if(!(this.options&bn)){let r=this.content[this.content.length-1],i;if(r&&r.isText&&(i=/[ \t\r\n\u000c]+$/.exec(r.text))){let s=r;r.text.length==i[0].length?this.content.pop():this.content[this.content.length-1]=s.withText(s.text.slice(0,s.text.length-i[0].length))}}let t=b.from(this.content);return!e&&this.match&&(t=t.append(this.match.fillBefore(b.empty,!0))),this.type?this.type.create(this.attrs,t,this.marks):t}inlineContext(e){return this.type?this.type.inlineContent:this.content.length?this.content[0].isInline:e.parentNode&&!Hl.hasOwnProperty(e.parentNode.nodeName.toLowerCase())}}class Js{constructor(e,t,r){this.parser=e,this.options=t,this.isOpen=r,this.open=0,this.localPreserveWS=!1;let i=t.topNode,s,o=qs(null,t.preserveWhitespace,0)|(r?rn:0);i?s=new Ln(i.type,i.attrs,B.none,!0,t.topMatch||i.type.contentMatch,o):r?s=new Ln(null,null,B.none,!0,null,o):s=new Ln(e.schema.topNodeType,null,B.none,!0,null,o),this.nodes=[s],this.find=t.findPositions,this.needsBlock=!1}get top(){return this.nodes[this.open]}addDOM(e,t){e.nodeType==3?this.addTextNode(e,t):e.nodeType==1&&this.addElement(e,t)}addTextNode(e,t){let r=e.nodeValue,i=this.top,s=i.options&Ni?"full":this.localPreserveWS||(i.options&bn)>0,{schema:o}=this.parser;if(s==="full"||i.inlineContext(e)||/[^ \t\r\n\u000c]/.test(r)){if(s)if(s==="full")r=r.replace(/\r\n?/g,` -`);else if(o.linebreakReplacement&&/[\r\n]/.test(r)&&this.top.findWrapping(o.linebreakReplacement.create())){let l=r.split(/\r?\n|\r/);for(let a=0;a!a.clearMark(c)):t=t.concat(this.parser.schema.marks[a.mark].create(a.attrs)),a.consuming===!1)l=a;else break}}return t}addElementByRule(e,t,r,i){let s,o;if(t.node)if(o=this.parser.schema.nodes[t.node],o.isLeaf)this.insertNode(o.create(t.attrs),r,e.nodeName=="BR")||this.leafFallback(e,r);else{let a=this.enter(o,t.attrs||null,r,t.preserveWhitespace);a&&(s=!0,r=a)}else{let a=this.parser.schema.marks[t.mark];r=r.concat(a.create(t.attrs))}let l=this.top;if(o&&o.isLeaf)this.findInside(e);else if(i)this.addElement(e,r,i);else if(t.getContent)this.findInside(e),t.getContent(e,this.parser.schema).forEach(a=>this.insertNode(a,r,!1));else{let a=e;typeof t.contentElement=="string"?a=e.querySelector(t.contentElement):typeof t.contentElement=="function"?a=t.contentElement(e):t.contentElement&&(a=t.contentElement),this.findAround(e,a,!0),this.addAll(a,r),this.findAround(e,a,!1)}s&&this.sync(l)&&this.open--}addAll(e,t,r,i){let s=r||0;for(let o=r?e.childNodes[r]:e.firstChild,l=i==null?null:e.childNodes[i];o!=l;o=o.nextSibling,++s)this.findAtPoint(e,s),this.addDOM(o,t);this.findAtPoint(e,s)}findPlace(e,t,r){let i,s;for(let o=this.open,l=0;o>=0;o--){let a=this.nodes[o],c=a.findWrapping(e);if(c&&(!i||i.length>c.length+l)&&(i=c,s=a,!c.length))break;if(a.solid){if(r)break;l+=2}}if(!i)return null;this.sync(s);for(let o=0;o(o.type?o.type.allowsMarkType(c.type):Ys(c.type,e))?(a=c.addToSet(a),!1):!0),this.nodes.push(new Ln(e,t,a,i,null,l)),this.open++,r}closeExtra(e=!1){let t=this.nodes.length-1;if(t>this.open){for(;t>this.open;t--)this.nodes[t-1].content.push(this.nodes[t].finish(e));this.nodes.length=this.open+1}}finish(){return this.open=0,this.closeExtra(this.isOpen),this.nodes[0].finish(!!(this.isOpen||this.options.topOpen))}sync(e){for(let t=this.open;t>=0;t--){if(this.nodes[t]==e)return this.open=t,!0;this.localPreserveWS&&(this.nodes[t].options|=bn)}return!1}get currentPos(){this.closeExtra();let e=0;for(let t=this.open;t>=0;t--){let r=this.nodes[t].content;for(let i=r.length-1;i>=0;i--)e+=r[i].nodeSize;t&&e++}return e}findAtPoint(e,t){if(this.find)for(let r=0;r-1)return e.split(/\s*\|\s*/).some(this.matchesContext,this);let t=e.split("/"),r=this.options.context,i=!this.isOpen&&(!r||r.parent.type==this.nodes[0].type),s=-(r?r.depth+1:0)+(i?0:1),o=(l,a)=>{for(;l>=0;l--){let c=t[l];if(c==""){if(l==t.length-1||l==0)continue;for(;a>=s;a--)if(o(l-1,a))return!0;return!1}else{let u=a>0||a==0&&i?this.nodes[a].type:r&&a>=s?r.node(a-s).type:null;if(!u||u.name!=c&&!u.isInGroup(c))return!1;a--}}return!0};return o(t.length-1,this.open)}textblockFromContext(){let e=this.options.context;if(e)for(let t=e.depth;t>=0;t--){let r=e.node(t).contentMatchAt(e.indexAfter(t)).defaultType;if(r&&r.isTextblock&&r.defaultAttrs)return r}for(let t in this.parser.schema.nodes){let r=this.parser.schema.nodes[t];if(r.isTextblock&&r.defaultAttrs)return r}}}function Bu(n){for(let e=n.firstChild,t=null;e;e=e.nextSibling){let r=e.nodeType==1?e.nodeName.toLowerCase():null;r&&jl.hasOwnProperty(r)&&t?(t.appendChild(e),e=t):r=="li"?t=e:r&&(t=null)}}function zu(n,e){return(n.matches||n.msMatchesSelector||n.webkitMatchesSelector||n.mozMatchesSelector).call(n,e)}function Gs(n){let e={};for(let t in n)e[t]=n[t];return e}function Ys(n,e){let t=e.schema.nodes;for(let r in t){let i=t[r];if(!i.allowsMarkType(n))continue;let s=[],o=l=>{s.push(l);for(let a=0;a{if(s.length||o.marks.length){let l=0,a=0;for(;l=0;i--){let s=this.serializeMark(e.marks[i],e.isInline,t);s&&((s.contentDOM||s.dom).appendChild(r),r=s.dom)}return r}serializeMark(e,t,r={}){let i=this.marks[e.type.name];return i&&Un(Pn(r),i(e,t),null,e.attrs)}static renderSpec(e,t,r=null,i){return typeof t=="string"?{dom:e.createTextNode(t)}:Un(e,t,r,i)}static fromSchema(e){return e.cached.domSerializer||(e.cached.domSerializer=new st(this.nodesFromSchema(e),this.marksFromSchema(e)))}static nodesFromSchema(e){let t=Xs(e.nodes);return t.text||(t.text=r=>r.text),t}static marksFromSchema(e){return Xs(e.marks)}}function Xs(n){let e={};for(let t in n){let r=n[t].spec.toDOM;r&&(e[t]=r)}return e}function Pn(n){return n.document||window.document}const Qs=new WeakMap;function $u(n){let e=Qs.get(n);return e===void 0&&Qs.set(n,e=Fu(n)),e}function Fu(n){let e=null;function t(r){if(r&&typeof r=="object")if(Array.isArray(r))if(typeof r[0]=="string")e||(e=[]),e.push(r);else for(let i=0;i-1)throw new RangeError("Using an array from an attribute object as a DOM spec. This may be an attempted cross site scripting attack.");let o=i.indexOf(" ");o>0&&(t=i.slice(0,o),i=i.slice(o+1));let l,a=t?n.createElementNS(t,i):n.createElement(i),c=e[1],u=1;if(c&&typeof c=="object"&&c.nodeType==null&&!Array.isArray(c)){u=2;for(let d in c)if(c[d]!=null){let f=d.indexOf(" ");f>0?a.setAttributeNS(d.slice(0,f),d.slice(f+1),c[d]):d=="style"&&a.style?a.style.cssText=c[d]:a.setAttribute(d,c[d])}}for(let d=u;du)throw new RangeError("Content hole must be the only child of its parent node");return{dom:a,contentDOM:a}}else if(typeof f=="string")a.appendChild(n.createTextNode(f));else{let{dom:h,contentDOM:p}=Un(n,f,t,r);if(a.appendChild(h),p){if(l)throw new RangeError("Multiple content holes");l=p}}}return{dom:a,contentDOM:l}}const Wl=65535,Kl=Math.pow(2,16);function Vu(n,e){return n+e*Kl}function Zs(n){return n&Wl}function Hu(n){return(n-(n&Wl))/Kl}const _l=1,Ul=2,qn=4,ql=8;class Di{constructor(e,t,r){this.pos=e,this.delInfo=t,this.recover=r}get deleted(){return(this.delInfo&ql)>0}get deletedBefore(){return(this.delInfo&(_l|qn))>0}get deletedAfter(){return(this.delInfo&(Ul|qn))>0}get deletedAcross(){return(this.delInfo&qn)>0}}class de{constructor(e,t=!1){if(this.ranges=e,this.inverted=t,!e.length&&de.empty)return de.empty}recover(e){let t=0,r=Zs(e);if(!this.inverted)for(let i=0;ie)break;let c=this.ranges[l+s],u=this.ranges[l+o],d=a+c;if(e<=d){let f=c?e==a?-1:e==d?1:t:t,h=a+i+(f<0?0:u);if(r)return h;let p=e==(t<0?a:d)?null:Vu(l/3,e-a),m=0;return c&&(m|=e==a?Ul:e==d?_l:qn,(t<0?e!=a:e!=d)&&(m|=ql)),new Di(h,m,p)}i+=u-c}return r?e+i:new Di(e+i,0,null)}touches(e,t){let r=0,i=Zs(t),s=this.inverted?2:1,o=this.inverted?1:2;for(let l=0;le)break;let c=this.ranges[l+s],u=a+c;if(e<=u&&l==i*3)return!0;r+=this.ranges[l+o]-c}return!1}forEach(e){let t=this.inverted?2:1,r=this.inverted?1:2;for(let i=0,s=0;i=0;t--){let i=e.getMirror(t);this.appendMap(e._maps[t].invert(),i!=null&&i>t?r-i-1:void 0)}}invert(){let e=new kn;return e.appendMappingInverted(this),e}map(e,t=1){if(this.mirror)return this._map(e,t,!0);for(let r=this.from;rs&&a!o.isAtom||!l.type.allowsMarkType(this.mark.type)?o:o.mark(this.mark.addToSet(o.marks)),i),t.openStart,t.openEnd);return K.fromReplace(e,this.from,this.to,s)}invert(){return new Ce(this.from,this.to,this.mark)}map(e){let t=e.mapResult(this.from,1),r=e.mapResult(this.to,-1);return t.deleted&&r.deleted||t.pos>=r.pos?null:new Ge(t.pos,r.pos,this.mark)}merge(e){return e instanceof Ge&&e.mark.eq(this.mark)&&this.from<=e.to&&this.to>=e.from?new Ge(Math.min(this.from,e.from),Math.max(this.to,e.to),this.mark):null}toJSON(){return{stepType:"addMark",mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(e,t){if(typeof t.from!="number"||typeof t.to!="number")throw new RangeError("Invalid input for AddMarkStep.fromJSON");return new Ge(t.from,t.to,e.markFromJSON(t.mark))}}se.jsonID("addMark",Ge);class Ce extends se{constructor(e,t,r){super(),this.from=e,this.to=t,this.mark=r}apply(e){let t=e.slice(this.from,this.to),r=new w(ss(t.content,i=>i.mark(this.mark.removeFromSet(i.marks)),e),t.openStart,t.openEnd);return K.fromReplace(e,this.from,this.to,r)}invert(){return new Ge(this.from,this.to,this.mark)}map(e){let t=e.mapResult(this.from,1),r=e.mapResult(this.to,-1);return t.deleted&&r.deleted||t.pos>=r.pos?null:new Ce(t.pos,r.pos,this.mark)}merge(e){return e instanceof Ce&&e.mark.eq(this.mark)&&this.from<=e.to&&this.to>=e.from?new Ce(Math.min(this.from,e.from),Math.max(this.to,e.to),this.mark):null}toJSON(){return{stepType:"removeMark",mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(e,t){if(typeof t.from!="number"||typeof t.to!="number")throw new RangeError("Invalid input for RemoveMarkStep.fromJSON");return new Ce(t.from,t.to,e.markFromJSON(t.mark))}}se.jsonID("removeMark",Ce);class Ye extends se{constructor(e,t){super(),this.pos=e,this.mark=t}apply(e){let t=e.nodeAt(this.pos);if(!t)return K.fail("No node at mark step's position");let r=t.type.create(t.attrs,null,this.mark.addToSet(t.marks));return K.fromReplace(e,this.pos,this.pos+1,new w(b.from(r),0,t.isLeaf?0:1))}invert(e){let t=e.nodeAt(this.pos);if(t){let r=this.mark.addToSet(t.marks);if(r.length==t.marks.length){for(let i=0;ir.pos?null:new G(t.pos,r.pos,i,s,this.slice,this.insert,this.structure)}toJSON(){let e={stepType:"replaceAround",from:this.from,to:this.to,gapFrom:this.gapFrom,gapTo:this.gapTo,insert:this.insert};return this.slice.size&&(e.slice=this.slice.toJSON()),this.structure&&(e.structure=!0),e}static fromJSON(e,t){if(typeof t.from!="number"||typeof t.to!="number"||typeof t.gapFrom!="number"||typeof t.gapTo!="number"||typeof t.insert!="number")throw new RangeError("Invalid input for ReplaceAroundStep.fromJSON");return new G(t.from,t.to,t.gapFrom,t.gapTo,w.fromJSON(e,t.slice),t.insert,!!t.structure)}}se.jsonID("replaceAround",G);function Ii(n,e,t){let r=n.resolve(e),i=t-e,s=r.depth;for(;i>0&&s>0&&r.indexAfter(s)==r.node(s).childCount;)s--,i--;if(i>0){let o=r.node(s).maybeChild(r.indexAfter(s));for(;i>0;){if(!o||o.isLeaf)return!0;o=o.firstChild,i--}}return!1}function ju(n,e,t,r){let i=[],s=[],o,l;n.doc.nodesBetween(e,t,(a,c,u)=>{if(!a.isInline)return;let d=a.marks;if(!r.isInSet(d)&&u.type.allowsMarkType(r.type)){let f=Math.max(c,e),h=Math.min(c+a.nodeSize,t),p=r.addToSet(d);for(let m=0;mn.step(a)),s.forEach(a=>n.step(a))}function Wu(n,e,t,r){let i=[],s=0;n.doc.nodesBetween(e,t,(o,l)=>{if(!o.isInline)return;s++;let a=null;if(r instanceof Fr){let c=o.marks,u;for(;u=r.isInSet(c);)(a||(a=[])).push(u),c=u.removeFromSet(c)}else r?r.isInSet(o.marks)&&(a=[r]):a=o.marks;if(a&&a.length){let c=Math.min(l+o.nodeSize,t);for(let u=0;un.step(new Ce(o.from,o.to,o.style)))}function ls(n,e,t,r=t.contentMatch,i=!0){let s=n.doc.nodeAt(e),o=[],l=e+1;for(let a=0;a=0;a--)n.step(o[a])}function Ku(n,e,t){return(e==0||n.canReplace(e,n.childCount))&&(t==n.childCount||n.canReplace(0,t))}function Ut(n){let t=n.parent.content.cutByIndex(n.startIndex,n.endIndex);for(let r=n.depth,i=0,s=0;;--r){let o=n.$from.node(r),l=n.$from.index(r)+i,a=n.$to.indexAfter(r)-s;if(rt;p--)m||r.index(p)>0?(m=!0,u=b.from(r.node(p).copy(u)),d++):a--;let f=b.empty,h=0;for(let p=s,m=!1;p>t;p--)m||i.after(p+1)=0;o--){if(r.size){let l=t[o].type.contentMatch.matchFragment(r);if(!l||!l.validEnd)throw new RangeError("Wrapper type given to Transform.wrap does not form valid content of its parent wrapper")}r=b.from(t[o].type.create(t[o].attrs,r))}let i=e.start,s=e.end;n.step(new G(i,s,i,s,new w(r,0,0),t.length,!0))}function Gu(n,e,t,r,i){if(!r.isTextblock)throw new RangeError("Type given to setBlockType should be a textblock");let s=n.steps.length;n.doc.nodesBetween(e,t,(o,l)=>{let a=typeof i=="function"?i(o):i;if(o.isTextblock&&!o.hasMarkup(r,a)&&Yu(n.doc,n.mapping.slice(s).map(l),r)){let c=null;if(r.schema.linebreakReplacement){let h=r.whitespace=="pre",p=!!r.contentMatch.matchType(r.schema.linebreakReplacement);h&&!p?c=!1:!h&&p&&(c=!0)}c===!1&&Gl(n,o,l,s),ls(n,n.mapping.slice(s).map(l,1),r,void 0,c===null);let u=n.mapping.slice(s),d=u.map(l,1),f=u.map(l+o.nodeSize,1);return n.step(new G(d,f,d+1,f-1,new w(b.from(r.create(a,null,o.marks)),0,0),1,!0)),c===!0&&Jl(n,o,l,s),!1}})}function Jl(n,e,t,r){e.forEach((i,s)=>{if(i.isText){let o,l=/\r?\n|\r/g;for(;o=l.exec(i.text);){let a=n.mapping.slice(r).map(t+1+s+o.index);n.replaceWith(a,a+1,e.type.schema.linebreakReplacement.create())}}})}function Gl(n,e,t,r){e.forEach((i,s)=>{if(i.type==i.type.schema.linebreakReplacement){let o=n.mapping.slice(r).map(t+1+s);n.replaceWith(o,o+1,e.type.schema.text(` -`))}})}function Yu(n,e,t){let r=n.resolve(e),i=r.index();return r.parent.canReplaceWith(i,i+1,t)}function Xu(n,e,t,r,i){let s=n.doc.nodeAt(e);if(!s)throw new RangeError("No node at given position");t||(t=s.type);let o=t.create(r,null,i||s.marks);if(s.isLeaf)return n.replaceWith(e,e+s.nodeSize,o);if(!t.validContent(s.content))throw new RangeError("Invalid content for node type "+t.name);n.step(new G(e,e+s.nodeSize,e+1,e+s.nodeSize-1,new w(b.from(o),0,0),1,!0))}function Fe(n,e,t=1,r){let i=n.resolve(e),s=i.depth-t,o=r&&r[r.length-1]||i.parent;if(s<0||i.parent.type.spec.isolating||!i.parent.canReplace(i.index(),i.parent.childCount)||!o.type.validContent(i.parent.content.cutByIndex(i.index(),i.parent.childCount)))return!1;for(let c=i.depth-1,u=t-2;c>s;c--,u--){let d=i.node(c),f=i.index(c);if(d.type.spec.isolating)return!1;let h=d.content.cutByIndex(f,d.childCount),p=r&&r[u+1];p&&(h=h.replaceChild(0,p.type.create(p.attrs)));let m=r&&r[u]||d;if(!d.canReplace(f+1,d.childCount)||!m.type.validContent(h))return!1}let l=i.indexAfter(s),a=r&&r[0];return i.node(s).canReplaceWith(l,l,a?a.type:i.node(s+1).type)}function Qu(n,e,t=1,r){let i=n.doc.resolve(e),s=b.empty,o=b.empty;for(let l=i.depth,a=i.depth-t,c=t-1;l>a;l--,c--){s=b.from(i.node(l).copy(s));let u=r&&r[c];o=b.from(u?u.type.create(u.attrs,o):i.node(l).copy(o))}n.step(new H(e,e,new w(s.append(o),t,t),!0))}function ot(n,e){let t=n.resolve(e),r=t.index();return Yl(t.nodeBefore,t.nodeAfter)&&t.parent.canReplace(r,r+1)}function Zu(n,e){e.content.size||n.type.compatibleContent(e.type);let t=n.contentMatchAt(n.childCount),{linebreakReplacement:r}=n.type.schema;for(let i=0;i0?(s=r.node(i+1),l++,o=r.node(i).maybeChild(l)):(s=r.node(i).maybeChild(l-1),o=r.node(i+1)),s&&!s.isTextblock&&Yl(s,o)&&r.node(i).canReplace(l,l+1))return e;if(i==0)break;e=t<0?r.before(i):r.after(i)}}function ed(n,e,t){let r=null,{linebreakReplacement:i}=n.doc.type.schema,s=n.doc.resolve(e-t),o=s.node().type;if(i&&o.inlineContent){let u=o.whitespace=="pre",d=!!o.contentMatch.matchType(i);u&&!d?r=!1:!u&&d&&(r=!0)}let l=n.steps.length;if(r===!1){let u=n.doc.resolve(e+t);Gl(n,u.node(),u.before(),l)}o.inlineContent&&ls(n,e+t-1,o,s.node().contentMatchAt(s.index()),r==null);let a=n.mapping.slice(l),c=a.map(e-t);if(n.step(new H(c,a.map(e+t,-1),w.empty,!0)),r===!0){let u=n.doc.resolve(c);Jl(n,u.node(),u.before(),n.steps.length)}return n}function td(n,e,t){let r=n.resolve(e);if(r.parent.canReplaceWith(r.index(),r.index(),t))return e;if(r.parentOffset==0)for(let i=r.depth-1;i>=0;i--){let s=r.index(i);if(r.node(i).canReplaceWith(s,s,t))return r.before(i+1);if(s>0)return null}if(r.parentOffset==r.parent.content.size)for(let i=r.depth-1;i>=0;i--){let s=r.indexAfter(i);if(r.node(i).canReplaceWith(s,s,t))return r.after(i+1);if(s=0;o--){let l=o==r.depth?0:r.pos<=(r.start(o+1)+r.end(o+1))/2?-1:1,a=r.index(o)+(l>0?1:0),c=r.node(o),u=!1;if(s==1)u=c.canReplace(a,a,i);else{let d=c.contentMatchAt(a).findWrapping(i.firstChild.type);u=d&&c.canReplaceWith(a,a,d[0])}if(u)return l==0?r.pos:l<0?r.before(o+1):r.after(o+1)}return null}function Hr(n,e,t=e,r=w.empty){if(e==t&&!r.size)return null;let i=n.resolve(e),s=n.resolve(t);return Ql(i,s,r)?new H(e,t,r):new nd(i,s,r).fit()}function Ql(n,e,t){return!t.openStart&&!t.openEnd&&n.start()==e.start()&&n.parent.canReplace(n.index(),e.index(),t.content)}class nd{constructor(e,t,r){this.$from=e,this.$to=t,this.unplaced=r,this.frontier=[],this.placed=b.empty;for(let i=0;i<=e.depth;i++){let s=e.node(i);this.frontier.push({type:s.type,match:s.contentMatchAt(e.indexAfter(i))})}for(let i=e.depth;i>0;i--)this.placed=b.from(e.node(i).copy(this.placed))}get depth(){return this.frontier.length-1}fit(){for(;this.unplaced.size;){let c=this.findFittable();c?this.placeNodes(c):this.openMore()||this.dropNode()}let e=this.mustMoveInline(),t=this.placed.size-this.depth-this.$from.depth,r=this.$from,i=this.close(e<0?this.$to:r.doc.resolve(e));if(!i)return null;let s=this.placed,o=r.depth,l=i.depth;for(;o&&l&&s.childCount==1;)s=s.firstChild.content,o--,l--;let a=new w(s,o,l);return e>-1?new G(r.pos,e,this.$to.pos,this.$to.end(),a,t):a.size||r.pos!=this.$to.pos?new H(r.pos,i.pos,a):null}findFittable(){let e=this.unplaced.openStart;for(let t=this.unplaced.content,r=0,i=this.unplaced.openEnd;r1&&(i=0),s.type.spec.isolating&&i<=r){e=r;break}t=s.content}for(let t=1;t<=2;t++)for(let r=t==1?e:this.unplaced.openStart;r>=0;r--){let i,s=null;r?(s=to(this.unplaced.content,r-1).firstChild,i=s.content):i=this.unplaced.content;let o=i.firstChild;for(let l=this.depth;l>=0;l--){let{type:a,match:c}=this.frontier[l],u,d=null;if(t==1&&(o?c.matchType(o.type)||(d=c.fillBefore(b.from(o),!1)):s&&a.compatibleContent(s.type)))return{sliceDepth:r,frontierDepth:l,parent:s,inject:d};if(t==2&&o&&(u=c.findWrapping(o.type)))return{sliceDepth:r,frontierDepth:l,parent:s,wrap:u};if(s&&c.matchType(s.type))break}}}openMore(){let{content:e,openStart:t,openEnd:r}=this.unplaced;return no(e,-1)<=t?!1:(this.unplaced.size>1&&no(e,1)>r&&r++,this.unplaced=new w(e,t+1,r),!0)}dropNode(){let{content:e,openStart:t,openEnd:r}=this.unplaced,i=to(e,t);if(i.childCount<=1&&t>0){let s=e.size-t<=t+i.size;this.unplaced=new w(Xt(e,t-1,1),t-1,s?t-1:r)}else this.unplaced=new w(Xt(e,t,1),t,r)}placeNodes({sliceDepth:e,frontierDepth:t,parent:r,inject:i,wrap:s}){for(;this.depth>t;)this.closeFrontierNode();if(s)for(let m=0;m1||a==0||m.content.size)&&(d=g,u.push(Zl(m.mark(f.allowedMarks(m.marks)),c==1?a:0,c==l.childCount?h:-1)))}let p=c==l.childCount;p||(h=-1),this.placed=Qt(this.placed,t,b.from(u)),this.frontier[t].match=d,p&&h<0&&r&&r.type==this.frontier[this.depth].type&&this.frontier.length>1&&this.closeFrontierNode();for(let m=0,g=l;m1&&i==this.$to.end(--r);)++i;return i}findCloseLevel(e){e:for(let t=Math.min(this.depth,e.depth);t>=0;t--){let{match:r,type:i}=this.frontier[t],s=t=0;l--){let{match:a,type:c}=this.frontier[l],u=ii(e,l,c,a,!0);if(!u||u.childCount)continue e}return{depth:t,fit:o,move:s?e.doc.resolve(e.after(t+1)):e}}}}close(e){let t=this.findCloseLevel(e);if(!t)return null;for(;this.depth>t.depth;)this.closeFrontierNode();t.fit.childCount&&(this.placed=Qt(this.placed,t.depth,t.fit)),e=t.move;for(let r=t.depth+1;r<=e.depth;r++){let i=e.node(r),s=i.type.contentMatch.fillBefore(i.content,!0,e.index(r));this.openFrontierNode(i.type,i.attrs,s)}return e}openFrontierNode(e,t=null,r){let i=this.frontier[this.depth];i.match=i.match.matchType(e),this.placed=Qt(this.placed,this.depth,b.from(e.create(t,r))),this.frontier.push({type:e,match:e.contentMatch})}closeFrontierNode(){let t=this.frontier.pop().match.fillBefore(b.empty,!0);t.childCount&&(this.placed=Qt(this.placed,this.frontier.length,t))}}function Xt(n,e,t){return e==0?n.cutByIndex(t,n.childCount):n.replaceChild(0,n.firstChild.copy(Xt(n.firstChild.content,e-1,t)))}function Qt(n,e,t){return e==0?n.append(t):n.replaceChild(n.childCount-1,n.lastChild.copy(Qt(n.lastChild.content,e-1,t)))}function to(n,e){for(let t=0;t1&&(r=r.replaceChild(0,Zl(r.firstChild,e-1,r.childCount==1?t-1:0))),e>0&&(r=n.type.contentMatch.fillBefore(r).append(r),t<=0&&(r=r.append(n.type.contentMatch.matchFragment(r).fillBefore(b.empty,!0)))),n.copy(r)}function ii(n,e,t,r,i){let s=n.node(e),o=i?n.indexAfter(e):n.index(e);if(o==s.childCount&&!t.compatibleContent(s.type))return null;let l=r.fillBefore(s.content,!0,o);return l&&!rd(t,s.content,o)?l:null}function rd(n,e,t){for(let r=t;r0;f--,h--){let p=i.node(f).type.spec;if(p.defining||p.definingAsContext||p.isolating)break;o.indexOf(f)>-1?l=f:i.before(f)==h&&o.splice(1,0,-f)}let a=o.indexOf(l),c=[],u=r.openStart;for(let f=r.content,h=0;;h++){let p=f.firstChild;if(c.push(p),h==r.openStart)break;f=p.content}for(let f=u-1;f>=0;f--){let h=c[f],p=id(h.type);if(p&&!h.sameMarkup(i.node(Math.abs(l)-1)))u=f;else if(p||!h.type.isTextblock)break}for(let f=r.openStart;f>=0;f--){let h=(f+u+1)%(r.openStart+1),p=c[h];if(p)for(let m=0;m=0&&(n.replace(e,t,r),!(n.steps.length>d));f--){let h=o[f];h<0||(e=i.before(h),t=s.after(h))}}function ea(n,e,t,r,i){if(er){let s=i.contentMatchAt(0),o=s.fillBefore(n).append(n);n=o.append(s.matchFragment(o).fillBefore(b.empty,!0))}return n}function od(n,e,t,r){if(!r.isInline&&e==t&&n.doc.resolve(e).parent.content.size){let i=td(n.doc,e,r.type);i!=null&&(e=t=i)}n.replaceRange(e,t,new w(b.from(r),0,0))}function ld(n,e,t){let r=n.doc.resolve(e),i=n.doc.resolve(t);if(r.parent.isTextblock&&i.parent.isTextblock&&r.start()!=i.start()&&r.parentOffset==0&&i.parentOffset==0){let o=r.sharedDepth(t),l=!1;for(let a=r.depth;a>o;a--)r.node(a).type.spec.isolating&&(l=!0);for(let a=i.depth;a>o;a--)i.node(a).type.spec.isolating&&(l=!0);if(!l){for(let a=r.depth;a>0&&e==r.start(a);a--)e=r.before(a);for(let a=i.depth;a>0&&t==i.start(a);a--)t=i.before(a);r=n.doc.resolve(e),i=n.doc.resolve(t)}}let s=ta(r,i);for(let o=0;o0&&(a||r.node(l-1).canReplace(r.index(l-1),i.indexAfter(l-1))))return n.delete(r.before(l),i.after(l))}for(let o=1;o<=r.depth&&o<=i.depth;o++)if(e-r.start(o)==r.depth-o&&t>r.end(o)&&i.end(o)-t!=i.depth-o&&r.start(o-1)==i.start(o-1)&&r.node(o-1).canReplace(r.index(o-1),i.index(o-1)))return n.delete(r.before(o),t);n.delete(e,t)}function ta(n,e){let t=[],r=Math.min(n.depth,e.depth);for(let i=r;i>=0;i--){let s=n.start(i);if(se.pos+(e.depth-i)||n.node(i).type.spec.isolating||e.node(i).type.spec.isolating)break;(s==e.start(i)||i==n.depth&&i==e.depth&&n.parent.inlineContent&&e.parent.inlineContent&&i&&e.start(i-1)==s-1)&&t.push(i)}return t}class zt extends se{constructor(e,t,r){super(),this.pos=e,this.attr=t,this.value=r}apply(e){let t=e.nodeAt(this.pos);if(!t)return K.fail("No node at attribute step's position");let r=Object.create(null);for(let s in t.attrs)r[s]=t.attrs[s];r[this.attr]=this.value;let i=t.type.create(r,null,t.marks);return K.fromReplace(e,this.pos,this.pos+1,new w(b.from(i),0,t.isLeaf?0:1))}getMap(){return de.empty}invert(e){return new zt(this.pos,this.attr,e.nodeAt(this.pos).attrs[this.attr])}map(e){let t=e.mapResult(this.pos,1);return t.deletedAfter?null:new zt(t.pos,this.attr,this.value)}toJSON(){return{stepType:"attr",pos:this.pos,attr:this.attr,value:this.value}}static fromJSON(e,t){if(typeof t.pos!="number"||typeof t.attr!="string")throw new RangeError("Invalid input for AttrStep.fromJSON");return new zt(t.pos,t.attr,t.value)}}se.jsonID("attr",zt);class Sn extends se{constructor(e,t){super(),this.attr=e,this.value=t}apply(e){let t=Object.create(null);for(let i in e.attrs)t[i]=e.attrs[i];t[this.attr]=this.value;let r=e.type.create(t,e.content,e.marks);return K.ok(r)}getMap(){return de.empty}invert(e){return new Sn(this.attr,e.attrs[this.attr])}map(e){return this}toJSON(){return{stepType:"docAttr",attr:this.attr,value:this.value}}static fromJSON(e,t){if(typeof t.attr!="string")throw new RangeError("Invalid input for DocAttrStep.fromJSON");return new Sn(t.attr,t.value)}}se.jsonID("docAttr",Sn);let Ft=class extends Error{};Ft=function n(e){let t=Error.call(this,e);return t.__proto__=n.prototype,t};Ft.prototype=Object.create(Error.prototype);Ft.prototype.constructor=Ft;Ft.prototype.name="TransformError";class na{constructor(e){this.doc=e,this.steps=[],this.docs=[],this.mapping=new kn}get before(){return this.docs.length?this.docs[0]:this.doc}step(e){let t=this.maybeStep(e);if(t.failed)throw new Ft(t.failed);return this}maybeStep(e){let t=e.apply(this.doc);return t.failed||this.addStep(e,t.doc),t}get docChanged(){return this.steps.length>0}changedRange(){let e=1e9,t=-1e9;for(let r=0;r{e=Math.min(e,l),t=Math.max(t,a)})}return e==1e9?null:{from:e,to:t}}addStep(e,t){this.docs.push(this.doc),this.steps.push(e),this.mapping.appendMap(e.getMap()),this.doc=t}replace(e,t=e,r=w.empty){let i=Hr(this.doc,e,t,r);return i&&this.step(i),this}replaceWith(e,t,r){return this.replace(e,t,new w(b.from(r),0,0))}delete(e,t){return this.replace(e,t,w.empty)}insert(e,t){return this.replaceWith(e,e,t)}replaceRange(e,t,r){return sd(this,e,t,r),this}replaceRangeWith(e,t,r){return od(this,e,t,r),this}deleteRange(e,t){return ld(this,e,t),this}lift(e,t){return _u(this,e,t),this}join(e,t=1){return ed(this,e,t),this}wrap(e,t){return Ju(this,e,t),this}setBlockType(e,t=e,r,i=null){return Gu(this,e,t,r,i),this}setNodeMarkup(e,t,r=null,i){return Xu(this,e,t,r,i),this}setNodeAttribute(e,t,r){return this.step(new zt(e,t,r)),this}setDocAttribute(e,t){return this.step(new Sn(e,t)),this}addNodeMark(e,t){return this.step(new Ye(e,t)),this}removeNodeMark(e,t){let r=this.doc.nodeAt(e);if(!r)throw new RangeError("No node at position "+e);if(t instanceof B)t.isInSet(r.marks)&&this.step(new wt(e,t));else{let i=r.marks,s,o=[];for(;s=t.isInSet(i);)o.push(new wt(e,s)),i=s.removeFromSet(i);for(let l=o.length-1;l>=0;l--)this.step(o[l])}return this}split(e,t=1,r){return Qu(this,e,t,r),this}addMark(e,t,r){return ju(this,e,t,r),this}removeMark(e,t,r){return Wu(this,e,t,r),this}clearIncompatible(e,t,r){return ls(this,e,t,r),this}}const si=Object.create(null);class O{constructor(e,t,r){this.$anchor=e,this.$head=t,this.ranges=r||[new ad(e.min(t),e.max(t))]}get anchor(){return this.$anchor.pos}get head(){return this.$head.pos}get from(){return this.$from.pos}get to(){return this.$to.pos}get $from(){return this.ranges[0].$from}get $to(){return this.ranges[0].$to}get empty(){let e=this.ranges;for(let t=0;t=0;s--){let o=t<0?It(e.node(0),e.node(s),e.before(s+1),e.index(s),t,r):It(e.node(0),e.node(s),e.after(s+1),e.index(s)+1,t,r);if(o)return o}return null}static near(e,t=1){return this.findFrom(e,t)||this.findFrom(e,-t)||new fe(e.node(0))}static atStart(e){return It(e,e,0,0,1)||new fe(e)}static atEnd(e){return It(e,e,e.content.size,e.childCount,-1)||new fe(e)}static fromJSON(e,t){if(!t||!t.type)throw new RangeError("Invalid input for Selection.fromJSON");let r=si[t.type];if(!r)throw new RangeError(`No selection type ${t.type} defined`);return r.fromJSON(e,t)}static jsonID(e,t){if(e in si)throw new RangeError("Duplicate use of selection JSON ID "+e);return si[e]=t,t.prototype.jsonID=e,t}getBookmark(){return T.between(this.$anchor,this.$head).getBookmark()}}O.prototype.visible=!0;class ad{constructor(e,t){this.$from=e,this.$to=t}}let ro=!1;function io(n){!ro&&!n.parent.inlineContent&&(ro=!0,console.warn("TextSelection endpoint not pointing into a node with inline content ("+n.parent.type.name+")"))}class T extends O{constructor(e,t=e){io(e),io(t),super(e,t)}get $cursor(){return this.$anchor.pos==this.$head.pos?this.$head:null}map(e,t){let r=e.resolve(t.map(this.head));if(!r.parent.inlineContent)return O.near(r);let i=e.resolve(t.map(this.anchor));return new T(i.parent.inlineContent?i:r,r)}replace(e,t=w.empty){if(super.replace(e,t),t==w.empty){let r=this.$from.marksAcross(this.$to);r&&e.ensureMarks(r)}}eq(e){return e instanceof T&&e.anchor==this.anchor&&e.head==this.head}getBookmark(){return new jr(this.anchor,this.head)}toJSON(){return{type:"text",anchor:this.anchor,head:this.head}}static fromJSON(e,t){if(typeof t.anchor!="number"||typeof t.head!="number")throw new RangeError("Invalid input for TextSelection.fromJSON");return new T(e.resolve(t.anchor),e.resolve(t.head))}static create(e,t,r=t){let i=e.resolve(t);return new this(i,r==t?i:e.resolve(r))}static between(e,t,r){let i=e.pos-t.pos;if((!r||i)&&(r=i>=0?1:-1),!t.parent.inlineContent){let s=O.findFrom(t,r,!0)||O.findFrom(t,-r,!0);if(s)t=s.$head;else return O.near(t,r)}return e.parent.inlineContent||(i==0?e=t:(e=(O.findFrom(e,-r,!0)||O.findFrom(e,r,!0)).$anchor,e.pos0?0:1);i>0?o=0;o+=i){let l=e.child(o);if(l.isAtom){if(!s&&E.isSelectable(l))return E.create(n,t-(i<0?l.nodeSize:0))}else{let a=It(n,l,t+i,i<0?l.childCount:0,i,s);if(a)return a}t+=l.nodeSize*i}return null}function so(n,e,t){let r=n.steps.length-1;if(r{o==null&&(o=u)}),n.setSelection(O.near(n.doc.resolve(o),t))}const oo=1,Bn=2,lo=4;class ud extends na{constructor(e){super(e.doc),this.curSelectionFor=0,this.updated=0,this.meta=Object.create(null),this.time=Date.now(),this.curSelection=e.selection,this.storedMarks=e.storedMarks}get selection(){return this.curSelectionFor0}setStoredMarks(e){return this.storedMarks=e,this.updated|=Bn,this}ensureMarks(e){return B.sameSet(this.storedMarks||this.selection.$from.marks(),e)||this.setStoredMarks(e),this}addStoredMark(e){return this.ensureMarks(e.addToSet(this.storedMarks||this.selection.$head.marks()))}removeStoredMark(e){return this.ensureMarks(e.removeFromSet(this.storedMarks||this.selection.$head.marks()))}get storedMarksSet(){return(this.updated&Bn)>0}addStep(e,t){super.addStep(e,t),this.updated=this.updated&~Bn,this.storedMarks=null}setTime(e){return this.time=e,this}replaceSelection(e){return this.selection.replace(this,e),this}replaceSelectionWith(e,t=!0){let r=this.selection;return t&&(e=e.mark(this.storedMarks||(r.empty?r.$from.marks():r.$from.marksAcross(r.$to)||B.none))),r.replaceWith(this,e),this}deleteSelection(){return this.selection.replace(this),this}insertText(e,t,r){let i=this.doc.type.schema;if(t==null)return e?this.replaceSelectionWith(i.text(e),!0):this.deleteSelection();{if(r==null&&(r=t),!e)return this.deleteRange(t,r);let s=this.storedMarks;if(!s){let o=this.doc.resolve(t);s=r==t?o.marks():o.marksAcross(this.doc.resolve(r))}return this.replaceRangeWith(t,r,i.text(e,s)),!this.selection.empty&&this.selection.to==t+e.length&&this.setSelection(O.near(this.selection.$to)),this}}setMeta(e,t){return this.meta[typeof e=="string"?e:e.key]=t,this}getMeta(e){return this.meta[typeof e=="string"?e:e.key]}get isGeneric(){for(let e in this.meta)return!1;return!0}scrollIntoView(){return this.updated|=lo,this}get scrolledIntoView(){return(this.updated&lo)>0}}function ao(n,e){return!e||!n?n:n.bind(e)}class Zt{constructor(e,t,r){this.name=e,this.init=ao(t.init,r),this.apply=ao(t.apply,r)}}const dd=[new Zt("doc",{init(n){return n.doc||n.schema.topNodeType.createAndFill()},apply(n){return n.doc}}),new Zt("selection",{init(n,e){return n.selection||O.atStart(e.doc)},apply(n){return n.selection}}),new Zt("storedMarks",{init(n){return n.storedMarks||null},apply(n,e,t,r){return r.selection.$cursor?n.storedMarks:null}}),new Zt("scrollToSelection",{init(){return 0},apply(n,e){return n.scrolledIntoView?e+1:e}})];class oi{constructor(e,t){this.schema=e,this.plugins=[],this.pluginsByKey=Object.create(null),this.fields=dd.slice(),t&&t.forEach(r=>{if(this.pluginsByKey[r.key])throw new RangeError("Adding different instances of a keyed plugin ("+r.key+")");this.plugins.push(r),this.pluginsByKey[r.key]=r,r.spec.state&&this.fields.push(new Zt(r.key,r.spec.state,r))})}}class Be{constructor(e){this.config=e}get schema(){return this.config.schema}get plugins(){return this.config.plugins}apply(e){return this.applyTransaction(e).state}filterTransaction(e,t=-1){for(let r=0;rr.toJSON())),e&&typeof e=="object")for(let r in e){if(r=="doc"||r=="selection")throw new RangeError("The JSON fields `doc` and `selection` are reserved");let i=e[r],s=i.spec.state;s&&s.toJSON&&(t[r]=s.toJSON.call(i,this[i.key]))}return t}static fromJSON(e,t,r){if(!t)throw new RangeError("Invalid input for EditorState.fromJSON");if(!e.schema)throw new RangeError("Required config field 'schema' missing");let i=new oi(e.schema,e.plugins),s=new Be(i);return i.fields.forEach(o=>{if(o.name=="doc")s.doc=bt.fromJSON(e.schema,t.doc);else if(o.name=="selection")s.selection=O.fromJSON(s.doc,t.selection);else if(o.name=="storedMarks")t.storedMarks&&(s.storedMarks=t.storedMarks.map(e.schema.markFromJSON));else{if(r)for(let l in r){let a=r[l],c=a.spec.state;if(a.key==o.name&&c&&c.fromJSON&&Object.prototype.hasOwnProperty.call(t,l)){s[o.name]=c.fromJSON.call(a,e,t[l],s);return}}s[o.name]=o.init(e,s)}}),s}}function ra(n,e,t){for(let r in n){let i=n[r];i instanceof Function?i=i.bind(e):r=="handleDOMEvents"&&(i=ra(i,e,{})),t[r]=i}return t}class ${constructor(e){this.spec=e,this.props={},e.props&&ra(e.props,this,this.props),this.key=e.key?e.key.key:ia("plugin")}getState(e){return e[this.key]}}const li=Object.create(null);function ia(n){return n in li?n+"$"+ ++li[n]:(li[n]=0,n+"$")}class _{constructor(e="key"){this.key=ia(e)}get(e){return e.config.pluginsByKey[this.key]}getState(e){return e[this.key]}}const sa=(n,e)=>n.selection.empty?!1:(e&&e(n.tr.deleteSelection().scrollIntoView()),!0);function oa(n,e){let{$cursor:t}=n.selection;return!t||(e?!e.endOfTextblock("backward",n):t.parentOffset>0)?null:t}const la=(n,e,t)=>{let r=oa(n,t);if(!r)return!1;let i=us(r);if(!i){let o=r.blockRange(),l=o&&Ut(o);return l==null?!1:(e&&e(n.tr.lift(o,l).scrollIntoView()),!0)}let s=i.nodeBefore;if(ga(n,i,e,-1))return!0;if(r.parent.content.size==0&&(Vt(s,"end")||E.isSelectable(s)))for(let o=r.depth;;o--){let l=Hr(n.doc,r.before(o),r.after(o),w.empty);if(l&&l.slice.size1)break}return s.isAtom&&i.depth==r.depth-1?(e&&e(n.tr.delete(i.pos-s.nodeSize,i.pos).scrollIntoView()),!0):!1},fd=(n,e,t)=>{let r=oa(n,t);if(!r)return!1;let i=us(r);return i?aa(n,i,e):!1},hd=(n,e,t)=>{let r=ua(n,t);if(!r)return!1;let i=ds(r);return i?aa(n,i,e):!1};function aa(n,e,t){let r=e.nodeBefore,i=r,s=e.pos-1;for(;!i.isTextblock;s--){if(i.type.spec.isolating)return!1;let u=i.lastChild;if(!u)return!1;i=u}let o=e.nodeAfter,l=o,a=e.pos+1;for(;!l.isTextblock;a++){if(l.type.spec.isolating)return!1;let u=l.firstChild;if(!u)return!1;l=u}let c=Hr(n.doc,s,a,w.empty);if(!c||c.from!=s||c instanceof H&&c.slice.size>=a-s)return!1;if(t){let u=n.tr.step(c);u.setSelection(T.create(u.doc,s)),t(u.scrollIntoView())}return!0}function Vt(n,e,t=!1){for(let r=n;r;r=e=="start"?r.firstChild:r.lastChild){if(r.isTextblock)return!0;if(t&&r.childCount!=1)return!1}return!1}const ca=(n,e,t)=>{let{$head:r,empty:i}=n.selection,s=r;if(!i)return!1;if(r.parent.isTextblock){if(t?!t.endOfTextblock("backward",n):r.parentOffset>0)return!1;s=us(r)}let o=s&&s.nodeBefore;return!o||!E.isSelectable(o)?!1:(e&&e(n.tr.setSelection(E.create(n.doc,s.pos-o.nodeSize)).scrollIntoView()),!0)};function us(n){if(!n.parent.type.spec.isolating)for(let e=n.depth-1;e>=0;e--){if(n.index(e)>0)return n.doc.resolve(n.before(e+1));if(n.node(e).type.spec.isolating)break}return null}function ua(n,e){let{$cursor:t}=n.selection;return!t||(e?!e.endOfTextblock("forward",n):t.parentOffset{let r=ua(n,t);if(!r)return!1;let i=ds(r);if(!i)return!1;let s=i.nodeAfter;if(ga(n,i,e,1))return!0;if(r.parent.content.size==0&&(Vt(s,"start")||E.isSelectable(s))){let o=Hr(n.doc,r.before(),r.after(),w.empty);if(o&&o.slice.size{let{$head:r,empty:i}=n.selection,s=r;if(!i)return!1;if(r.parent.isTextblock){if(t?!t.endOfTextblock("forward",n):r.parentOffset=0;e--){let t=n.node(e);if(n.index(e)+1{let t=n.selection,r=t instanceof E,i;if(r){if(t.node.isTextblock||!ot(n.doc,t.from))return!1;i=t.from}else if(i=Vr(n.doc,t.from,-1),i==null)return!1;if(e){let s=n.tr.join(i);r&&s.setSelection(E.create(s.doc,i-n.doc.resolve(i).nodeBefore.nodeSize)),e(s.scrollIntoView())}return!0},md=(n,e)=>{let t=n.selection,r;if(t instanceof E){if(t.node.isTextblock||!ot(n.doc,t.to))return!1;r=t.to}else if(r=Vr(n.doc,t.to,1),r==null)return!1;return e&&e(n.tr.join(r).scrollIntoView()),!0},gd=(n,e)=>{let{$from:t,$to:r}=n.selection,i=t.blockRange(r),s=i&&Ut(i);return s==null?!1:(e&&e(n.tr.lift(i,s).scrollIntoView()),!0)},ha=(n,e)=>{let{$head:t,$anchor:r}=n.selection;return!t.parent.type.spec.code||!t.sameParent(r)?!1:(e&&e(n.tr.insertText(` -`).scrollIntoView()),!0)};function fs(n){for(let e=0;e{let{$head:t,$anchor:r}=n.selection;if(!t.parent.type.spec.code||!t.sameParent(r))return!1;let i=t.node(-1),s=t.indexAfter(-1),o=fs(i.contentMatchAt(s));if(!o||!i.canReplaceWith(s,s,o))return!1;if(e){let l=t.after(),a=n.tr.replaceWith(l,l,o.createAndFill());a.setSelection(O.near(a.doc.resolve(l),1)),e(a.scrollIntoView())}return!0},pa=(n,e)=>{let t=n.selection,{$from:r,$to:i}=t;if(t instanceof fe||r.parent.inlineContent||i.parent.inlineContent)return!1;let s=fs(i.parent.contentMatchAt(i.indexAfter()));if(!s||!s.isTextblock)return!1;if(e){let o=(!r.parentOffset&&i.index(){let{$cursor:t}=n.selection;if(!t||t.parent.content.size)return!1;if(t.depth>1&&t.after()!=t.end(-1)){let s=t.before();if(Fe(n.doc,s))return e&&e(n.tr.split(s).scrollIntoView()),!0}let r=t.blockRange(),i=r&&Ut(r);return i==null?!1:(e&&e(n.tr.lift(r,i).scrollIntoView()),!0)};function bd(n){return(e,t)=>{if(e.selection instanceof E&&e.selection.node.isBlock){let{$from:h}=e.selection;return!h.parentOffset||!Fe(e.doc,h.pos)?!1:(t&&t(e.tr.split(h.pos).scrollIntoView()),!0)}if(!e.selection.$from.depth)return!1;let r=e.tr;!e.selection.empty&&(e.selection instanceof T||e.selection instanceof fe)&&r.deleteSelection();let{$from:i}=r.selection,s=r.steps.length,o=[],l,a,c=!1,u=!1;for(let h=i.depth;;h--)if(i.node(h).isBlock){c=i.end(h)==i.pos+(i.depth-h),u=i.start(h)==i.pos-(i.depth-h),a=fs(i.node(h-1).contentMatchAt(i.indexAfter(h-1))),o.unshift(c&&a?{type:a}:null),l=h;break}else{if(h==1)return!1;o.unshift(null)}let d=i.pos,f=Fe(r.doc,d,o.length,o);if(f||(o[0]=a?{type:a}:null,f=Fe(r.doc,d,o.length,o)),!f)return!1;if(r.split(d,o.length,o),!c&&u&&i.node(l).type!=a){let h=r.mapping.slice(s),p=h.map(i.before(l)),m=r.doc.resolve(p);a&&i.node(l-1).canReplaceWith(m.index(),m.index()+1,a)&&r.setNodeMarkup(h.map(i.before(l)),a)}return t&&t(r.scrollIntoView()),!0}}const kd=bd(),Sd=(n,e)=>{let{$from:t,to:r}=n.selection,i,s=t.sharedDepth(r);return s==0?!1:(i=t.before(s),e&&e(n.tr.setSelection(E.create(n.doc,i))),!0)};function xd(n,e,t){let r=e.nodeBefore,i=e.nodeAfter,s=e.index();return!r||!i||!r.type.compatibleContent(i.type)?!1:!r.content.size&&e.parent.canReplace(s-1,s)?(t&&t(n.tr.delete(e.pos-r.nodeSize,e.pos).scrollIntoView()),!0):!e.parent.canReplace(s,s+1)||!(i.isTextblock||ot(n.doc,e.pos))?!1:(t&&t(n.tr.join(e.pos).scrollIntoView()),!0)}function ga(n,e,t,r){let i=e.nodeBefore,s=e.nodeAfter,o,l,a=i.type.spec.isolating||s.type.spec.isolating;if(!a&&xd(n,e,t))return!0;let c=!a&&e.parent.canReplace(e.index(),e.index()+1);if(c&&(o=(l=i.contentMatchAt(i.childCount)).findWrapping(s.type))&&l.matchType(o[0]||s.type).validEnd){if(t){let h=e.pos+s.nodeSize,p=b.empty;for(let y=o.length-1;y>=0;y--)p=b.from(o[y].create(null,p));p=b.from(i.copy(p));let m=n.tr.step(new G(e.pos-1,h,e.pos,h,new w(p,1,0),o.length,!0)),g=m.doc.resolve(h+2*o.length);g.nodeAfter&&g.nodeAfter.type==i.type&&ot(m.doc,g.pos)&&m.join(g.pos),t(m.scrollIntoView())}return!0}let u=s.type.spec.isolating||r>0&&a?null:O.findFrom(e,1),d=u&&u.$from.blockRange(u.$to),f=d&&Ut(d);if(f!=null&&f>=e.depth)return t&&t(n.tr.lift(d,f).scrollIntoView()),!0;if(c&&Vt(s,"start",!0)&&Vt(i,"end")){let h=i,p=[];for(;p.push(h),!h.isTextblock;)h=h.lastChild;let m=s,g=1;for(;!m.isTextblock;m=m.firstChild)g++;if(h.canReplace(h.childCount,h.childCount,m.content)){if(t){let y=b.empty;for(let x=p.length-1;x>=0;x--)y=b.from(p[x].copy(y));let S=n.tr.step(new G(e.pos-p.length,e.pos+s.nodeSize,e.pos+g,e.pos+s.nodeSize-g,new w(y,p.length,0),0,!0));t(S.scrollIntoView())}return!0}}return!1}function ya(n){return function(e,t){let r=e.selection,i=n<0?r.$from:r.$to,s=i.depth;for(;i.node(s).isInline;){if(!s)return!1;s--}return i.node(s).isTextblock?(t&&t(e.tr.setSelection(T.create(e.doc,n<0?i.start(s):i.end(s)))),!0):!1}}const wd=ya(-1),Cd=ya(1);function Md(n,e=null){return function(t,r){let{$from:i,$to:s}=t.selection,o=i.blockRange(s),l=o&&as(o,n,e);return l?(r&&r(t.tr.wrap(o,l).scrollIntoView()),!0):!1}}function co(n,e=null){return function(t,r){let i=!1;for(let s=0;s{if(i)return!1;if(!(!a.isTextblock||a.hasMarkup(n,e)))if(a.type==n)i=!0;else{let u=t.doc.resolve(c),d=u.index();i=u.parent.canReplaceWith(d,d+1,n)}})}if(!i)return!1;if(r){let s=t.tr;for(let o=0;o=2&&e.$from.node(e.depth-1).type.compatibleContent(t)&&e.startIndex==0){if(e.$from.index(e.depth-1)==0)return!1;let a=o.resolve(e.start-2);s=new Zn(a,a,e.depth),e.endIndex=0;u--)s=b.from(t[u].type.create(t[u].attrs,s));n.step(new G(e.start-(r?2:0),e.end,e.start,e.end,new w(s,0,0),t.length,!0));let o=0;for(let u=0;uo.childCount>0&&o.firstChild.type==n);return s?t?r.node(s.depth-1).type==n?Od(e,t,n,s):Nd(e,t,s):!0:!1}}function Od(n,e,t,r){let i=n.tr,s=r.end,o=r.$to.end(r.depth);sm;p--)h-=i.child(p).nodeSize,r.delete(h-1,h+1);let s=r.doc.resolve(t.start),o=s.nodeAfter;if(r.mapping.map(t.end)!=t.start+s.nodeAfter.nodeSize)return!1;let l=t.startIndex==0,a=t.endIndex==i.childCount,c=s.node(-1),u=s.index(-1);if(!c.canReplace(u+(l?0:1),u+1,o.content.append(a?b.empty:b.from(i))))return!1;let d=s.pos,f=d+o.nodeSize;return r.step(new G(d-(l?1:0),f+(a?1:0),d+1,f-1,new w((l?b.empty:b.from(i.copy(b.empty))).append(a?b.empty:b.from(i.copy(b.empty))),l?0:1,a?0:1),l?0:1)),e(r.scrollIntoView()),!0}function Dd(n){return function(e,t){let{$from:r,$to:i}=e.selection,s=r.blockRange(i,c=>c.childCount>0&&c.firstChild.type==n);if(!s)return!1;let o=s.startIndex;if(o==0)return!1;let l=s.parent,a=l.child(o-1);if(a.type!=n)return!1;if(t){let c=a.lastChild&&a.lastChild.type==l.type,u=b.from(c?n.create():null),d=new w(b.from(n.create(null,b.from(l.type.create(null,u)))),c?3:1,0),f=s.start,h=s.end;t(e.tr.step(new G(f-(c?3:1),h,f,h,d,1,!0)).scrollIntoView())}return!0}}const Z=function(n){for(var e=0;;e++)if(n=n.previousSibling,!n)return e},Ht=function(n){let e=n.assignedSlot||n.parentNode;return e&&e.nodeType==11?e.host:e};let Ri=null;const Pe=function(n,e,t){let r=Ri||(Ri=document.createRange());return r.setEnd(n,t??n.nodeValue.length),r.setStart(n,e||0),r},Id=function(){Ri=null},Ct=function(n,e,t,r){return t&&(uo(n,e,t,r,-1)||uo(n,e,t,r,1))},Rd=/^(img|br|input|textarea|hr)$/i;function uo(n,e,t,r,i){for(var s;;){if(n==t&&e==r)return!0;if(e==(i<0?0:re(n))){let o=n.parentNode;if(!o||!v(o)||Tn(n)||Rd.test(n.nodeName)||n.contentEditable=="false")return!1;e=Z(n)+(i<0?0:1),n=o}else if(v(n)){let o=n.childNodes[e+(i<0?-1:0)];if(v(o)&&o.contentEditable=="false")if(!((s=o.pmViewDesc)===null||s===void 0)&&s.ignoreForSelection)e+=i;else return!1;else n=o,e=i<0?re(n):0}else return!1}}function re(n){return n.nodeType==3?n.nodeValue.length:n.childNodes.length}function v(n){return n.nodeType==1}function U(n){return n.nodeType==3}function Mt(n,e){return e?n.contains(v(e)?e:e.parentNode):!1}function Ld(n,e){for(;;){if(U(n)&&e)return n;if(v(n)&&e>0){if(n.contentEditable=="false")return null;n=n.childNodes[e-1],e=re(n)}else if(n.parentNode&&!Tn(n))e=Z(n),n=n.parentNode;else return null}}function Pd(n,e){for(;;){if(U(n)&&e2),be=jt||(Ae?/Mac/.test(Ae.platform):!1),Sa=Ae?/Win/.test(Ae.platform):!1,ze=/Android \d/.test(lt),Kr=!!fo&&"webkitFontSmoothing"in fo.documentElement.style,Fd=Kr?+(/\bAppleWebKit\/(\d+)/.exec(navigator.userAgent)||[0,0])[1]:0;function Vd(n){let e=n.defaultView&&n.defaultView.visualViewport;return e?{left:0,right:e.width,top:0,bottom:e.height}:{left:0,right:n.documentElement.clientWidth,top:0,bottom:n.documentElement.clientHeight}}function Ne(n,e){return typeof n=="number"?n:n[e]}function Hd(n){let e=n.getBoundingClientRect(),t=e.width/n.offsetWidth||1,r=e.height/n.offsetHeight||1;return{left:e.left,right:e.left+n.clientWidth*t,top:e.top,bottom:e.top+n.clientHeight*r}}function ho(n,e,t){if(!zi(e)&&e.left==0)return;let r=n.someProp("scrollThreshold")||0,i=n.someProp("scrollMargin")||5,s=n.dom.ownerDocument;for(let o=t||n.dom;o;){if(!v(o)){o=Ht(o);continue}let l=o==s.body,a=l?Vd(s):Hd(o),c=0,u=0;if(e.topa.bottom-Ne(r,"bottom")&&(u=e.bottom-e.top>a.bottom-a.top?e.top+Ne(i,"top")-a.top:e.bottom-a.bottom+Ne(i,"bottom")),e.lefta.right-Ne(r,"right")&&(c=e.right-a.right+Ne(i,"right")),c||u)if(l)s.defaultView.scrollBy(c,u);else{let f=o.scrollLeft,h=o.scrollTop;u&&(o.scrollTop+=u),c&&(o.scrollLeft+=c);let p=o.scrollLeft-f,m=o.scrollTop-h;e={left:e.left-p,top:e.top-m,right:e.right-p,bottom:e.bottom-m}}let d=l?"fixed":getComputedStyle(o).position;if(/^(fixed|sticky)$/.test(d))break;o=d=="absolute"?o.offsetParent:Ht(o)}}function jd(n){let e=n.dom.getBoundingClientRect(),t=Math.max(0,e.top),r,i;for(let s=(e.left+e.right)/2,o=t+1;o=t-20){r=l,i=a.top;break}}return{refDOM:r,refTop:i,stack:xa(n.dom)}}function xa(n){let e=[],t=n.ownerDocument;for(let r=n;r&&(e.push({dom:r,top:r.scrollTop,left:r.scrollLeft}),n!=t);r=Ht(r));return e}function Wd({refDOM:n,refTop:e,stack:t}){let r=n?n.getBoundingClientRect().top:0;wa(t,r==0?0:r-e)}function wa(n,e){for(let t=0;t=l){o=Math.max(p.bottom,o),l=Math.min(p.top,l);let m=p.left>e.left?p.left-e.left:p.right=(p.left+p.right)/2?1:0));continue}}else p.top>e.top&&!a&&p.left<=e.left&&p.right>=e.left&&(a=u,c={left:Math.max(p.left,Math.min(p.right,e.left)),top:p.top});!t&&(e.left>=p.right&&e.top>=p.top||e.left>=p.left&&e.top>=p.bottom)&&(s=d+1)}}return!t&&a&&(t=a,i=c,r=0),t&&U(t)?_d(t,i):!t||r?{node:n,offset:s}:Ca(t,i)}function _d(n,e){let t=n.nodeValue.length,r=document.createRange(),i;for(let s=0;s=(o.left+o.right)/2?1:0)};break}}return r.detach(),i||{node:n,offset:0}}function ps(n,e){return n.left>=e.left-1&&n.left<=e.right+1&&n.top>=e.top-1&&n.top<=e.bottom+1}function Ud(n,e){let t=n.parentNode;return t&&/^li$/i.test(t.nodeName)&&e.left(o.left+o.right)/2?1:-1}return n.docView.posFromDOM(r,i,s)}function Jd(n,e,t,r){let i=-1;for(let s=e,o=!1;s!=n.dom;){let l=n.docView.nearestDesc(s,!0),a;if(!l)return null;if(v(l.dom)&&(l.node.isBlock&&l.parent||!l.contentDOM)&&((a=l.dom.getBoundingClientRect()).width||a.height)&&(l.node.isBlock&&l.parent&&!/^T(R|BODY|HEAD|FOOT)$/.test(l.dom.nodeName)&&(!o&&a.left>r.left||a.top>r.top?i=l.posBefore:(!o&&a.right-1?i:n.docView.posFromDOM(e,t,-1)}function Ma(n,e,t){let r=n.childNodes.length;if(r&&t.tope.top&&i++}let c;Kr&&i&&v(r)&&v(c=r.childNodes[i-1])&&c.contentEditable=="false"&&c.getBoundingClientRect().top>=e.top&&i--,r==n.dom&&i==r.childNodes.length-1&&v(r.lastChild)&&e.top>r.lastChild.getBoundingClientRect().bottom?l=n.state.doc.content.size:(i==0||!v(r)||r.childNodes[i-1].nodeName!="BR")&&(l=Jd(n,r,i,e))}l==null&&(l=qd(n,o,e));let a=n.docView.nearestDesc(o,!0);return{pos:l,inside:a?a.posAtStart-a.border:-1}}function zi(n){return n.top=0&&i==r.nodeValue.length?(a--,u=1):t<0?a--:c++,qt(Ke(Pe(r,a,c),u),u<0)}if(!n.state.doc.resolve(e-(s||0)).parent.inlineContent){if(s==null&&i&&(t<0||i==re(r))){let a=r.childNodes[i-1];if(v(a))return ai(a.getBoundingClientRect(),!1)}if(s==null&&i=0)}if(s==null&&i&&(t<0||i==re(r))){let a=r.childNodes[i-1],c=U(a)?Pe(a,re(a)-(o?0:1)):v(a)&&(a.nodeName!="BR"||!a.nextSibling)?a:null;if(c)return qt(Ke(c,1),!1)}if(s==null&&i=0)}function qt(n,e){if(n.width==0)return n;let t=e?n.left:n.right;return{top:n.top,bottom:n.bottom,left:t,right:t}}function ai(n,e){if(n.height==0)return n;let t=e?n.top:n.bottom;return{top:t,bottom:t,left:n.left,right:n.right}}function Ea(n,e,t){let r=n.state,i=n.root.activeElement;r!=e&&n.updateState(e),i!=n.dom&&n.focus();try{return t()}finally{r!=e&&n.updateState(r),i!=n.dom&&i&&i.focus()}}function Xd(n,e,t){let r=e.selection,i=t=="up"?r.$from:r.$to;return Ea(n,e,()=>{let{node:s}=n.docView.domFromPos(i.pos,t=="up"?-1:1);for(;;){let l=n.docView.nearestDesc(s,!0);if(!l)break;if(l.node.isBlock){s=l.contentDOM||l.dom;break}s=l.dom.parentNode}let o=va(n,i.pos,1);for(let l=s.firstChild;l;l=l.nextSibling){let a;if(v(l))a=l.getClientRects();else if(U(l))a=Pe(l,0,l.nodeValue.length).getClientRects();else continue;for(let c=0;cu.top+1&&(t=="up"?o.top-u.top>(u.bottom-o.top)*2:u.bottom-o.bottom>(o.bottom-u.top)*2))return!1}}return!0})}const Qd=/[\u0590-\u08ac]/;function Zd(n,e,t){let{$head:r}=e.selection;if(!r.parent.isTextblock)return!1;let i=r.parentOffset,s=!i,o=i==r.parent.content.size,l=n.domSelection();return l?!Qd.test(r.parent.textContent)||!l.modify?t=="left"||t=="backward"?s:o:Ea(n,e,()=>{let{focusNode:a,focusOffset:c,anchorNode:u,anchorOffset:d}=n.domSelectionRange(),f=l.caretBidiLevel;l.modify("move",t,"character");let h=r.depth?n.docView.domAfterPos(r.before()):n.dom,{focusNode:p,focusOffset:m}=n.domSelectionRange(),g=p&&!Mt(h,p)||a==p&&c==m;try{l.collapse(u,d),a&&(a!=u||c!=d)&&l.extend&&l.extend(a,c)}catch{}return f!=null&&(l.caretBidiLevel=f),g}):r.pos==r.start()||r.pos==r.end()}let po=null,mo=null,go=!1;function ef(n,e,t){return po==e&&mo==t?go:(po=e,mo=t,go=t=="up"||t=="down"?Xd(n,e,t):Zd(n,e,t))}const ke=0,yo=1,dt=2,Me=3;class An{constructor(e,t,r,i){this.parent=e,this.children=t,this.dom=r,this.contentDOM=i,this.dirty=ke,r.pmViewDesc=this}matchesWidget(e){return!1}matchesMark(e){return!1}matchesNode(e,t,r){return!1}matchesHack(e){return!1}parseRule(e){return null}stopEvent(e){return!1}get size(){let e=0;for(let t=0;tZ(this.contentDOM);else if(this.contentDOM&&this.contentDOM!=this.dom&&this.dom.contains(this.contentDOM))i=!!(e.compareDocumentPosition(this.contentDOM)&4);else if(this.dom.firstChild){if(t==0)for(let s=e;;s=s.parentNode){if(s==this.dom){i=!1;break}if(s.previousSibling)break}if(i==null&&t==e.childNodes.length)for(let s=e;;s=s.parentNode){if(s==this.dom){i=!0;break}if(s.nextSibling)break}}return i??r>0?this.posAtEnd:this.posAtStart}nearestDesc(e,t=!1){for(let r=!0,i=e;i;i=i.parentNode){let s=this.getDesc(i),o;if(s&&(!t||s.node))if(r&&(o=s.nodeDOM)&&!(v(o)?Mt(o,e):o==e))r=!1;else return s}}getDesc(e){let t=e.pmViewDesc;for(let r=t;r;r=r.parent)if(r==this)return t}posFromDOM(e,t,r){for(let i=e;i;i=i.parentNode){let s=this.getDesc(i);if(s)return s.localPosFromDOM(e,t,r)}return-1}descAt(e){for(let t=0,r=0;te){i=e-s;break}s=l}if(i)return this.children[r].domFromPos(i-this.children[r].border,t);for(;r>0;r--){let s=this.children[r-1];if(s.size||!(s instanceof Aa||s instanceof Ta&&s.side>=0))break}if(t<=0){let s,o=!0;for(;s=r?this.children[r-1]:null,!(!s||s.dom.parentNode==this.contentDOM);r--,o=!1);return s&&t&&o&&!s.border&&!s.domAtom?s.domFromPos(s.size,t):{node:this.contentDOM,offset:s?Z(s.dom)+1:0}}else{let s,o=!0;for(;s=r=u&&t<=c-a.border&&a.node&&a.contentDOM&&this.contentDOM.contains(a.contentDOM))return a.parseRange(e,t,u);e=o;for(let d=l;d>0;d--){let f=this.children[d-1];if(f.size&&f.dom.parentNode==this.contentDOM&&!f.emptyChildAt(1)){i=Z(f.dom)+1;break}e-=f.size}i==-1&&(i=0)}if(i>-1&&(c>t||l==this.children.length-1)){t=c;for(let u=l+1;up&&ot){let p=l;l=a,a=p}let h=document.createRange();h.setEnd(a.node,a.offset),h.setStart(l.node,l.offset),c.removeAllRanges(),c.addRange(h)}}ignoreMutation(e){return!this.contentDOM&&e.type!="selection"}get contentLost(){return this.contentDOM&&this.contentDOM!=this.dom&&!this.dom.contains(this.contentDOM)}markDirty(e,t){for(let r=0,i=0;i=r:er){let l=r+s.border,a=o-s.border;if(e>=l&&t<=a){this.dirty=e==r||t==o?dt:yo,e==l&&t==a&&(s.contentLost||s.dom.parentNode!=this.contentDOM)?s.dirty=Me:s.markDirty(e-l,t-l);return}else s.dirty=s.dom==s.contentDOM&&s.dom.parentNode==this.contentDOM&&!s.children.length?dt:Me}r=o}this.dirty=dt}markParentsDirty(){let e=1;for(let t=this.parent;t;t=t.parent,e++){let r=e==1?dt:yo;t.dirty{if(!s)return i;if(s.parent)return s.parent.posBeforeChild(s)})),!t.type.spec.raw){let l=v(o)?o:document.createElement("span");l!=o&&l.appendChild(o),l.hasAttribute("contenteditable")||(l.contentEditable="false"),l.classList.add("ProseMirror-widget")}super(e,[],o,null),this.widget=t,this.widget=t,s=this}matchesWidget(e){return this.dirty==ke&&e.type.eq(this.widget.type)}parseRule(){return{ignore:!0}}stopEvent(e){let t=this.widget.spec.stopEvent;return t?t(e):!1}ignoreMutation(e){return e.type!="selection"||this.widget.spec.ignoreSelection}destroy(){this.widget.type.destroy(this.dom),super.destroy()}get domAtom(){return!0}get ignoreForSelection(){return!!this.widget.type.spec.relaxedSide}get side(){return this.widget.type.side}}class tf extends An{constructor(e,t,r,i){super(e,[],t,null),this.textDOM=r,this.text=i}get size(){return this.text.length}localPosFromDOM(e,t){return e!=this.textDOM?this.posAtStart+(t?this.size:0):this.posAtStart+t}domFromPos(e){return{node:this.textDOM,offset:e}}ignoreMutation(e){return e.type==="characterData"&&e.target.nodeValue==e.oldValue}}class Ze extends An{constructor(e,t,r,i,s){super(e,[],r,i),this.mark=t,this.spec=s}static create(e,t,r,i){let s=i.nodeViews[t.type.name],o=s&&s(t,i,r);return(!o||!o.dom)&&(o=st.renderSpec(document,t.type.spec.toDOM(t,r),null,t.attrs)),new Ze(e,t,o.dom,o.contentDOM||o.dom,o)}parseRule(){return this.dirty&Me||this.mark.type.spec.reparseInView?null:{mark:this.mark.type.name,attrs:this.mark.attrs,contentElement:this.contentDOM}}matchesMark(e){return this.dirty!=Me&&this.mark.eq(e)}markDirty(e,t){if(super.markDirty(e,t),this.dirty!=ke){let r=this.parent;for(;!r.node;)r=r.parent;r.dirty0&&(s=Fi(s,0,e,r));for(let l=0;l{if(!a)return o;if(a.parent)return a.parent.posBeforeChild(a)},r,i),u=c&&c.dom,d=c&&c.contentDOM;if(t.isText){if(!u)u=document.createTextNode(t.text);else if(!U(u))throw new RangeError("Text must be rendered as a DOM text node")}else u||({dom:u,contentDOM:d}=st.renderSpec(document,t.type.spec.toDOM(t),null,t.attrs));!d&&!t.isText&&u.nodeName!="BR"&&(u.hasAttribute("contenteditable")||(u.contentEditable="false"),t.type.spec.draggable&&(u.draggable=!0));let f=u;return u=Da(u,r,t),c?a=new nf(e,t,r,i,u,d||null,f,c):t.isText?new _r(e,t,r,i,u,f):new et(e,t,r,i,u,d||null,f)}parseRule(e){if(this.node.type.spec.reparseInView)return null;let t={node:this.node.type.name,attrs:this.node.attrs};if(this.node.type.whitespace=="pre"&&(t.preserveWhitespace="full"),!this.contentDOM)t.getContent=()=>this.node.content;else if(!this.contentLost)t.contentElement=this.contentDOM;else{for(let r=this.children.length-1;r>=0;r--){let i=this.children[r];if(this.dom.contains(i.dom.parentNode)){t.contentElement=i.dom.parentNode;break}}if(!t.contentElement){let r=e&&e.find(i=>v(i)&&e.indexOf(i.parentNode)<0&&this.dom.contains(i));r?t.contentElement=r:t.getContent=()=>b.empty}}return t}matchesNode(e,t,r){return this.dirty==ke&&e.eq(this.node)&&tr(t,this.outerDeco)&&r.eq(this.innerDeco)}get size(){return this.node.nodeSize}get border(){return this.node.isLeaf?0:1}updateChildren(e,t){let r=this.node.inlineContent,i=t,s=e.composing?this.localCompositionInfo(e,t):null,o=s&&s.pos>-1?s:null,l=s&&s.pos<0,a=new sf(this,o&&o.node,e),c=this.node.inlineContent,u=c&&this.node.isBlock;af(this.node,this.innerDeco,(d,f,h)=>{d.spec.marks?a.syncToMarks(d.spec.marks,r,e,f):d.type.side>=0&&!h&&a.syncToMarks(f==this.node.childCount?B.none:this.node.child(f).marks,r,e,f),a.placeWidget(d,e,i)},(d,f,h,p)=>{a.syncToMarks(d.marks,r,e,p),u&&d.isAtom&&!d.isText&&a.addHackNode("IMG",a.top);let m;a.findNodeMatch(d,f,h,p)||l&&e.state.selection.from>i&&e.state.selection.to-1&&a.updateNodeAt(d,f,h,m,e)||a.updateNextNode(d,f,h,e,p,i)||a.addNode(d,f,h,e,i),i+=d.nodeSize,c&&(u=d.isAtom&&!d.isText)}),a.syncToMarks([],r,e,0),this.node.isTextblock&&a.addTextblockHacks(),a.destroyRest(),(a.changed||this.dirty==dt)&&(o&&this.protectLocalComposition(e,o),Oa(this.contentDOM,this.children,e),jt&&cf(this.dom))}localCompositionInfo(e,t){let{from:r,to:i}=e.state.selection;if(!(e.state.selection instanceof T)||rt+this.node.content.size)return null;let s=e.input.compositionNode;if(!s||!this.dom.contains(s.parentNode))return null;if(this.node.inlineContent){let o=s.nodeValue,l=uf(this.node.content,o,r-t,i-t);return l<0?null:{node:s,pos:l,text:o}}else return{node:s,pos:-1,text:""}}protectLocalComposition(e,{node:t,pos:r,text:i}){if(this.getDesc(t))return;let s=t;for(;s.parentNode!=this.contentDOM;s=s.parentNode){for(;s.previousSibling;)s.parentNode.removeChild(s.previousSibling);for(;s.nextSibling;)s.parentNode.removeChild(s.nextSibling);s.pmViewDesc&&(s.pmViewDesc=void 0)}let o=new tf(this,s,t,i);e.input.compositionNodes.push(o),this.children=Fi(this.children,r,r+i.length,e,o)}update(e,t,r,i){return this.dirty==Me||!e.sameMarkup(this.node)?!1:(this.updateInner(e,t,r,i),!0)}updateInner(e,t,r,i){this.updateOuterDeco(t),this.node=e,this.innerDeco=r,this.contentDOM&&this.updateChildren(i,this.posAtStart),this.dirty=ke}updateOuterDeco(e){if(tr(e,this.outerDeco))return;let t=!v(this.nodeDOM),r=this.dom;this.dom=Na(this.dom,this.nodeDOM,$i(this.outerDeco,this.node,t),$i(e,this.node,t)),this.dom!=r&&(r.pmViewDesc=void 0,this.dom.pmViewDesc=this),this.outerDeco=e}selectNode(){v(this.nodeDOM)&&(this.nodeDOM.classList.add("ProseMirror-selectednode"),(this.contentDOM||!this.node.type.spec.draggable)&&(this.nodeDOM.draggable=!0))}deselectNode(){v(this.nodeDOM)&&(this.nodeDOM.classList.remove("ProseMirror-selectednode"),(this.contentDOM||!this.node.type.spec.draggable)&&this.nodeDOM.removeAttribute("draggable"))}get domAtom(){return this.node.isAtom}}function bo(n,e,t,r,i){Da(r,e,n);let s=new et(void 0,n,e,t,r,r,r);return s.contentDOM&&s.updateChildren(i,0),s}class _r extends et{constructor(e,t,r,i,s,o){super(e,t,r,i,s,null,o)}parseRule(){let e=this.nodeDOM.parentNode;for(;e&&e!=this.dom&&!e.pmIsDeco;)e=e.parentNode;return{skip:e||!0}}update(e,t,r,i){return this.dirty==Me||this.dirty!=ke&&!this.inParent()||!e.sameMarkup(this.node)?!1:(this.updateOuterDeco(t),(this.dirty!=ke||e.text!=this.node.text)&&e.text!=this.nodeDOM.nodeValue&&(this.nodeDOM.nodeValue=e.text,i.trackWrites==this.nodeDOM&&(i.trackWrites=null)),this.node=e,this.dirty=ke,!0)}inParent(){let e=this.parent.contentDOM;for(let t=this.nodeDOM;t;t=t.parentNode)if(t==e)return!0;return!1}domFromPos(e){return{node:this.nodeDOM,offset:e}}localPosFromDOM(e,t,r){return e==this.nodeDOM?this.posAtStart+Math.min(t,this.node.text.length):super.localPosFromDOM(e,t,r)}ignoreMutation(e){return e.type!="characterData"&&e.type!="selection"}slice(e,t,r){let i=this.node.cut(e,t),s=document.createTextNode(i.text);return new _r(this.parent,i,this.outerDeco,this.innerDeco,s,s)}markDirty(e,t){super.markDirty(e,t),this.dom!=this.nodeDOM&&(e==0||t==this.nodeDOM.nodeValue.length)&&(this.dirty=Me)}get domAtom(){return!1}isText(e){return this.node.text==e}}class Aa extends An{parseRule(){return{ignore:!0}}matchesHack(e){return this.dirty==ke&&this.dom.nodeName==e}get domAtom(){return!0}get ignoreForCoords(){return this.dom.nodeName=="IMG"}}class nf extends et{constructor(e,t,r,i,s,o,l,a){super(e,t,r,i,s,o,l),this.spec=a}update(e,t,r,i){if(this.dirty==Me)return!1;if(this.spec.update&&(this.node.type==e.type||this.spec.multiType)){let s=this.spec.update(e,t,r);return s&&this.updateInner(e,t,r,i),s}else return!this.contentDOM&&!e.isLeaf?!1:super.update(e,t,r,i)}selectNode(){this.spec.selectNode?this.spec.selectNode():super.selectNode()}deselectNode(){this.spec.deselectNode?this.spec.deselectNode():super.deselectNode()}setSelection(e,t,r,i){this.spec.setSelection?this.spec.setSelection(e,t,r.root):super.setSelection(e,t,r,i)}destroy(){this.spec.destroy&&this.spec.destroy(),super.destroy()}stopEvent(e){return this.spec.stopEvent?this.spec.stopEvent(e):!1}ignoreMutation(e){return this.spec.ignoreMutation?this.spec.ignoreMutation(e):super.ignoreMutation(e)}}function Oa(n,e,t){let r=n.firstChild,i=!1;for(let s=0;s>1,l=Math.min(o,e.length);for(;s-1)a>this.index&&(this.changed=!0,this.destroyBetween(this.index,a)),this.top=this.top.children[this.index];else{let u=Ze.create(this.top,e[o],t,r);this.top.children.splice(this.index,0,u),this.top=u,this.changed=!0}this.index=0,o++}}findNodeMatch(e,t,r,i){let s=-1,o;if(i>=this.preMatch.index&&(o=this.preMatch.matches[i-this.preMatch.index]).parent==this.top&&o.matchesNode(e,t,r))s=this.top.children.indexOf(o,this.index);else for(let l=this.index,a=Math.min(this.top.children.length,l+5);l0;){let l;for(;;)if(r){let c=t.children[r-1];if(c instanceof Ze)t=c,r=c.children.length;else{l=c,r--;break}}else{if(t==e)break e;r=t.parent.children.indexOf(t),t=t.parent}let a=l.node;if(a){if(a!=n.child(i-1))break;--i,s.set(l,i),o.push(l)}}return{index:i,matched:s,matches:o.reverse()}}function lf(n,e){return n.type.side-e.type.side}function af(n,e,t,r){let i=e.locals(n),s=0;if(i.length==0){for(let c=0;cs;)l.push(i[o++]);let p=s+f.nodeSize;if(f.isText){let g=p;o!g.inline):l.slice();r(f,m,e.forChild(s,f),h),s=p}}function cf(n){if(n.nodeName=="UL"||n.nodeName=="OL"){let e=n.style.cssText;n.style.cssText=e+"; list-style: square !important",window.getComputedStyle(n).listStyle,n.style.cssText=e}}function uf(n,e,t,r){for(let i=0,s=0;i=t){if(s>=r&&a.slice(r-e.length-l,r-l)==e)return r-e.length;let c=l=0&&c+e.length+l>=t)return l+c;if(t==r&&a.length>=r+e.length-l&&a.slice(r-l,r-l+e.length)==e)return r}}return-1}function Fi(n,e,t,r,i){let s=[];for(let o=0,l=0;o=t||u<=e?s.push(a):(ct&&s.push(a.slice(t-c,a.size,r)))}return s}function ms(n,e=null){let t=n.domSelectionRange(),r=n.state.doc;if(!t.focusNode)return null;let i=n.docView.nearestDesc(t.focusNode),s=i&&i.size==0,o=n.docView.posFromDOM(t.focusNode,t.focusOffset,1);if(o<0)return null;let l=r.resolve(o),a,c;if(Wr(t)){for(a=o;i&&!i.node;)i=i.parent;if(i&&i.node.isAtom&&E.isSelectable(i.node)&&i.parent&&!(i.node.isInline&&Bd(t.focusNode,t.focusOffset,i.dom))){let d=i.posBefore;c=new E(o==d?l:r.resolve(d))}else if(he&&e=="key"&&o>n.state.selection.to&&v(t.focusNode)&&t.focusOffset==t.focusNode.childNodes.length&&i&&i.posAtStart>n.state.selection.to)for(let d=t.focusNode;;d=d.parentNode){if(getComputedStyle(d).overflow!="visible"){c=O.findFrom(r.resolve(i.posAtStart),1);break}if(d==i.dom||d.nextSibling||!d.parentNode||!v(d.parentNode))break}}else{if(t instanceof n.dom.ownerDocument.defaultView.Selection&&t.rangeCount>1){let d=o,f=o;for(let h=0;h{(t.anchorNode!=r||t.anchorOffset!=i)&&(e.removeEventListener("selectionchange",n.input.hideSelectionGuard),setTimeout(()=>{(!Ia(n)||n.state.selection.visible)&&n.dom.classList.remove("ProseMirror-hideselection")},20))})}function ff(n){let e=n.domSelection();if(!e)return;let t=n.cursorWrapper.dom,r=t.nodeName=="IMG";r?e.collapse(t.parentNode,Z(t)+1):e.collapse(t,0),!r&&!n.state.selection.visible&&ue&&Qe<=11&&(t.disabled=!0,t.disabled=!1)}function Ra(n,e){if(e instanceof E){let t=n.docView.descAt(e.from);t!=n.lastSelectedViewDesc&&(Co(n),t&&t.selectNode(),n.lastSelectedViewDesc=t)}else Co(n)}function Co(n){n.lastSelectedViewDesc&&(n.lastSelectedViewDesc.parent&&n.lastSelectedViewDesc.deselectNode(),n.lastSelectedViewDesc=void 0)}function gs(n,e,t,r){return n.someProp("createSelectionBetween",i=>i(n,e,t))||T.between(e,t,r)}function Mo(n){return n.editable&&!n.hasFocus()?!1:La(n)}function La(n){let e=n.domSelectionRange();if(!e.anchorNode)return!1;try{return Mt(n.dom,e.anchorNode)&&(n.editable||Mt(n.dom,e.focusNode))}catch{return!1}}function hf(n){let e=n.docView.domFromPos(n.state.selection.anchor,0),t=n.domSelectionRange();return Ct(e.node,e.offset,t.anchorNode,t.anchorOffset)}function Vi(n,e){let{$anchor:t,$head:r}=n.selection,i=e>0?t.max(r):t.min(r),s=i.parent.inlineContent?i.depth?n.doc.resolve(e>0?i.after():i.before()):null:i;return s&&O.findFrom(s,e)}function _e(n,e){return n.dispatch(n.state.tr.setSelection(e).scrollIntoView()),!0}function vo(n,e,t){let r=n.state.selection;if(r instanceof T)if(t.indexOf("s")>-1){let{$head:i}=r,s=i.textOffset?null:e<0?i.nodeBefore:i.nodeAfter;if(!s||s.isText||!s.isLeaf)return!1;let o=n.state.doc.resolve(i.pos+s.nodeSize*(e<0?-1:1));return _e(n,new T(r.$anchor,o))}else if(r.empty){if(n.endOfTextblock(e>0?"forward":"backward")){let i=Vi(n.state,e);return i&&i instanceof E?_e(n,i):!1}else if(!(be&&t.indexOf("m")>-1)){let i=r.$head,s=i.textOffset?null:e<0?i.nodeBefore:i.nodeAfter,o;if(!s||s.isText)return!1;let l=e<0?i.pos-s.nodeSize:i.pos;return s.isAtom||(o=n.docView.descAt(l))&&!o.contentDOM?E.isSelectable(s)?_e(n,new E(e<0?n.state.doc.resolve(i.pos-s.nodeSize):i)):_e(n,new T(n.state.doc.resolve(e<0?l:l+s.nodeSize))):!1}}else return!1;else{if(r instanceof E&&r.node.isInline)return _e(n,new T(e>0?r.$to:r.$from));{let i=Vi(n.state,e);return i?_e(n,i):!1}}}function on(n,e){let t=n.pmViewDesc;return t?t.size==0&&(e<0||n.nextSibling||n.nodeName!="BR"):v(n)&&n.contentEditable=="false"}function Ot(n,e){return e<0?pf(n):mf(n)}function pf(n){let e=n.domSelectionRange(),t=e.focusNode,r=e.focusOffset;if(!t)return;let i,s,o=!1;for(he&&v(t)&&r0){if(!v(t))break;let l=t.childNodes[r-1];if(on(l,-1))i=t,s=--r;else if(U(l))t=l,r=t.nodeValue.length;else break}else{if(Pa(t))break;{let l=t.previousSibling;for(;l&&on(l,-1);)i=t.parentNode,s=Z(l),l=l.previousSibling;if(l)t=l,r=re(t);else{if(t=t.parentNode,t==n.dom)break;r=0}}}o?Hi(n,t,r):i&&Hi(n,i,s)}function mf(n){let e=n.domSelectionRange(),t=e.focusNode,r=e.focusOffset;if(!t)return;let i=re(t),s,o;for(;;)if(r{n.state==i&&Ve(n)},50)}function Eo(n,e){let t=n.state.doc.resolve(e);if(!(te||Sa)&&t.parent.inlineContent){let i=n.coordsAtPos(e);if(e>t.start()){let s=n.coordsAtPos(e-1),o=(s.top+s.bottom)/2;if(o>i.top&&o1)return s.lefti.top&&o1)return s.left>i.left?"ltr":"rtl"}}return getComputedStyle(n.dom).direction=="rtl"?"rtl":"ltr"}function To(n,e,t){let r=n.state.selection;if(r instanceof T&&!r.empty||t.indexOf("s")>-1||be&&t.indexOf("m")>-1)return!1;let{$from:i,$to:s}=r;if(!i.parent.inlineContent||n.endOfTextblock(e<0?"up":"down")){let o=Vi(n.state,e);if(o&&o instanceof E)return _e(n,o)}if(!i.parent.inlineContent){let o=e<0?i:s,l=r instanceof fe?O.near(o,e):O.findFrom(o,e);return l?_e(n,l):!1}return!1}function Ao(n,e){if(!(n.state.selection instanceof T))return!0;let{$head:t,$anchor:r,empty:i}=n.state.selection;if(!t.sameParent(r))return!0;if(!i)return!1;if(n.endOfTextblock(e>0?"forward":"backward"))return!0;let s=!t.textOffset&&(e<0?t.nodeBefore:t.nodeAfter);if(s&&!s.isText){let o=n.state.tr;return e<0?o.delete(t.pos-s.nodeSize,t.pos):o.delete(t.pos,t.pos+s.nodeSize),n.dispatch(o),!0}return!1}function Oo(n,e,t){n.domObserver.stop(),e.contentEditable=t,n.domObserver.start()}function bf(n){if(!ie||n.state.selection.$head.parentOffset>0)return!1;let{focusNode:e,focusOffset:t}=n.domSelectionRange();if(e&&v(e)&&t==0&&e.firstChild&&v(e.firstChild)&&e.firstChild.contentEditable=="false"){let r=e.firstChild;Oo(n,r,"true"),setTimeout(()=>Oo(n,r,"false"),20)}return!1}function kf(n){let e="";return n.ctrlKey&&(e+="c"),n.metaKey&&(e+="m"),n.altKey&&(e+="a"),n.shiftKey&&(e+="s"),e}function Sf(n,e){let t=e.keyCode,r=kf(e);if(t==8||be&&t==72&&r=="c")return Ao(n,-1)||Ot(n,-1);if(t==46&&!e.shiftKey||be&&t==68&&r=="c")return Ao(n,1)||Ot(n,1);if(t==13||t==27)return!0;if(t==37||be&&t==66&&r=="c"){let i=t==37?Eo(n,n.state.selection.from)=="ltr"?-1:1:-1;return vo(n,i,r)||Ot(n,i)}else if(t==39||be&&t==70&&r=="c"){let i=t==39?Eo(n,n.state.selection.from)=="ltr"?1:-1:1;return vo(n,i,r)||Ot(n,i)}else{if(t==38||be&&t==80&&r=="c")return To(n,-1,r)||Ot(n,-1);if(t==40||be&&t==78&&r=="c")return bf(n)||To(n,1,r)||Ot(n,1);if(r==(be?"m":"c")&&(t==66||t==73||t==89||t==90))return!0}return!1}function ys(n,e){n.someProp("transformCopied",h=>{e=h(e,n)});let t=[],{content:r,openStart:i,openEnd:s}=e;for(;i>1&&s>1&&r.childCount==1&&r.firstChild.childCount==1;){i--,s--;let h=r.firstChild;t.push(h.type.name,h.attrs!=h.type.defaultAttrs?h.attrs:null),r=h.content}let o=n.someProp("clipboardSerializer")||st.fromSchema(n.state.schema),l=Ha(),a=l.createElement("div");a.appendChild(o.serializeFragment(r,{document:l}));let c=a.firstChild,u,d=0;for(;c&&v(c)&&(u=Va[c.nodeName.toLowerCase()]);){for(let h=u.length-1;h>=0;h--){let p=l.createElement(u[h]);for(;a.firstChild;)p.appendChild(a.firstChild);a.appendChild(p),d++}c=a.firstChild}c&&v(c)&&c.setAttribute("data-pm-slice",`${i} ${s}${d?` -${d}`:""} ${JSON.stringify(t)}`);let f=n.someProp("clipboardTextSerializer",h=>h(e,n))||e.content.textBetween(0,e.content.size,` +var Eo=Object.defineProperty,Xd=(n,e)=>{let t={};for(var r in n)Eo(t,r,{get:n[r],enumerable:!0});return Eo(t,Symbol.toStringTag,{value:"Module"}),t};function ne(n){this.content=n}ne.prototype={constructor:ne,find:function(n){for(var e=0;e>1}};ne.from=function(n){if(n instanceof ne)return n;var e=[];if(n)for(var t in n)e.push(t,n[t]);return new ne(e)};function Oa(n,e,t){for(let r=0;;r++){if(r==n.childCount||r==e.childCount)return n.childCount==e.childCount?null:t;let i=n.child(r),s=e.child(r);if(i==s){t+=i.nodeSize;continue}if(!i.sameMarkup(s))return t;if(i.isText&&i.text!=s.text){let o=i.text,l=s.text,a=0;for(;o[a]==l[a];a++)t++;return a&&a0&&f>0&&c[d-1]==u[f-1];)d--,f--,t--,r--;return d&&f&&d=56320&&n<57344}function Ia(n){return n>=55296&&n<56320}class b{constructor(e,t){if(this.content=e,this.size=t||0,t==null)for(let r=0;re&&r(a,i+l,s||null,o)!==!1&&a.content.size){let u=l+1;a.nodesBetween(Math.max(0,e-u),Math.min(a.content.size,t-u),r,i+u)}l=c}}descendants(e){this.nodesBetween(0,this.size,e)}textBetween(e,t,r,i){let s="",o=!0;return this.nodesBetween(e,t,(l,a)=>{let c=l.isText?l.text.slice(Math.max(e,a)-a,t-a):l.isLeaf?i?typeof i=="function"?i(l):i:l.type.spec.leafText?l.type.spec.leafText(l):"":"";l.isBlock&&(l.isLeaf&&c||l.isTextblock)&&r&&(o?o=!1:s+=r),s+=c},0),s}append(e){if(!e.size)return this;if(!this.size)return e;let t=this.lastChild,r=e.firstChild,i=this.content.slice(),s=0;for(t.isText&&t.sameMarkup(r)&&(i[i.length-1]=t.withText(t.text+r.text),s=1);se)for(let s=0,o=0;oe&&((ot)&&(l.isText?l=l.cut(Math.max(0,e-o),Math.min(l.text.length,t-o)):l=l.cut(Math.max(0,e-o-1),Math.min(l.content.size,t-o-1))),r.push(l),i+=l.nodeSize),o=a}return new b(r,i)}cutByIndex(e,t){return e==t?b.empty:e==0&&t==this.content.length?this:new b(this.content.slice(e,t))}replaceChild(e,t){let r=this.content[e];if(r==t)return this;let i=this.content.slice(),s=this.size+t.nodeSize-r.nodeSize;return i[e]=t,new b(i,s)}addToStart(e){return new b([e].concat(this.content),this.size+e.nodeSize)}addToEnd(e){return new b(this.content.concat(e),this.size+e.nodeSize)}eq(e){if(this.content.length!=e.content.length)return!1;for(let t=0;tthis.size||e<0)throw new RangeError(`Position ${e} outside of fragment (${this})`);for(let t=0,r=0;;t++){let i=this.child(t),s=r+i.nodeSize;if(s>=e)return s==e?Yn(t+1,s):Yn(t,r);r=s}}toString(){return"<"+this.toStringInner()+">"}toStringInner(){return this.content.join(", ")}toJSON(){return this.content.length?this.content.map(e=>e.toJSON()):null}static fromJSON(e,t){if(!t)return b.empty;if(!Array.isArray(t))throw new RangeError("Invalid input for Fragment.fromJSON");return b.fromArray(t.map(e.nodeFromJSON))}static fromArray(e){if(!e.length)return b.empty;let t,r=0;for(let i=0;ithis.type.rank&&(t||(t=e.slice(0,i)),t.push(this),r=!0),t&&t.push(s)}}return t||(t=e.slice()),r||t.push(this),t}removeFromSet(e){for(let t=0;tr.type.rank-i.type.rank),t}};$.none=[];class On extends Error{}class x{constructor(e,t,r){this.content=e,this.openStart=t,this.openEnd=r}get size(){return this.content.size-this.openStart-this.openEnd}insertAt(e,t){let r=Pa(this.content,e+this.openStart,t,this.openStart+1,this.openEnd+1);return r&&new x(r,this.openStart,this.openEnd)}removeBetween(e,t){return new x(La(this.content,e+this.openStart,t+this.openStart),this.openStart,this.openEnd)}eq(e){return this.content.eq(e.content)&&this.openStart==e.openStart&&this.openEnd==e.openEnd}toString(){return this.content+"("+this.openStart+","+this.openEnd+")"}toJSON(){if(!this.content.size)return null;let e={content:this.content.toJSON()};return this.openStart>0&&(e.openStart=this.openStart),this.openEnd>0&&(e.openEnd=this.openEnd),e}static fromJSON(e,t){if(!t)return x.empty;let r=t.openStart||0,i=t.openEnd||0;if(typeof r!="number"||typeof i!="number")throw new RangeError("Invalid input for Slice.fromJSON");return new x(b.fromJSON(e,t.content),r,i)}static maxOpen(e,t=!0){let r=0,i=0;for(let s=e.firstChild;s&&!s.isLeaf&&(t||!s.type.spec.isolating);s=s.firstChild)r++;for(let s=e.lastChild;s&&!s.isLeaf&&(t||!s.type.spec.isolating);s=s.lastChild)i++;return new x(e,r,i)}}x.empty=new x(b.empty,0,0);function La(n,e,t){let{index:r,offset:i}=n.findIndex(e),s=n.maybeChild(r),{index:o,offset:l}=n.findIndex(t);if(i==e||s.isText){if(l!=t&&!n.child(o).isText)throw new RangeError("Removing non-flat range");return n.cut(0,e).append(n.cut(t))}if(r!=o)throw new RangeError("Removing non-flat range");return n.replaceChild(r,s.copy(La(s.content,e-i-1,t-i-1)))}function Pa(n,e,t,r,i,s){let{index:o,offset:l}=n.findIndex(e),a=n.maybeChild(o);if(l==e||a.isText)return s&&r<=0&&i<=0&&!s.canReplace(o,o,t)?null:n.cut(0,e).append(t).append(n.cut(e));let c=Pa(a.content,e-l-1,t,o==0?r-1:0,o==n.childCount-1?i-1:0,a);return c&&n.replaceChild(o,a.copy(c))}function Qd(n,e,t){if(t.openStart>n.depth)throw new On("Inserted content deeper than insertion position");if(n.depth-t.openStart!=e.depth-t.openEnd)throw new On("Inconsistent open depths");return za(n,e,t,0)}function za(n,e,t,r){let i=n.index(r),s=n.node(r);if(i==e.index(r)&&r=0&&n.isText&&n.sameMarkup(e[t])?e[t]=n.withText(e[t].text+n.text):e.push(n)}function yn(n,e,t,r){let i=(e||n).node(t),s=0,o=e?e.index(t):i.childCount;n&&(s=n.index(t),n.depth>t?s++:n.textOffset&&(Tt(n.nodeAfter,r),s++));for(let l=s;li&&rs(n,e,i+1),o=r.depth>i&&rs(t,r,i+1),l=[];return yn(null,n,i,l),s&&o&&e.index(i)==t.index(i)?(Ba(s,o),Tt(Et(s,$a(n,e,t,r,i+1)),l)):(s&&Tt(Et(s,wr(n,e,i+1)),l),yn(e,t,i,l),o&&Tt(Et(o,wr(t,r,i+1)),l)),yn(r,null,i,l),new b(l)}function wr(n,e,t){let r=[];if(yn(null,n,t,r),n.depth>t){let i=rs(n,e,t+1);Tt(Et(i,wr(n,e,t+1)),r)}return yn(e,null,t,r),new b(r)}function Zd(n,e){let t=e.depth-n.openStart,i=e.node(t).copy(n.content);for(let s=t-1;s>=0;s--)i=e.node(s).copy(b.from(i));return{start:i.resolveNoCache(n.openStart+t),end:i.resolveNoCache(i.content.size-n.openEnd-t)}}class Rn{constructor(e,t,r){this.pos=e,this.path=t,this.parentOffset=r,this.depth=t.length/3-1}resolveDepth(e){return e==null?this.depth:e<0?this.depth+e:e}get parent(){return this.node(this.depth)}get doc(){return this.node(0)}node(e){return this.path[this.resolveDepth(e)*3]}index(e){return this.path[this.resolveDepth(e)*3+1]}indexAfter(e){return e=this.resolveDepth(e),this.index(e)+(e==this.depth&&!this.textOffset?0:1)}start(e){return e=this.resolveDepth(e),e==0?0:this.path[e*3-1]+1}end(e){return e=this.resolveDepth(e),this.start(e)+this.node(e).content.size}before(e){if(e=this.resolveDepth(e),!e)throw new RangeError("There is no position before the top-level node");return e==this.depth+1?this.pos:this.path[e*3-1]}after(e){if(e=this.resolveDepth(e),!e)throw new RangeError("There is no position after the top-level node");return e==this.depth+1?this.pos:this.path[e*3-1]+this.path[e*3].nodeSize}get textOffset(){return this.pos-this.path[this.path.length-1]}get nodeAfter(){let e=this.parent,t=this.index(this.depth);if(t==e.childCount)return null;let r=this.pos-this.path[this.path.length-1],i=e.child(t);return r?e.child(t).cut(r):i}get nodeBefore(){let e=this.index(this.depth),t=this.pos-this.path[this.path.length-1];return t?this.parent.child(e).cut(0,t):e==0?null:this.parent.child(e-1)}posAtIndex(e,t){t=this.resolveDepth(t);let r=this.path[t*3],i=t==0?0:this.path[t*3-1]+1;for(let s=0;s0;t--)if(this.start(t)<=e&&this.end(t)>=e)return t;return 0}blockRange(e=this,t){if(e.pos=0;r--)if(e.pos<=this.end(r)&&(!t||t(this.node(r))))return new Sr(this,e,r);return null}sameParent(e){return this.pos-this.parentOffset==e.pos-e.parentOffset}max(e){return e.pos>this.pos?e:this}min(e){return e.pos=0&&t<=e.content.size))throw new RangeError("Position "+t+" out of range");let r=[],i=0,s=t;for(let o=e;;){let{index:l,offset:a}=o.content.findIndex(s),c=s-a;if(r.push(o,l,i+a),!c||(o=o.child(l),o.isText))break;s=c-1,i+=a+1}return new Rn(t,r,s)}static resolveCached(e,t){let r=Ao.get(e);if(r)for(let s=0;se&&this.nodesBetween(e,t,s=>(r.isInSet(s.marks)&&(i=!0),!i)),i}get isBlock(){return this.type.isBlock}get isTextblock(){return this.type.isTextblock}get inlineContent(){return this.type.inlineContent}get isInline(){return this.type.isInline}get isText(){return this.type.isText}get isLeaf(){return this.type.isLeaf}get isAtom(){return this.type.isAtom}toString(){if(this.type.spec.toDebugString)return this.type.spec.toDebugString(this);let e=this.type.name;return this.content.size&&(e+="("+this.content.toStringInner()+")"),Ha(this.marks,e)}contentMatchAt(e){let t=this.type.contentMatch.matchFragment(this.content,0,e);if(!t)throw new Error("Called contentMatchAt on a node with invalid content");return t}canReplace(e,t,r=b.empty,i=0,s=r.childCount){let o=this.contentMatchAt(e).matchFragment(r,i,s),l=o&&o.matchFragment(this.content,t);if(!l||!l.validEnd)return!1;for(let a=i;at.type.name)}`);this.content.forEach(t=>t.check())}toJSON(){let e={type:this.type.name};for(let t in this.attrs){e.attrs=this.attrs;break}return this.content.size&&(e.content=this.content.toJSON()),this.marks.length&&(e.marks=this.marks.map(t=>t.toJSON())),e}static fromJSON(e,t){if(!t)throw new RangeError("Invalid input for Node.fromJSON");let r;if(t.marks){if(!Array.isArray(t.marks))throw new RangeError("Invalid mark data for Node.fromJSON");r=t.marks.map(e.markFromJSON)}if(t.type=="text"){if(typeof t.text!="string")throw new RangeError("Invalid text node in JSON");return e.text(t.text,r)}let i=b.fromJSON(e,t.content);return e.nodeType(t.type).create(t.attrs,i,r)}};At.prototype.text=void 0;class Cr extends At{constructor(e,t,r,i){if(super(e,t,null,i),!r)throw new RangeError("Empty text nodes are not allowed");this.text=r}toString(){return this.type.spec.toDebugString?this.type.spec.toDebugString(this):Ha(this.marks,JSON.stringify(this.text))}get textContent(){return this.text}textBetween(e,t){return this.text.slice(e,t)}get nodeSize(){return this.text.length}mark(e){return e==this.marks?this:new Cr(this.type,this.attrs,this.text,e)}withText(e){return e==this.text?this:new Cr(this.type,this.attrs,e,this.marks)}cut(e=0,t=this.text.length){return e==0&&t==this.text.length?this:this.withText(this.text.slice(e,t))}eq(e){return this.sameMarkup(e)&&this.text==e.text}toJSON(){let e=super.toJSON();return e.text=this.text,e}}function Ha(n,e){for(let t=n.length-1;t>=0;t--)e=n[t].type.name+"("+e+")";return e}function No(n,e,t,r){for(let i in e)if(!(i in n))throw new RangeError(`Unsupported attribute ${i} for ${t} of type ${r}`);for(let i in n)n[i].validate&&n[i].validate(e[i])}class Dt{constructor(e){this.validEnd=e,this.next=[],this.wrapCache=[]}static parse(e,t){let r=new rf(e,t);if(r.next==null)return Dt.empty;let i=Fa(r);r.next&&r.err("Unexpected trailing text");let s=df(uf(i));return ff(s,r),s}matchType(e){for(let t=0;tc.createAndFill()));for(let c=0;c=this.next.length)throw new RangeError(`There's no ${e}th edge in this content match`);return this.next[e]}toString(){let e=[];function t(r){e.push(r);for(let i=0;i{let s=i+(r.validEnd?"*":" ")+" ";for(let o=0;o"+e.indexOf(r.next[o].next);return s}).join(` +`)}}Dt.empty=new Dt(!0);class rf{constructor(e,t){this.string=e,this.nodeTypes=t,this.inline=null,this.pos=0,this.tokens=e.split(/\s*(?=\b|\W|$)/),this.tokens[this.tokens.length-1]==""&&this.tokens.pop(),this.tokens[0]==""&&this.tokens.shift()}get next(){return this.tokens[this.pos]}eat(e){return this.next==e&&(this.pos++||!0)}err(e){throw new SyntaxError(e+" (in content expression '"+this.string+"')")}}function Fa(n){let e=[];do e.push(sf(n));while(n.eat("|"));return e.length==1?e[0]:{type:"choice",exprs:e}}function sf(n){let e=[];do e.push(of(n));while(n.next&&n.next!=")"&&n.next!="|");return e.length==1?e[0]:{type:"seq",exprs:e}}function of(n){let e=cf(n);for(;;)if(n.eat("+"))e={type:"plus",expr:e};else if(n.eat("*"))e={type:"star",expr:e};else if(n.eat("?"))e={type:"opt",expr:e};else if(n.eat("{"))e=lf(n,e);else break;return e}function Oo(n){/\D/.test(n.next)&&n.err("Expected number, got '"+n.next+"'");let e=Number(n.next);return n.pos++,e}function lf(n,e){let t=Oo(n),r=t;return n.eat(",")&&(n.next!="}"?r=Oo(n):r=-1),n.eat("}")||n.err("Unclosed braced range"),{type:"range",min:t,max:r,expr:e}}function af(n,e){let t=n.nodeTypes,r=t[e];if(r)return[r];let i=[];for(let s in t){let o=t[s];o.isInGroup(e)&&i.push(o)}return i.length==0&&n.err("No node type or group '"+e+"' found"),i}function cf(n){if(n.eat("(")){let e=Fa(n);return n.eat(")")||n.err("Missing closing paren"),e}else if(/\W/.test(n.next))n.err("Unexpected token '"+n.next+"'");else{let e=af(n,n.next).map(t=>(n.inline==null?n.inline=t.isInline:n.inline!=t.isInline&&n.err("Mixing inline and block content"),{type:"name",value:t}));return n.pos++,e.length==1?e[0]:{type:"choice",exprs:e}}}function uf(n){let e=[[]];return i(s(n,0),t()),e;function t(){return e.push([])-1}function r(o,l,a){let c={term:a,to:l};return e[o].push(c),c}function i(o,l){o.forEach(a=>a.to=l)}function s(o,l){if(o.type=="choice")return o.exprs.reduce((a,c)=>a.concat(s(c,l)),[]);if(o.type=="seq")for(let a=0;;a++){let c=s(o.exprs[a],l);if(a==o.exprs.length-1)return c;i(c,l=t())}else if(o.type=="star"){let a=t();return r(l,a),i(s(o.expr,a),a),[r(a)]}else if(o.type=="plus"){let a=t();return i(s(o.expr,l),a),i(s(o.expr,a),a),[r(a)]}else{if(o.type=="opt")return[r(l)].concat(s(o.expr,l));if(o.type=="range"){let a=l;for(let c=0;c{n[o].forEach(({term:l,to:a})=>{if(!l)return;let c;for(let u=0;u{c||i.push([l,c=[]]),c.indexOf(u)==-1&&c.push(u)})})});let s=e[r.join(",")]=new Dt(r.indexOf(n.length-1)>-1);for(let o=0;o-1}get whitespace(){return this.spec.whitespace||(this.spec.code?"pre":"normal")}hasRequiredAttrs(){for(let e in this.attrs)if(this.attrs[e].isRequired)return!0;return!1}compatibleContent(e){return this==e||this.contentMatch.compatible(e.contentMatch)}computeAttrs(e){return!e&&this.defaultAttrs?this.defaultAttrs:ja(this.attrs,e)}create(e=null,t,r){if(this.isText)throw new Error("NodeType.create can't construct text nodes");return new At(this,this.computeAttrs(e),b.from(t),$.setFrom(r))}createChecked(e=null,t,r){return t=b.from(t),this.checkContent(t),new At(this,this.computeAttrs(e),t,$.setFrom(r))}createAndFill(e=null,t,r){if(e=this.computeAttrs(e),t=b.from(t),t.size){let o=this.contentMatch.fillBefore(t);if(!o)return null;t=o.append(t)}let i=this.contentMatch.matchFragment(t),s=i&&i.fillBefore(b.empty,!0);return s?new At(this,e,t.append(s),$.setFrom(r)):null}validContent(e){let t=this.contentMatch.matchFragment(e);if(!t||!t.validEnd)return!1;for(let r=0;r-1}allowsMarks(e){if(this.markSet==null)return!0;for(let t=0;tr[s]=new Ua(s,t,o));let i=t.spec.topNode||"doc";if(!r[i])throw new RangeError("Schema is missing its top node type ('"+i+"')");if(!r.text)throw new RangeError("Every schema needs a 'text' type");for(let s in r.text.attrs)throw new RangeError("The text node type should not have attributes");return r}};function hf(n,e,t){let r=t.split("|");return i=>{let s=i===null?"null":typeof i;if(r.indexOf(s)<0)throw new RangeError(`Expected value of type ${r} for attribute ${e} on type ${n}, got ${s}`)}}class pf{constructor(e,t,r){this.hasDefault=Object.prototype.hasOwnProperty.call(r,"default"),this.default=r.default,this.validate=typeof r.validate=="string"?hf(e,t,r.validate):r.validate}get isRequired(){return!this.hasDefault}}class ci{constructor(e,t,r,i){this.name=e,this.rank=t,this.schema=r,this.spec=i,this.attrs=_a(e,i.attrs),this.excluded=null;let s=Wa(this.attrs);this.instance=s?new $(this,s):null}create(e=null){return!e&&this.instance?this.instance:new $(this,ja(this.attrs,e))}static compile(e,t){let r=Object.create(null),i=0;return e.forEach((s,o)=>r[s]=new ci(s,i++,t,o)),r}removeFromSet(e){for(var t=0;t-1}}class Ka{constructor(e){this.linebreakReplacement=null,this.cached=Object.create(null);let t=this.spec={};for(let i in e)t[i]=e[i];t.nodes=ne.from(e.nodes),t.marks=ne.from(e.marks||{}),this.nodes=Do.compile(this.spec.nodes,this),this.marks=ci.compile(this.spec.marks,this);let r=Object.create(null);for(let i in this.nodes){if(i in this.marks)throw new RangeError(i+" can not be both a node and a mark");let s=this.nodes[i],o=s.spec.content||"",l=s.spec.marks;if(s.contentMatch=r[o]||(r[o]=Dt.parse(o,this.nodes)),s.inlineContent=s.contentMatch.inlineContent,s.spec.linebreakReplacement){if(this.linebreakReplacement)throw new RangeError("Multiple linebreak nodes defined");if(!s.isInline||!s.isLeaf)throw new RangeError("Linebreak replacement nodes must be inline leaf nodes");this.linebreakReplacement=s}s.markSet=l=="_"?null:l?Io(this,l.split(" ")):l==""||!s.inlineContent?[]:null}for(let i in this.marks){let s=this.marks[i],o=s.spec.excludes;s.excluded=o==null?[s]:o==""?[]:Io(this,o.split(" "))}this.nodeFromJSON=i=>At.fromJSON(this,i),this.markFromJSON=i=>$.fromJSON(this,i),this.topNodeType=this.nodes[this.spec.topNode||"doc"],this.cached.wrappings=Object.create(null)}node(e,t=null,r,i){if(typeof e=="string")e=this.nodeType(e);else if(e instanceof Do){if(e.schema!=this)throw new RangeError("Node type from different schema used ("+e.name+")")}else throw new RangeError("Invalid node type: "+e);return e.createChecked(t,r,i)}text(e,t){let r=this.nodes.text;return new Cr(r,r.defaultAttrs,e,$.setFrom(t))}mark(e,t){return typeof e=="string"&&(e=this.marks[e]),e.create(t)}nodeType(e){let t=this.nodes[e];if(!t)throw new RangeError("Unknown node type: "+e);return t}}function Io(n,e){let t=[];for(let r=0;r-1)&&t.push(o=a)}if(!o)throw new SyntaxError("Unknown mark type: '"+e[r]+"'")}return t}function mf(n){return n.tag!=null}function gf(n){return n.style!=null}class Ke{constructor(e,t){this.schema=e,this.rules=t,this.tags=[],this.styles=[];let r=this.matchedStyles=[];t.forEach(i=>{if(mf(i))this.tags.push(i);else if(gf(i)){let s=/[^=]*/.exec(i.style)[0];r.indexOf(s)<0&&r.push(s),this.styles.push(i)}}),this.normalizeLists=!this.tags.some(i=>{if(!/^(ul|ol)\b/.test(i.tag)||!i.node)return!1;let s=e.nodes[i.node];return s.contentMatch.matchType(s)})}parse(e,t={}){let r=new Po(this,t,!1);return r.addAll(e,$.none,t.from,t.to),r.finish()}parseSlice(e,t={}){let r=new Po(this,t,!0);return r.addAll(e,$.none,t.from,t.to),x.maxOpen(r.finish())}matchTag(e,t,r){for(let i=r?this.tags.indexOf(r)+1:0;ie.length&&(l.charCodeAt(e.length)!=61||l.slice(e.length+1)!=t))){if(o.getAttrs){let a=o.getAttrs(t);if(a===!1)continue;o.attrs=a||void 0}return o}}}static schemaRules(e){let t=[];function r(i){let s=i.priority==null?50:i.priority,o=0;for(;o{r(o=zo(o)),o.mark||o.ignore||o.clearMark||(o.mark=i)})}for(let i in e.nodes){let s=e.nodes[i].spec.parseDOM;s&&s.forEach(o=>{r(o=zo(o)),o.node||o.ignore||o.mark||(o.node=i)})}return t}static fromSchema(e){return e.cached.domParser||(e.cached.domParser=new Ke(e,Ke.schemaRules(e)))}}const qa={address:!0,article:!0,aside:!0,blockquote:!0,body:!0,canvas:!0,dd:!0,div:!0,dl:!0,fieldset:!0,figcaption:!0,figure:!0,footer:!0,form:!0,h1:!0,h2:!0,h3:!0,h4:!0,h5:!0,h6:!0,header:!0,hgroup:!0,hr:!0,li:!0,noscript:!0,ol:!0,output:!0,p:!0,pre:!0,section:!0,table:!0,tfoot:!0,ul:!0},yf={head:!0,noscript:!0,object:!0,script:!0,style:!0,title:!0},Ja={ol:!0,ul:!0},Dn=1,ss=2,bn=4;function Lo(n,e,t){return e!=null?(e?Dn:0)|(e==="full"?ss:0):n&&n.whitespace=="pre"?Dn|ss:t&~bn}class Xn{constructor(e,t,r,i,s,o){this.type=e,this.attrs=t,this.marks=r,this.solid=i,this.options=o,this.content=[],this.activeMarks=$.none,this.match=s||(o&bn?null:e.contentMatch)}findWrapping(e){if(!this.match){if(!this.type)return[];let t=this.type.contentMatch.fillBefore(b.from(e));if(t)this.match=this.type.contentMatch.matchFragment(t);else{let r=this.type.contentMatch,i;return(i=r.findWrapping(e.type))?(this.match=r,i):null}}return this.match.findWrapping(e.type)}finish(e){if(!(this.options&Dn)){let r=this.content[this.content.length-1],i;if(r&&r.isText&&(i=/[ \t\r\n\u000c]+$/.exec(r.text))){let s=r;r.text.length==i[0].length?this.content.pop():this.content[this.content.length-1]=s.withText(s.text.slice(0,s.text.length-i[0].length))}}let t=b.from(this.content);return!e&&this.match&&(t=t.append(this.match.fillBefore(b.empty,!0))),this.type?this.type.create(this.attrs,t,this.marks):t}inlineContext(e){return this.type?this.type.inlineContent:this.content.length?this.content[0].isInline:e.parentNode&&!qa.hasOwnProperty(e.parentNode.nodeName.toLowerCase())}}class Po{constructor(e,t,r){this.parser=e,this.options=t,this.isOpen=r,this.open=0,this.localPreserveWS=!1;let i=t.topNode,s,o=Lo(null,t.preserveWhitespace,0)|(r?bn:0);i?s=new Xn(i.type,i.attrs,$.none,!0,t.topMatch||i.type.contentMatch,o):r?s=new Xn(null,null,$.none,!0,null,o):s=new Xn(e.schema.topNodeType,null,$.none,!0,null,o),this.nodes=[s],this.find=t.findPositions,this.needsBlock=!1}get top(){return this.nodes[this.open]}addDOM(e,t){e.nodeType==3?this.addTextNode(e,t):e.nodeType==1&&this.addElement(e,t)}addTextNode(e,t){let r=e.nodeValue,i=this.top,s=i.options&ss?"full":this.localPreserveWS||(i.options&Dn)>0,{schema:o}=this.parser;if(s==="full"||i.inlineContext(e)||/[^ \t\r\n\u000c]/.test(r)){if(s)if(s==="full")r=r.replace(/\r\n?/g,` +`);else if(o.linebreakReplacement&&/[\r\n]/.test(r)&&this.top.findWrapping(o.linebreakReplacement.create())){let l=r.split(/\r?\n|\r/);for(let a=0;a!a.clearMark(c)):t=t.concat(this.parser.schema.marks[a.mark].create(a.attrs)),a.consuming===!1)l=a;else break}}return t}addElementByRule(e,t,r,i){let s,o;if(t.node)if(o=this.parser.schema.nodes[t.node],o.isLeaf)this.insertNode(o.create(t.attrs),r,e.nodeName=="BR")||this.leafFallback(e,r);else{let a=this.enter(o,t.attrs||null,r,t.preserveWhitespace);a&&(s=!0,r=a)}else{let a=this.parser.schema.marks[t.mark];r=r.concat(a.create(t.attrs))}let l=this.top;if(o&&o.isLeaf)this.findInside(e);else if(i)this.addElement(e,r,i);else if(t.getContent)this.findInside(e),t.getContent(e,this.parser.schema).forEach(a=>this.insertNode(a,r,!1));else{let a=e;typeof t.contentElement=="string"?a=e.querySelector(t.contentElement):typeof t.contentElement=="function"?a=t.contentElement(e):t.contentElement&&(a=t.contentElement),this.findAround(e,a,!0),this.addAll(a,r),this.findAround(e,a,!1)}s&&this.sync(l)&&this.open--}addAll(e,t,r,i){let s=r||0;for(let o=r?e.childNodes[r]:e.firstChild,l=i==null?null:e.childNodes[i];o!=l;o=o.nextSibling,++s)this.findAtPoint(e,s),this.addDOM(o,t);this.findAtPoint(e,s)}findPlace(e,t,r){let i,s;for(let o=this.open,l=0;o>=0;o--){let a=this.nodes[o],c=a.findWrapping(e);if(c&&(!i||i.length>c.length+l)&&(i=c,s=a,!c.length))break;if(a.solid){if(r)break;l+=2}}if(!i)return null;this.sync(s);for(let o=0;o(o.type?o.type.allowsMarkType(c.type):Bo(c.type,e))?(a=c.addToSet(a),!1):!0),this.nodes.push(new Xn(e,t,a,i,null,l)),this.open++,r}closeExtra(e=!1){let t=this.nodes.length-1;if(t>this.open){for(;t>this.open;t--)this.nodes[t-1].content.push(this.nodes[t].finish(e));this.nodes.length=this.open+1}}finish(){return this.open=0,this.closeExtra(this.isOpen),this.nodes[0].finish(!!(this.isOpen||this.options.topOpen))}sync(e){for(let t=this.open;t>=0;t--){if(this.nodes[t]==e)return this.open=t,!0;this.localPreserveWS&&(this.nodes[t].options|=Dn)}return!1}get currentPos(){this.closeExtra();let e=0;for(let t=this.open;t>=0;t--){let r=this.nodes[t].content;for(let i=r.length-1;i>=0;i--)e+=r[i].nodeSize;t&&e++}return e}findAtPoint(e,t){if(this.find)for(let r=0;r-1)return e.split(/\s*\|\s*/).some(this.matchesContext,this);let t=e.split("/"),r=this.options.context,i=!this.isOpen&&(!r||r.parent.type==this.nodes[0].type),s=-(r?r.depth+1:0)+(i?0:1),o=(l,a)=>{for(;l>=0;l--){let c=t[l];if(c==""){if(l==t.length-1||l==0)continue;for(;a>=s;a--)if(o(l-1,a))return!0;return!1}else{let u=a>0||a==0&&i?this.nodes[a].type:r&&a>=s?r.node(a-s).type:null;if(!u||u.name!=c&&!u.isInGroup(c))return!1;a--}}return!0};return o(t.length-1,this.open)}textblockFromContext(){let e=this.options.context;if(e)for(let t=e.depth;t>=0;t--){let r=e.node(t).contentMatchAt(e.indexAfter(t)).defaultType;if(r&&r.isTextblock&&r.defaultAttrs)return r}for(let t in this.parser.schema.nodes){let r=this.parser.schema.nodes[t];if(r.isTextblock&&r.defaultAttrs)return r}}}function bf(n){for(let e=n.firstChild,t=null;e;e=e.nextSibling){let r=e.nodeType==1?e.nodeName.toLowerCase():null;r&&Ja.hasOwnProperty(r)&&t?(t.appendChild(e),e=t):r=="li"?t=e:r&&(t=null)}}function kf(n,e){return(n.matches||n.msMatchesSelector||n.webkitMatchesSelector||n.mozMatchesSelector).call(n,e)}function zo(n){let e={};for(let t in n)e[t]=n[t];return e}function Bo(n,e){let t=e.schema.nodes;for(let r in t){let i=t[r];if(!i.allowsMarkType(n))continue;let s=[],o=l=>{s.push(l);for(let a=0;a{if(s.length||o.marks.length){let l=0,a=0;for(;l=0;i--){let s=this.serializeMark(e.marks[i],e.isInline,t);s&&((s.contentDOM||s.dom).appendChild(r),r=s.dom)}return r}serializeMark(e,t,r={}){let i=this.marks[e.type.name];return i&&fr(Qn(r),i(e,t),null,e.attrs)}static renderSpec(e,t,r=null,i){return typeof t=="string"?{dom:e.createTextNode(t)}:fr(e,t,r,i)}static fromSchema(e){return e.cached.domSerializer||(e.cached.domSerializer=new ht(this.nodesFromSchema(e),this.marksFromSchema(e)))}static nodesFromSchema(e){let t=$o(e.nodes);return t.text||(t.text=r=>r.text),t}static marksFromSchema(e){return $o(e.marks)}}function $o(n){let e={};for(let t in n){let r=n[t].spec.toDOM;r&&(e[t]=r)}return e}function Qn(n){return n.document||window.document}const Ho=new WeakMap;function wf(n){let e=Ho.get(n);return e===void 0&&Ho.set(n,e=Sf(n)),e}function Sf(n){let e=null;function t(r){if(r&&typeof r=="object")if(Array.isArray(r))if(typeof r[0]=="string")e||(e=[]),e.push(r);else for(let i=0;i-1)throw new RangeError("Using an array from an attribute object as a DOM spec. This may be an attempted cross site scripting attack.");let o=i.indexOf(" ");o>0&&(t=i.slice(0,o),i=i.slice(o+1));let l,a=t?n.createElementNS(t,i):n.createElement(i),c=e[1],u=1;if(c&&typeof c=="object"&&c.nodeType==null&&!Array.isArray(c)){u=2;for(let d in c)if(c[d]!=null){let f=d.indexOf(" ");f>0?a.setAttributeNS(d.slice(0,f),d.slice(f+1),c[d]):d=="style"&&a.style?a.style.cssText=c[d]:a.setAttribute(d,c[d])}}for(let d=u;du)throw new RangeError("Content hole must be the only child of its parent node");return{dom:a,contentDOM:a}}else if(typeof f=="string")a.appendChild(n.createTextNode(f));else{let{dom:h,contentDOM:p}=fr(n,f,t,r);if(a.appendChild(h),p){if(l)throw new RangeError("Multiple content holes");l=p}}}return{dom:a,contentDOM:l}}const Ga=65535,Ya=Math.pow(2,16);function Cf(n,e){return n+e*Ya}function Fo(n){return n&Ga}function xf(n){return(n-(n&Ga))/Ya}const Xa=1,Qa=2,hr=4,Za=8;class ls{constructor(e,t,r){this.pos=e,this.delInfo=t,this.recover=r}get deleted(){return(this.delInfo&Za)>0}get deletedBefore(){return(this.delInfo&(Xa|hr))>0}get deletedAfter(){return(this.delInfo&(Qa|hr))>0}get deletedAcross(){return(this.delInfo&hr)>0}}class me{constructor(e,t=!1){if(this.ranges=e,this.inverted=t,!e.length&&me.empty)return me.empty}recover(e){let t=0,r=Fo(e);if(!this.inverted)for(let i=0;ie)break;let c=this.ranges[l+s],u=this.ranges[l+o],d=a+c;if(e<=d){let f=c?e==a?-1:e==d?1:t:t,h=a+i+(f<0?0:u);if(r)return h;let p=e==(t<0?a:d)?null:Cf(l/3,e-a),m=0;return c&&(m|=e==a?Qa:e==d?Xa:hr,(t<0?e!=a:e!=d)&&(m|=Za)),new ls(h,m,p)}i+=u-c}return r?e+i:new ls(e+i,0,null)}touches(e,t){let r=0,i=Fo(t),s=this.inverted?2:1,o=this.inverted?1:2;for(let l=0;le)break;let c=this.ranges[l+s],u=a+c;if(e<=u&&l==i*3)return!0;r+=this.ranges[l+o]-c}return!1}forEach(e){let t=this.inverted?2:1,r=this.inverted?1:2;for(let i=0,s=0;i=0;t--){let i=e.getMirror(t);this.appendMap(e._maps[t].invert(),i!=null&&i>t?r-i-1:void 0)}}invert(){let e=new In;return e.appendMappingInverted(this),e}map(e,t=1){if(this.mirror)return this._map(e,t,!0);for(let r=this.from;rs&&a!o.isAtom||!l.type.allowsMarkType(this.mark.type)?o:o.mark(this.mark.addToSet(o.marks)),i),t.openStart,t.openEnd);return G.fromReplace(e,this.from,this.to,s)}invert(){return new Ee(this.from,this.to,this.mark)}map(e){let t=e.mapResult(this.from,1),r=e.mapResult(this.to,-1);return t.deleted&&r.deleted||t.pos>=r.pos?null:new it(t.pos,r.pos,this.mark)}merge(e){return e instanceof it&&e.mark.eq(this.mark)&&this.from<=e.to&&this.to>=e.from?new it(Math.min(this.from,e.from),Math.max(this.to,e.to),this.mark):null}toJSON(){return{stepType:"addMark",mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(e,t){if(typeof t.from!="number"||typeof t.to!="number")throw new RangeError("Invalid input for AddMarkStep.fromJSON");return new it(t.from,t.to,e.markFromJSON(t.mark))}}ue.jsonID("addMark",it);class Ee extends ue{constructor(e,t,r){super(),this.from=e,this.to=t,this.mark=r}apply(e){let t=e.slice(this.from,this.to),r=new x(js(t.content,i=>i.mark(this.mark.removeFromSet(i.marks)),e),t.openStart,t.openEnd);return G.fromReplace(e,this.from,this.to,r)}invert(){return new it(this.from,this.to,this.mark)}map(e){let t=e.mapResult(this.from,1),r=e.mapResult(this.to,-1);return t.deleted&&r.deleted||t.pos>=r.pos?null:new Ee(t.pos,r.pos,this.mark)}merge(e){return e instanceof Ee&&e.mark.eq(this.mark)&&this.from<=e.to&&this.to>=e.from?new Ee(Math.min(this.from,e.from),Math.max(this.to,e.to),this.mark):null}toJSON(){return{stepType:"removeMark",mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(e,t){if(typeof t.from!="number"||typeof t.to!="number")throw new RangeError("Invalid input for RemoveMarkStep.fromJSON");return new Ee(t.from,t.to,e.markFromJSON(t.mark))}}ue.jsonID("removeMark",Ee);class st extends ue{constructor(e,t){super(),this.pos=e,this.mark=t}apply(e){let t=e.nodeAt(this.pos);if(!t)return G.fail("No node at mark step's position");let r=t.type.create(t.attrs,null,this.mark.addToSet(t.marks));return G.fromReplace(e,this.pos,this.pos+1,new x(b.from(r),0,t.isLeaf?0:1))}invert(e){let t=e.nodeAt(this.pos);if(t){let r=this.mark.addToSet(t.marks);if(r.length==t.marks.length){for(let i=0;ir.pos?null:new Z(t.pos,r.pos,i,s,this.slice,this.insert,this.structure)}toJSON(){let e={stepType:"replaceAround",from:this.from,to:this.to,gapFrom:this.gapFrom,gapTo:this.gapTo,insert:this.insert};return this.slice.size&&(e.slice=this.slice.toJSON()),this.structure&&(e.structure=!0),e}static fromJSON(e,t){if(typeof t.from!="number"||typeof t.to!="number"||typeof t.gapFrom!="number"||typeof t.gapTo!="number"||typeof t.insert!="number")throw new RangeError("Invalid input for ReplaceAroundStep.fromJSON");return new Z(t.from,t.to,t.gapFrom,t.gapTo,x.fromJSON(e,t.slice),t.insert,!!t.structure)}}ue.jsonID("replaceAround",Z);function as(n,e,t){let r=n.resolve(e),i=t-e,s=r.depth;for(;i>0&&s>0&&r.indexAfter(s)==r.node(s).childCount;)s--,i--;if(i>0){let o=r.node(s).maybeChild(r.indexAfter(s));for(;i>0;){if(!o||o.isLeaf)return!0;o=o.firstChild,i--}}return!1}function vf(n,e,t,r){let i=[],s=[],o,l;n.doc.nodesBetween(e,t,(a,c,u)=>{if(!a.isInline)return;let d=a.marks;if(!r.isInSet(d)&&u.type.allowsMarkType(r.type)){let f=Math.max(c,e),h=Math.min(c+a.nodeSize,t),p=r.addToSet(d);for(let m=0;mn.step(a)),s.forEach(a=>n.step(a))}function Mf(n,e,t,r){let i=[],s=0;n.doc.nodesBetween(e,t,(o,l)=>{if(!o.isInline)return;s++;let a=null;if(r instanceof ci){let c=o.marks,u;for(;u=r.isInSet(c);)(a||(a=[])).push(u),c=u.removeFromSet(c)}else r?r.isInSet(o.marks)&&(a=[r]):a=o.marks;if(a&&a.length){let c=Math.min(l+o.nodeSize,t);for(let u=0;un.step(new Ee(o.from,o.to,o.style)))}function _s(n,e,t,r=t.contentMatch,i=!0){let s=n.doc.nodeAt(e),o=[],l=e+1;for(let a=0;a=0;a--)n.step(o[a])}function Tf(n,e,t){return(e==0||n.canReplace(e,n.childCount))&&(t==n.childCount||n.canReplace(0,t))}function on(n){let t=n.parent.content.cutByIndex(n.startIndex,n.endIndex);for(let r=n.depth,i=0,s=0;;--r){let o=n.$from.node(r),l=n.$from.index(r)+i,a=n.$to.indexAfter(r)-s;if(rt;p--)m||r.index(p)>0?(m=!0,u=b.from(r.node(p).copy(u)),d++):a--;let f=b.empty,h=0;for(let p=s,m=!1;p>t;p--)m||i.after(p+1)=0;o--){if(r.size){let l=t[o].type.contentMatch.matchFragment(r);if(!l||!l.validEnd)throw new RangeError("Wrapper type given to Transform.wrap does not form valid content of its parent wrapper")}r=b.from(t[o].type.create(t[o].attrs,r))}let i=e.start,s=e.end;n.step(new Z(i,s,i,s,new x(r,0,0),t.length,!0))}function Rf(n,e,t,r,i){if(!r.isTextblock)throw new RangeError("Type given to setBlockType should be a textblock");let s=n.steps.length;n.doc.nodesBetween(e,t,(o,l)=>{let a=typeof i=="function"?i(o):i;if(o.isTextblock&&!o.hasMarkup(r,a)&&Df(n.doc,n.mapping.slice(s).map(l),r)){let c=null;if(r.schema.linebreakReplacement){let h=r.whitespace=="pre",p=!!r.contentMatch.matchType(r.schema.linebreakReplacement);h&&!p?c=!1:!h&&p&&(c=!0)}c===!1&&tc(n,o,l,s),_s(n,n.mapping.slice(s).map(l,1),r,void 0,c===null);let u=n.mapping.slice(s),d=u.map(l,1),f=u.map(l+o.nodeSize,1);return n.step(new Z(d,f,d+1,f-1,new x(b.from(r.create(a,null,o.marks)),0,0),1,!0)),c===!0&&ec(n,o,l,s),!1}})}function ec(n,e,t,r){e.forEach((i,s)=>{if(i.isText){let o,l=/\r?\n|\r/g;for(;o=l.exec(i.text);){let a=n.mapping.slice(r).map(t+1+s+o.index);n.replaceWith(a,a+1,e.type.schema.linebreakReplacement.create())}}})}function tc(n,e,t,r){e.forEach((i,s)=>{if(i.type==i.type.schema.linebreakReplacement){let o=n.mapping.slice(r).map(t+1+s);n.replaceWith(o,o+1,e.type.schema.text(` +`))}})}function Df(n,e,t){let r=n.resolve(e),i=r.index();return r.parent.canReplaceWith(i,i+1,t)}function If(n,e,t,r,i){let s=n.doc.nodeAt(e);if(!s)throw new RangeError("No node at given position");t||(t=s.type);let o=t.create(r,null,i||s.marks);if(s.isLeaf)return n.replaceWith(e,e+s.nodeSize,o);if(!t.validContent(s.content))throw new RangeError("Invalid content for node type "+t.name);n.step(new Z(e,e+s.nodeSize,e+1,e+s.nodeSize-1,new x(b.from(o),0,0),1,!0))}function qe(n,e,t=1,r){let i=n.resolve(e),s=i.depth-t,o=r&&r[r.length-1]||i.parent;if(s<0||i.parent.type.spec.isolating||!i.parent.canReplace(i.index(),i.parent.childCount)||!o.type.validContent(i.parent.content.cutByIndex(i.index(),i.parent.childCount)))return!1;for(let c=i.depth-1,u=t-2;c>s;c--,u--){let d=i.node(c),f=i.index(c);if(d.type.spec.isolating)return!1;let h=d.content.cutByIndex(f,d.childCount),p=r&&r[u+1];p&&(h=h.replaceChild(0,p.type.create(p.attrs)));let m=r&&r[u]||d;if(!d.canReplace(f+1,d.childCount)||!m.type.validContent(h))return!1}let l=i.indexAfter(s),a=r&&r[0];return i.node(s).canReplaceWith(l,l,a?a.type:i.node(s+1).type)}function Lf(n,e,t=1,r){let i=n.doc.resolve(e),s=b.empty,o=b.empty;for(let l=i.depth,a=i.depth-t,c=t-1;l>a;l--,c--){s=b.from(i.node(l).copy(s));let u=r&&r[c];o=b.from(u?u.type.create(u.attrs,o):i.node(l).copy(o))}n.step(new K(e,e,new x(s.append(o),t,t),!0))}function pt(n,e){let t=n.resolve(e),r=t.index();return nc(t.nodeBefore,t.nodeAfter)&&t.parent.canReplace(r,r+1)}function Pf(n,e){e.content.size||n.type.compatibleContent(e.type);let t=n.contentMatchAt(n.childCount),{linebreakReplacement:r}=n.type.schema;for(let i=0;i0?(s=r.node(i+1),l++,o=r.node(i).maybeChild(l)):(s=r.node(i).maybeChild(l-1),o=r.node(i+1)),s&&!s.isTextblock&&nc(s,o)&&r.node(i).canReplace(l,l+1))return e;if(i==0)break;e=t<0?r.before(i):r.after(i)}}function zf(n,e,t){let r=null,{linebreakReplacement:i}=n.doc.type.schema,s=n.doc.resolve(e-t),o=s.node().type;if(i&&o.inlineContent){let u=o.whitespace=="pre",d=!!o.contentMatch.matchType(i);u&&!d?r=!1:!u&&d&&(r=!0)}let l=n.steps.length;if(r===!1){let u=n.doc.resolve(e+t);tc(n,u.node(),u.before(),l)}o.inlineContent&&_s(n,e+t-1,o,s.node().contentMatchAt(s.index()),r==null);let a=n.mapping.slice(l),c=a.map(e-t);if(n.step(new K(c,a.map(e+t,-1),x.empty,!0)),r===!0){let u=n.doc.resolve(c);ec(n,u.node(),u.before(),n.steps.length)}return n}function Bf(n,e,t){let r=n.resolve(e);if(r.parent.canReplaceWith(r.index(),r.index(),t))return e;if(r.parentOffset==0)for(let i=r.depth-1;i>=0;i--){let s=r.index(i);if(r.node(i).canReplaceWith(s,s,t))return r.before(i+1);if(s>0)return null}if(r.parentOffset==r.parent.content.size)for(let i=r.depth-1;i>=0;i--){let s=r.indexAfter(i);if(r.node(i).canReplaceWith(s,s,t))return r.after(i+1);if(s=0;o--){let l=o==r.depth?0:r.pos<=(r.start(o+1)+r.end(o+1))/2?-1:1,a=r.index(o)+(l>0?1:0),c=r.node(o),u=!1;if(s==1)u=c.canReplace(a,a,i);else{let d=c.contentMatchAt(a).findWrapping(i.firstChild.type);u=d&&c.canReplaceWith(a,a,d[0])}if(u)return l==0?r.pos:l<0?r.before(o+1):r.after(o+1)}return null}function di(n,e,t=e,r=x.empty){if(e==t&&!r.size)return null;let i=n.resolve(e),s=n.resolve(t);return ic(i,s,r)?new K(e,t,r):new $f(i,s,r).fit()}function ic(n,e,t){return!t.openStart&&!t.openEnd&&n.start()==e.start()&&n.parent.canReplace(n.index(),e.index(),t.content)}class $f{constructor(e,t,r){this.$from=e,this.$to=t,this.unplaced=r,this.frontier=[],this.placed=b.empty;for(let i=0;i<=e.depth;i++){let s=e.node(i);this.frontier.push({type:s.type,match:s.contentMatchAt(e.indexAfter(i))})}for(let i=e.depth;i>0;i--)this.placed=b.from(e.node(i).copy(this.placed))}get depth(){return this.frontier.length-1}fit(){for(;this.unplaced.size;){let c=this.findFittable();c?this.placeNodes(c):this.openMore()||this.dropNode()}let e=this.mustMoveInline(),t=this.placed.size-this.depth-this.$from.depth,r=this.$from,i=this.close(e<0?this.$to:r.doc.resolve(e));if(!i)return null;let s=this.placed,o=r.depth,l=i.depth;for(;o&&l&&s.childCount==1;)s=s.firstChild.content,o--,l--;let a=new x(s,o,l);return e>-1?new Z(r.pos,e,this.$to.pos,this.$to.end(),a,t):a.size||r.pos!=this.$to.pos?new K(r.pos,i.pos,a):null}findFittable(){let e=this.unplaced.openStart;for(let t=this.unplaced.content,r=0,i=this.unplaced.openEnd;r1&&(i=0),s.type.spec.isolating&&i<=r){e=r;break}t=s.content}for(let t=1;t<=2;t++)for(let r=t==1?e:this.unplaced.openStart;r>=0;r--){let i,s=null;r?(s=Wo(this.unplaced.content,r-1).firstChild,i=s.content):i=this.unplaced.content;let o=i.firstChild;for(let l=this.depth;l>=0;l--){let{type:a,match:c}=this.frontier[l],u,d=null;if(t==1&&(o?c.matchType(o.type)||(d=c.fillBefore(b.from(o),!1)):s&&a.compatibleContent(s.type)))return{sliceDepth:r,frontierDepth:l,parent:s,inject:d};if(t==2&&o&&(u=c.findWrapping(o.type)))return{sliceDepth:r,frontierDepth:l,parent:s,wrap:u};if(s&&c.matchType(s.type))break}}}openMore(){let{content:e,openStart:t,openEnd:r}=this.unplaced;return jo(e,-1)<=t?!1:(this.unplaced.size>1&&jo(e,1)>r&&r++,this.unplaced=new x(e,t+1,r),!0)}dropNode(){let{content:e,openStart:t,openEnd:r}=this.unplaced,i=Wo(e,t);if(i.childCount<=1&&t>0){let s=e.size-t<=t+i.size;this.unplaced=new x(fn(e,t-1,1),t-1,s?t-1:r)}else this.unplaced=new x(fn(e,t,1),t,r)}placeNodes({sliceDepth:e,frontierDepth:t,parent:r,inject:i,wrap:s}){for(;this.depth>t;)this.closeFrontierNode();if(s)for(let m=0;m1||a==0||m.content.size)&&(d=g,u.push(sc(m.mark(f.allowedMarks(m.marks)),c==1?a:0,c==l.childCount?h:-1)))}let p=c==l.childCount;p||(h=-1),this.placed=hn(this.placed,t,b.from(u)),this.frontier[t].match=d,p&&h<0&&r&&r.type==this.frontier[this.depth].type&&this.frontier.length>1&&this.closeFrontierNode();for(let m=0,g=l;m1&&i==this.$to.end(--r);)++i;return i}findCloseLevel(e){e:for(let t=Math.min(this.depth,e.depth);t>=0;t--){let{match:r,type:i}=this.frontier[t],s=t=0;l--){let{match:a,type:c}=this.frontier[l],u=Ni(e,l,c,a,!0);if(!u||u.childCount)continue e}return{depth:t,fit:o,move:s?e.doc.resolve(e.after(t+1)):e}}}}close(e){let t=this.findCloseLevel(e);if(!t)return null;for(;this.depth>t.depth;)this.closeFrontierNode();t.fit.childCount&&(this.placed=hn(this.placed,t.depth,t.fit)),e=t.move;for(let r=t.depth+1;r<=e.depth;r++){let i=e.node(r),s=i.type.contentMatch.fillBefore(i.content,!0,e.index(r));this.openFrontierNode(i.type,i.attrs,s)}return e}openFrontierNode(e,t=null,r){let i=this.frontier[this.depth];i.match=i.match.matchType(e),this.placed=hn(this.placed,this.depth,b.from(e.create(t,r))),this.frontier.push({type:e,match:e.contentMatch})}closeFrontierNode(){let t=this.frontier.pop().match.fillBefore(b.empty,!0);t.childCount&&(this.placed=hn(this.placed,this.frontier.length,t))}}function fn(n,e,t){return e==0?n.cutByIndex(t,n.childCount):n.replaceChild(0,n.firstChild.copy(fn(n.firstChild.content,e-1,t)))}function hn(n,e,t){return e==0?n.append(t):n.replaceChild(n.childCount-1,n.lastChild.copy(hn(n.lastChild.content,e-1,t)))}function Wo(n,e){for(let t=0;t1&&(r=r.replaceChild(0,sc(r.firstChild,e-1,r.childCount==1?t-1:0))),e>0&&(r=n.type.contentMatch.fillBefore(r).append(r),t<=0&&(r=r.append(n.type.contentMatch.matchFragment(r).fillBefore(b.empty,!0)))),n.copy(r)}function Ni(n,e,t,r,i){let s=n.node(e),o=i?n.indexAfter(e):n.index(e);if(o==s.childCount&&!t.compatibleContent(s.type))return null;let l=r.fillBefore(s.content,!0,o);return l&&!Hf(t,s.content,o)?l:null}function Hf(n,e,t){for(let r=t;r0;f--,h--){let p=i.node(f).type.spec;if(p.defining||p.definingAsContext||p.isolating)break;o.indexOf(f)>-1?l=f:i.before(f)==h&&o.splice(1,0,-f)}let a=o.indexOf(l),c=[],u=r.openStart;for(let f=r.content,h=0;;h++){let p=f.firstChild;if(c.push(p),h==r.openStart)break;f=p.content}for(let f=u-1;f>=0;f--){let h=c[f],p=Ff(h.type);if(p&&!h.sameMarkup(i.node(Math.abs(l)-1)))u=f;else if(p||!h.type.isTextblock)break}for(let f=r.openStart;f>=0;f--){let h=(f+u+1)%(r.openStart+1),p=c[h];if(p)for(let m=0;m=0&&(n.replace(e,t,r),!(n.steps.length>d));f--){let h=o[f];h<0||(e=i.before(h),t=s.after(h))}}function oc(n,e,t,r,i){if(er){let s=i.contentMatchAt(0),o=s.fillBefore(n).append(n);n=o.append(s.matchFragment(o).fillBefore(b.empty,!0))}return n}function Wf(n,e,t,r){if(!r.isInline&&e==t&&n.doc.resolve(e).parent.content.size){let i=Bf(n.doc,e,r.type);i!=null&&(e=t=i)}n.replaceRange(e,t,new x(b.from(r),0,0))}function jf(n,e,t){let r=n.doc.resolve(e),i=n.doc.resolve(t);if(r.parent.isTextblock&&i.parent.isTextblock&&r.start()!=i.start()&&r.parentOffset==0&&i.parentOffset==0){let o=r.sharedDepth(t),l=!1;for(let a=r.depth;a>o;a--)r.node(a).type.spec.isolating&&(l=!0);for(let a=i.depth;a>o;a--)i.node(a).type.spec.isolating&&(l=!0);if(!l){for(let a=r.depth;a>0&&e==r.start(a);a--)e=r.before(a);for(let a=i.depth;a>0&&t==i.start(a);a--)t=i.before(a);r=n.doc.resolve(e),i=n.doc.resolve(t)}}let s=lc(r,i);for(let o=0;o0&&(a||r.node(l-1).canReplace(r.index(l-1),i.indexAfter(l-1))))return n.delete(r.before(l),i.after(l))}for(let o=1;o<=r.depth&&o<=i.depth;o++)if(e-r.start(o)==r.depth-o&&t>r.end(o)&&i.end(o)-t!=i.depth-o&&r.start(o-1)==i.start(o-1)&&r.node(o-1).canReplace(r.index(o-1),i.index(o-1)))return n.delete(r.before(o),t);n.delete(e,t)}function lc(n,e){let t=[],r=Math.min(n.depth,e.depth);for(let i=r;i>=0;i--){let s=n.start(i);if(se.pos+(e.depth-i)||n.node(i).type.spec.isolating||e.node(i).type.spec.isolating)break;(s==e.start(i)||i==n.depth&&i==e.depth&&n.parent.inlineContent&&e.parent.inlineContent&&i&&e.start(i-1)==s-1)&&t.push(i)}return t}class Gt extends ue{constructor(e,t,r){super(),this.pos=e,this.attr=t,this.value=r}apply(e){let t=e.nodeAt(this.pos);if(!t)return G.fail("No node at attribute step's position");let r=Object.create(null);for(let s in t.attrs)r[s]=t.attrs[s];r[this.attr]=this.value;let i=t.type.create(r,null,t.marks);return G.fromReplace(e,this.pos,this.pos+1,new x(b.from(i),0,t.isLeaf?0:1))}getMap(){return me.empty}invert(e){return new Gt(this.pos,this.attr,e.nodeAt(this.pos).attrs[this.attr])}map(e){let t=e.mapResult(this.pos,1);return t.deletedAfter?null:new Gt(t.pos,this.attr,this.value)}toJSON(){return{stepType:"attr",pos:this.pos,attr:this.attr,value:this.value}}static fromJSON(e,t){if(typeof t.pos!="number"||typeof t.attr!="string")throw new RangeError("Invalid input for AttrStep.fromJSON");return new Gt(t.pos,t.attr,t.value)}}ue.jsonID("attr",Gt);class Ln extends ue{constructor(e,t){super(),this.attr=e,this.value=t}apply(e){let t=Object.create(null);for(let i in e.attrs)t[i]=e.attrs[i];t[this.attr]=this.value;let r=e.type.create(t,e.content,e.marks);return G.ok(r)}getMap(){return me.empty}invert(e){return new Ln(this.attr,e.attrs[this.attr])}map(e){return this}toJSON(){return{stepType:"docAttr",attr:this.attr,value:this.value}}static fromJSON(e,t){if(typeof t.attr!="string")throw new RangeError("Invalid input for DocAttrStep.fromJSON");return new Ln(t.attr,t.value)}}ue.jsonID("docAttr",Ln);let Xt=class extends Error{};Xt=function n(e){let t=Error.call(this,e);return t.__proto__=n.prototype,t};Xt.prototype=Object.create(Error.prototype);Xt.prototype.constructor=Xt;Xt.prototype.name="TransformError";class Ks{constructor(e){this.doc=e,this.steps=[],this.docs=[],this.mapping=new In}get before(){return this.docs.length?this.docs[0]:this.doc}step(e){let t=this.maybeStep(e);if(t.failed)throw new Xt(t.failed);return this}maybeStep(e){let t=e.apply(this.doc);return t.failed||this.addStep(e,t.doc),t}get docChanged(){return this.steps.length>0}changedRange(){let e=1e9,t=-1e9;for(let r=0;r{e=Math.min(e,l),t=Math.max(t,a)})}return e==1e9?null:{from:e,to:t}}addStep(e,t){this.docs.push(this.doc),this.steps.push(e),this.mapping.appendMap(e.getMap()),this.doc=t}replace(e,t=e,r=x.empty){let i=di(this.doc,e,t,r);return i&&this.step(i),this}replaceWith(e,t,r){return this.replace(e,t,new x(b.from(r),0,0))}delete(e,t){return this.replace(e,t,x.empty)}insert(e,t){return this.replaceWith(e,e,t)}replaceRange(e,t,r){return Vf(this,e,t,r),this}replaceRangeWith(e,t,r){return Wf(this,e,t,r),this}deleteRange(e,t){return jf(this,e,t),this}lift(e,t){return Ef(this,e,t),this}join(e,t=1){return zf(this,e,t),this}wrap(e,t){return Of(this,e,t),this}setBlockType(e,t=e,r,i=null){return Rf(this,e,t,r,i),this}setNodeMarkup(e,t,r=null,i){return If(this,e,t,r,i),this}setNodeAttribute(e,t,r){return this.step(new Gt(e,t,r)),this}setDocAttribute(e,t){return this.step(new Ln(e,t)),this}addNodeMark(e,t){return this.step(new st(e,t)),this}removeNodeMark(e,t){let r=this.doc.nodeAt(e);if(!r)throw new RangeError("No node at position "+e);if(t instanceof $)t.isInSet(r.marks)&&this.step(new It(e,t));else{let i=r.marks,s,o=[];for(;s=t.isInSet(i);)o.push(new It(e,s)),i=s.removeFromSet(i);for(let l=o.length-1;l>=0;l--)this.step(o[l])}return this}split(e,t=1,r){return Lf(this,e,t,r),this}addMark(e,t,r){return vf(this,e,t,r),this}removeMark(e,t,r){return Mf(this,e,t,r),this}clearIncompatible(e,t,r){return _s(this,e,t,r),this}}const Oi=Object.create(null);class N{constructor(e,t,r){this.$anchor=e,this.$head=t,this.ranges=r||[new ac(e.min(t),e.max(t))]}get anchor(){return this.$anchor.pos}get head(){return this.$head.pos}get from(){return this.$from.pos}get to(){return this.$to.pos}get $from(){return this.ranges[0].$from}get $to(){return this.ranges[0].$to}get empty(){let e=this.ranges;for(let t=0;t=0;s--){let o=t<0?_t(e.node(0),e.node(s),e.before(s+1),e.index(s),t,r):_t(e.node(0),e.node(s),e.after(s+1),e.index(s)+1,t,r);if(o)return o}return null}static near(e,t=1){return this.findFrom(e,t)||this.findFrom(e,-t)||new ye(e.node(0))}static atStart(e){return _t(e,e,0,0,1)||new ye(e)}static atEnd(e){return _t(e,e,e.content.size,e.childCount,-1)||new ye(e)}static fromJSON(e,t){if(!t||!t.type)throw new RangeError("Invalid input for Selection.fromJSON");let r=Oi[t.type];if(!r)throw new RangeError(`No selection type ${t.type} defined`);return r.fromJSON(e,t)}static jsonID(e,t){if(e in Oi)throw new RangeError("Duplicate use of selection JSON ID "+e);return Oi[e]=t,t.prototype.jsonID=e,t}getBookmark(){return v.between(this.$anchor,this.$head).getBookmark()}}N.prototype.visible=!0;class ac{constructor(e,t){this.$from=e,this.$to=t}}let _o=!1;function Uo(n){!_o&&!n.parent.inlineContent&&(_o=!0,console.warn("TextSelection endpoint not pointing into a node with inline content ("+n.parent.type.name+")"))}class v extends N{constructor(e,t=e){Uo(e),Uo(t),super(e,t)}get $cursor(){return this.$anchor.pos==this.$head.pos?this.$head:null}map(e,t){let r=e.resolve(t.map(this.head));if(!r.parent.inlineContent)return N.near(r);let i=e.resolve(t.map(this.anchor));return new v(i.parent.inlineContent?i:r,r)}replace(e,t=x.empty){if(super.replace(e,t),t==x.empty){let r=this.$from.marksAcross(this.$to);r&&e.ensureMarks(r)}}eq(e){return e instanceof v&&e.anchor==this.anchor&&e.head==this.head}getBookmark(){return new fi(this.anchor,this.head)}toJSON(){return{type:"text",anchor:this.anchor,head:this.head}}static fromJSON(e,t){if(typeof t.anchor!="number"||typeof t.head!="number")throw new RangeError("Invalid input for TextSelection.fromJSON");return new v(e.resolve(t.anchor),e.resolve(t.head))}static create(e,t,r=t){let i=e.resolve(t);return new this(i,r==t?i:e.resolve(r))}static between(e,t,r){let i=e.pos-t.pos;if((!r||i)&&(r=i>=0?1:-1),!t.parent.inlineContent){let s=N.findFrom(t,r,!0)||N.findFrom(t,-r,!0);if(s)t=s.$head;else return N.near(t,r)}return e.parent.inlineContent||(i==0?e=t:(e=(N.findFrom(e,-r,!0)||N.findFrom(e,r,!0)).$anchor,e.pos0?0:1);i>0?o=0;o+=i){let l=e.child(o);if(l.isAtom){if(!s&&T.isSelectable(l))return T.create(n,t-(i<0?l.nodeSize:0))}else{let a=_t(n,l,t+i,i<0?l.childCount:0,i,s);if(a)return a}t+=l.nodeSize*i}return null}function Ko(n,e,t){let r=n.steps.length-1;if(r{o==null&&(o=u)}),n.setSelection(N.near(n.doc.resolve(o),t))}const qo=1,Zn=2,Jo=4;class Uf extends Ks{constructor(e){super(e.doc),this.curSelectionFor=0,this.updated=0,this.meta=Object.create(null),this.time=Date.now(),this.curSelection=e.selection,this.storedMarks=e.storedMarks}get selection(){return this.curSelectionFor0}setStoredMarks(e){return this.storedMarks=e,this.updated|=Zn,this}ensureMarks(e){return $.sameSet(this.storedMarks||this.selection.$from.marks(),e)||this.setStoredMarks(e),this}addStoredMark(e){return this.ensureMarks(e.addToSet(this.storedMarks||this.selection.$head.marks()))}removeStoredMark(e){return this.ensureMarks(e.removeFromSet(this.storedMarks||this.selection.$head.marks()))}get storedMarksSet(){return(this.updated&Zn)>0}addStep(e,t){super.addStep(e,t),this.updated=this.updated&~Zn,this.storedMarks=null}setTime(e){return this.time=e,this}replaceSelection(e){return this.selection.replace(this,e),this}replaceSelectionWith(e,t=!0){let r=this.selection;return t&&(e=e.mark(this.storedMarks||(r.empty?r.$from.marks():r.$from.marksAcross(r.$to)||$.none))),r.replaceWith(this,e),this}deleteSelection(){return this.selection.replace(this),this}insertText(e,t,r){let i=this.doc.type.schema;if(t==null)return e?this.replaceSelectionWith(i.text(e),!0):this.deleteSelection();{if(r==null&&(r=t),!e)return this.deleteRange(t,r);let s=this.storedMarks;if(!s){let o=this.doc.resolve(t);s=r==t?o.marks():o.marksAcross(this.doc.resolve(r))}return this.replaceRangeWith(t,r,i.text(e,s)),!this.selection.empty&&this.selection.to==t+e.length&&this.setSelection(N.near(this.selection.$to)),this}}setMeta(e,t){return this.meta[typeof e=="string"?e:e.key]=t,this}getMeta(e){return this.meta[typeof e=="string"?e:e.key]}get isGeneric(){for(let e in this.meta)return!1;return!0}scrollIntoView(){return this.updated|=Jo,this}get scrolledIntoView(){return(this.updated&Jo)>0}}function Go(n,e){return!e||!n?n:n.bind(e)}class pn{constructor(e,t,r){this.name=e,this.init=Go(t.init,r),this.apply=Go(t.apply,r)}}const Kf=[new pn("doc",{init(n){return n.doc||n.schema.topNodeType.createAndFill()},apply(n){return n.doc}}),new pn("selection",{init(n,e){return n.selection||N.atStart(e.doc)},apply(n){return n.selection}}),new pn("storedMarks",{init(n){return n.storedMarks||null},apply(n,e,t,r){return r.selection.$cursor?n.storedMarks:null}}),new pn("scrollToSelection",{init(){return 0},apply(n,e){return n.scrolledIntoView?e+1:e}})];class Ri{constructor(e,t){this.schema=e,this.plugins=[],this.pluginsByKey=Object.create(null),this.fields=Kf.slice(),t&&t.forEach(r=>{if(this.pluginsByKey[r.key])throw new RangeError("Adding different instances of a keyed plugin ("+r.key+")");this.plugins.push(r),this.pluginsByKey[r.key]=r,r.spec.state&&this.fields.push(new pn(r.key,r.spec.state,r))})}}class je{constructor(e){this.config=e}get schema(){return this.config.schema}get plugins(){return this.config.plugins}apply(e){return this.applyTransaction(e).state}filterTransaction(e,t=-1){for(let r=0;rr.toJSON())),e&&typeof e=="object")for(let r in e){if(r=="doc"||r=="selection")throw new RangeError("The JSON fields `doc` and `selection` are reserved");let i=e[r],s=i.spec.state;s&&s.toJSON&&(t[r]=s.toJSON.call(i,this[i.key]))}return t}static fromJSON(e,t,r){if(!t)throw new RangeError("Invalid input for EditorState.fromJSON");if(!e.schema)throw new RangeError("Required config field 'schema' missing");let i=new Ri(e.schema,e.plugins),s=new je(i);return i.fields.forEach(o=>{if(o.name=="doc")s.doc=At.fromJSON(e.schema,t.doc);else if(o.name=="selection")s.selection=N.fromJSON(s.doc,t.selection);else if(o.name=="storedMarks")t.storedMarks&&(s.storedMarks=t.storedMarks.map(e.schema.markFromJSON));else{if(r)for(let l in r){let a=r[l],c=a.spec.state;if(a.key==o.name&&c&&c.fromJSON&&Object.prototype.hasOwnProperty.call(t,l)){s[o.name]=c.fromJSON.call(a,e,t[l],s);return}}s[o.name]=o.init(e,s)}}),s}}function cc(n,e,t){for(let r in n){let i=n[r];i instanceof Function?i=i.bind(e):r=="handleDOMEvents"&&(i=cc(i,e,{})),t[r]=i}return t}class z{constructor(e){this.spec=e,this.props={},e.props&&cc(e.props,this,this.props),this.key=e.key?e.key.key:uc("plugin")}getState(e){return e[this.key]}}const Di=Object.create(null);function uc(n){return n in Di?n+"$"+ ++Di[n]:(Di[n]=0,n+"$")}class W{constructor(e="key"){this.key=uc(e)}get(e){return e.config.pluginsByKey[this.key]}getState(e){return e[this.key]}}const dc=(n,e)=>n.selection.empty?!1:(e&&e(n.tr.deleteSelection().scrollIntoView()),!0);function fc(n,e){let{$cursor:t}=n.selection;return!t||(e?!e.endOfTextblock("backward",n):t.parentOffset>0)?null:t}const hc=(n,e,t)=>{let r=fc(n,t);if(!r)return!1;let i=Js(r);if(!i){let o=r.blockRange(),l=o&&on(o);return l==null?!1:(e&&e(n.tr.lift(o,l).scrollIntoView()),!0)}let s=i.nodeBefore;if(Cc(n,i,e,-1))return!0;if(r.parent.content.size==0&&(Qt(s,"end")||T.isSelectable(s)))for(let o=r.depth;;o--){let l=di(n.doc,r.before(o),r.after(o),x.empty);if(l&&l.slice.size1)break}return s.isAtom&&i.depth==r.depth-1?(e&&e(n.tr.delete(i.pos-s.nodeSize,i.pos).scrollIntoView()),!0):!1},qf=(n,e,t)=>{let r=fc(n,t);if(!r)return!1;let i=Js(r);return i?pc(n,i,e):!1},Jf=(n,e,t)=>{let r=gc(n,t);if(!r)return!1;let i=Gs(r);return i?pc(n,i,e):!1};function pc(n,e,t){let r=e.nodeBefore,i=r,s=e.pos-1;for(;!i.isTextblock;s--){if(i.type.spec.isolating)return!1;let u=i.lastChild;if(!u)return!1;i=u}let o=e.nodeAfter,l=o,a=e.pos+1;for(;!l.isTextblock;a++){if(l.type.spec.isolating)return!1;let u=l.firstChild;if(!u)return!1;l=u}let c=di(n.doc,s,a,x.empty);if(!c||c.from!=s||c instanceof K&&c.slice.size>=a-s)return!1;if(t){let u=n.tr.step(c);u.setSelection(v.create(u.doc,s)),t(u.scrollIntoView())}return!0}function Qt(n,e,t=!1){for(let r=n;r;r=e=="start"?r.firstChild:r.lastChild){if(r.isTextblock)return!0;if(t&&r.childCount!=1)return!1}return!1}const mc=(n,e,t)=>{let{$head:r,empty:i}=n.selection,s=r;if(!i)return!1;if(r.parent.isTextblock){if(t?!t.endOfTextblock("backward",n):r.parentOffset>0)return!1;s=Js(r)}let o=s&&s.nodeBefore;return!o||!T.isSelectable(o)?!1:(e&&e(n.tr.setSelection(T.create(n.doc,s.pos-o.nodeSize)).scrollIntoView()),!0)};function Js(n){if(!n.parent.type.spec.isolating)for(let e=n.depth-1;e>=0;e--){if(n.index(e)>0)return n.doc.resolve(n.before(e+1));if(n.node(e).type.spec.isolating)break}return null}function gc(n,e){let{$cursor:t}=n.selection;return!t||(e?!e.endOfTextblock("forward",n):t.parentOffset{let r=gc(n,t);if(!r)return!1;let i=Gs(r);if(!i)return!1;let s=i.nodeAfter;if(Cc(n,i,e,1))return!0;if(r.parent.content.size==0&&(Qt(s,"start")||T.isSelectable(s))){let o=di(n.doc,r.before(),r.after(),x.empty);if(o&&o.slice.size{let{$head:r,empty:i}=n.selection,s=r;if(!i)return!1;if(r.parent.isTextblock){if(t?!t.endOfTextblock("forward",n):r.parentOffset=0;e--){let t=n.node(e);if(n.index(e)+1{let t=n.selection,r=t instanceof T,i;if(r){if(t.node.isTextblock||!pt(n.doc,t.from))return!1;i=t.from}else if(i=ui(n.doc,t.from,-1),i==null)return!1;if(e){let s=n.tr.join(i);r&&s.setSelection(T.create(s.doc,i-n.doc.resolve(i).nodeBefore.nodeSize)),e(s.scrollIntoView())}return!0},Yf=(n,e)=>{let t=n.selection,r;if(t instanceof T){if(t.node.isTextblock||!pt(n.doc,t.to))return!1;r=t.to}else if(r=ui(n.doc,t.to,1),r==null)return!1;return e&&e(n.tr.join(r).scrollIntoView()),!0},Xf=(n,e)=>{let{$from:t,$to:r}=n.selection,i=t.blockRange(r),s=i&&on(i);return s==null?!1:(e&&e(n.tr.lift(i,s).scrollIntoView()),!0)},kc=(n,e)=>{let{$head:t,$anchor:r}=n.selection;return!t.parent.type.spec.code||!t.sameParent(r)?!1:(e&&e(n.tr.insertText(` +`).scrollIntoView()),!0)};function Ys(n){for(let e=0;e{let{$head:t,$anchor:r}=n.selection;if(!t.parent.type.spec.code||!t.sameParent(r))return!1;let i=t.node(-1),s=t.indexAfter(-1),o=Ys(i.contentMatchAt(s));if(!o||!i.canReplaceWith(s,s,o))return!1;if(e){let l=t.after(),a=n.tr.replaceWith(l,l,o.createAndFill());a.setSelection(N.near(a.doc.resolve(l),1)),e(a.scrollIntoView())}return!0},wc=(n,e)=>{let t=n.selection,{$from:r,$to:i}=t;if(t instanceof ye||r.parent.inlineContent||i.parent.inlineContent)return!1;let s=Ys(i.parent.contentMatchAt(i.indexAfter()));if(!s||!s.isTextblock)return!1;if(e){let o=(!r.parentOffset&&i.index(){let{$cursor:t}=n.selection;if(!t||t.parent.content.size)return!1;if(t.depth>1&&t.after()!=t.end(-1)){let s=t.before();if(qe(n.doc,s))return e&&e(n.tr.split(s).scrollIntoView()),!0}let r=t.blockRange(),i=r&&on(r);return i==null?!1:(e&&e(n.tr.lift(r,i).scrollIntoView()),!0)};function Zf(n){return(e,t)=>{if(e.selection instanceof T&&e.selection.node.isBlock){let{$from:h}=e.selection;return!h.parentOffset||!qe(e.doc,h.pos)?!1:(t&&t(e.tr.split(h.pos).scrollIntoView()),!0)}if(!e.selection.$from.depth)return!1;let r=e.tr;!e.selection.empty&&(e.selection instanceof v||e.selection instanceof ye)&&r.deleteSelection();let{$from:i}=r.selection,s=r.steps.length,o=[],l,a,c=!1,u=!1;for(let h=i.depth;;h--)if(i.node(h).isBlock){c=i.end(h)==i.pos+(i.depth-h),u=i.start(h)==i.pos-(i.depth-h),a=Ys(i.node(h-1).contentMatchAt(i.indexAfter(h-1))),o.unshift(c&&a?{type:a}:null),l=h;break}else{if(h==1)return!1;o.unshift(null)}let d=i.pos,f=qe(r.doc,d,o.length,o);if(f||(o[0]=a?{type:a}:null,f=qe(r.doc,d,o.length,o)),!f)return!1;if(r.split(d,o.length,o),!c&&u&&i.node(l).type!=a){let h=r.mapping.slice(s),p=h.map(i.before(l)),m=r.doc.resolve(p);a&&i.node(l-1).canReplaceWith(m.index(),m.index()+1,a)&&r.setNodeMarkup(h.map(i.before(l)),a)}return t&&t(r.scrollIntoView()),!0}}const eh=Zf(),th=(n,e)=>{let{$from:t,to:r}=n.selection,i,s=t.sharedDepth(r);return s==0?!1:(i=t.before(s),e&&e(n.tr.setSelection(T.create(n.doc,i))),!0)};function nh(n,e,t){let r=e.nodeBefore,i=e.nodeAfter,s=e.index();return!r||!i||!r.type.compatibleContent(i.type)?!1:!r.content.size&&e.parent.canReplace(s-1,s)?(t&&t(n.tr.delete(e.pos-r.nodeSize,e.pos).scrollIntoView()),!0):!e.parent.canReplace(s,s+1)||!(i.isTextblock||pt(n.doc,e.pos))?!1:(t&&t(n.tr.join(e.pos).scrollIntoView()),!0)}function Cc(n,e,t,r){let i=e.nodeBefore,s=e.nodeAfter,o,l,a=i.type.spec.isolating||s.type.spec.isolating;if(!a&&nh(n,e,t))return!0;let c=!a&&e.parent.canReplace(e.index(),e.index()+1);if(c&&(o=(l=i.contentMatchAt(i.childCount)).findWrapping(s.type))&&l.matchType(o[0]||s.type).validEnd){if(t){let h=e.pos+s.nodeSize,p=b.empty;for(let y=o.length-1;y>=0;y--)p=b.from(o[y].create(null,p));p=b.from(i.copy(p));let m=n.tr.step(new Z(e.pos-1,h,e.pos,h,new x(p,1,0),o.length,!0)),g=m.doc.resolve(h+2*o.length);g.nodeAfter&&g.nodeAfter.type==i.type&&pt(m.doc,g.pos)&&m.join(g.pos),t(m.scrollIntoView())}return!0}let u=s.type.spec.isolating||r>0&&a?null:N.findFrom(e,1),d=u&&u.$from.blockRange(u.$to),f=d&&on(d);if(f!=null&&f>=e.depth)return t&&t(n.tr.lift(d,f).scrollIntoView()),!0;if(c&&Qt(s,"start",!0)&&Qt(i,"end")){let h=i,p=[];for(;p.push(h),!h.isTextblock;)h=h.lastChild;let m=s,g=1;for(;!m.isTextblock;m=m.firstChild)g++;if(h.canReplace(h.childCount,h.childCount,m.content)){if(t){let y=b.empty;for(let w=p.length-1;w>=0;w--)y=b.from(p[w].copy(y));let k=n.tr.step(new Z(e.pos-p.length,e.pos+s.nodeSize,e.pos+g,e.pos+s.nodeSize-g,new x(y,p.length,0),0,!0));t(k.scrollIntoView())}return!0}}return!1}function xc(n){return function(e,t){let r=e.selection,i=n<0?r.$from:r.$to,s=i.depth;for(;i.node(s).isInline;){if(!s)return!1;s--}return i.node(s).isTextblock?(t&&t(e.tr.setSelection(v.create(e.doc,n<0?i.start(s):i.end(s)))),!0):!1}}const rh=xc(-1),ih=xc(1);function sh(n,e=null){return function(t,r){let{$from:i,$to:s}=t.selection,o=i.blockRange(s),l=o&&Us(o,n,e);return l?(r&&r(t.tr.wrap(o,l).scrollIntoView()),!0):!1}}function Yo(n,e=null){return function(t,r){let i=!1;for(let s=0;s{if(i)return!1;if(!(!a.isTextblock||a.hasMarkup(n,e)))if(a.type==n)i=!0;else{let u=t.doc.resolve(c),d=u.index();i=u.parent.canReplaceWith(d,d+1,n)}})}if(!i)return!1;if(r){let s=t.tr;for(let o=0;o=2&&e.$from.node(e.depth-1).type.compatibleContent(t)&&e.startIndex==0){if(e.$from.index(e.depth-1)==0)return!1;let a=o.resolve(e.start-2);s=new Sr(a,a,e.depth),e.endIndex=0;u--)s=b.from(t[u].type.create(t[u].attrs,s));n.step(new Z(e.start-(r?2:0),e.end,e.start,e.end,new x(s,0,0),t.length,!0));let o=0;for(let u=0;uo.childCount>0&&o.firstChild.type==n);return s?t?r.node(s.depth-1).type==n?uh(e,t,n,s):dh(e,t,s):!0:!1}}function uh(n,e,t,r){let i=n.tr,s=r.end,o=r.$to.end(r.depth);sm;p--)h-=i.child(p).nodeSize,r.delete(h-1,h+1);let s=r.doc.resolve(t.start),o=s.nodeAfter;if(r.mapping.map(t.end)!=t.start+s.nodeAfter.nodeSize)return!1;let l=t.startIndex==0,a=t.endIndex==i.childCount,c=s.node(-1),u=s.index(-1);if(!c.canReplace(u+(l?0:1),u+1,o.content.append(a?b.empty:b.from(i))))return!1;let d=s.pos,f=d+o.nodeSize;return r.step(new Z(d-(l?1:0),f+(a?1:0),d+1,f-1,new x((l?b.empty:b.from(i.copy(b.empty))).append(a?b.empty:b.from(i.copy(b.empty))),l?0:1,a?0:1),l?0:1)),e(r.scrollIntoView()),!0}function fh(n){return function(e,t){let{$from:r,$to:i}=e.selection,s=r.blockRange(i,c=>c.childCount>0&&c.firstChild.type==n);if(!s)return!1;let o=s.startIndex;if(o==0)return!1;let l=s.parent,a=l.child(o-1);if(a.type!=n)return!1;if(t){let c=a.lastChild&&a.lastChild.type==l.type,u=b.from(c?n.create():null),d=new x(b.from(n.create(null,b.from(l.type.create(null,u)))),c?3:1,0),f=s.start,h=s.end;t(e.tr.step(new Z(f-(c?3:1),h,f,h,d,1,!0)).scrollIntoView())}return!0}}const re=function(n){for(var e=0;;e++)if(n=n.previousSibling,!n)return e},Zt=function(n){let e=n.assignedSlot||n.parentNode;return e&&e.nodeType==11?e.host:e};let cs=null;const We=function(n,e,t){let r=cs||(cs=document.createRange());return r.setEnd(n,t??n.nodeValue.length),r.setStart(n,e||0),r},hh=function(){cs=null},Lt=function(n,e,t,r){return t&&(Xo(n,e,t,r,-1)||Xo(n,e,t,r,1))},ph=/^(img|br|input|textarea|hr)$/i;function Xo(n,e,t,r,i){for(var s;;){if(n==t&&e==r)return!0;if(e==(i<0?0:le(n))){let o=n.parentNode;if(!o||!A(o)||_n(n)||ph.test(n.nodeName)||n.contentEditable=="false")return!1;e=re(n)+(i<0?0:1),n=o}else if(A(n)){let o=n.childNodes[e+(i<0?-1:0)];if(A(o)&&o.contentEditable=="false")if(!((s=o.pmViewDesc)===null||s===void 0)&&s.ignoreForSelection)e+=i;else return!1;else n=o,e=i<0?le(n):0}else return!1}}function le(n){return n.nodeType==3?n.nodeValue.length:n.childNodes.length}function A(n){return n.nodeType==1}function Y(n){return n.nodeType==3}function Pt(n,e){return e?n.contains(A(e)?e:e.parentNode):!1}function mh(n,e){for(;;){if(Y(n)&&e)return n;if(A(n)&&e>0){if(n.contentEditable=="false")return null;n=n.childNodes[e-1],e=le(n)}else if(n.parentNode&&!_n(n))e=re(n),n=n.parentNode;else return null}}function gh(n,e){for(;;){if(Y(n)&&e2),Ce=en||(Ie?/Mac/.test(Ie.platform):!1),Tc=Ie?/Win/.test(Ie.platform):!1,_e=/Android \d/.test(mt),pi=!!Qo&&"webkitFontSmoothing"in Qo.documentElement.style,wh=pi?+(/\bAppleWebKit\/(\d+)/.exec(navigator.userAgent)||[0,0])[1]:0;function Sh(n){let e=n.defaultView&&n.defaultView.visualViewport;return e?{left:0,right:e.width,top:0,bottom:e.height}:{left:0,right:n.documentElement.clientWidth,top:0,bottom:n.documentElement.clientHeight}}function ze(n,e){return typeof n=="number"?n:n[e]}function Ch(n){let e=n.getBoundingClientRect(),t=e.width/n.offsetWidth||1,r=e.height/n.offsetHeight||1;return{left:e.left,right:e.left+n.clientWidth*t,top:e.top,bottom:e.top+n.clientHeight*r}}function Zo(n,e,t){if(!hs(e)&&e.left==0)return;let r=n.someProp("scrollThreshold")||0,i=n.someProp("scrollMargin")||5,s=n.dom.ownerDocument;for(let o=t||n.dom;o;){if(!A(o)){o=Zt(o);continue}let l=o==s.body,a=l?Sh(s):Ch(o),c=0,u=0;if(e.topa.bottom-ze(r,"bottom")&&(u=e.bottom-e.top>a.bottom-a.top?e.top+ze(i,"top")-a.top:e.bottom-a.bottom+ze(i,"bottom")),e.lefta.right-ze(r,"right")&&(c=e.right-a.right+ze(i,"right")),c||u)if(l)s.defaultView.scrollBy(c,u);else{let f=o.scrollLeft,h=o.scrollTop;u&&(o.scrollTop+=u),c&&(o.scrollLeft+=c);let p=o.scrollLeft-f,m=o.scrollTop-h;e={left:e.left-p,top:e.top-m,right:e.right-p,bottom:e.bottom-m}}let d=l?"fixed":getComputedStyle(o).position;if(/^(fixed|sticky)$/.test(d))break;o=d=="absolute"?o.offsetParent:Zt(o)}}function xh(n){let e=n.dom.getBoundingClientRect(),t=Math.max(0,e.top),r,i;for(let s=(e.left+e.right)/2,o=t+1;o=t-20){r=l,i=a.top;break}}return{refDOM:r,refTop:i,stack:Ec(n.dom)}}function Ec(n){let e=[],t=n.ownerDocument;for(let r=n;r&&(e.push({dom:r,top:r.scrollTop,left:r.scrollLeft}),n!=t);r=Zt(r));return e}function vh({refDOM:n,refTop:e,stack:t}){let r=n?n.getBoundingClientRect().top:0;Ac(t,r==0?0:r-e)}function Ac(n,e){for(let t=0;t=l){o=Math.max(p.bottom,o),l=Math.min(p.top,l);let m=p.left>e.left?p.left-e.left:p.right=(p.left+p.right)/2?1:0));continue}}else p.top>e.top&&!a&&p.left<=e.left&&p.right>=e.left&&(a=u,c={left:Math.max(p.left,Math.min(p.right,e.left)),top:p.top});!t&&(e.left>=p.right&&e.top>=p.top||e.left>=p.left&&e.top>=p.bottom)&&(s=d+1)}}return!t&&a&&(t=a,i=c,r=0),t&&Y(t)?Th(t,i):!t||r?{node:n,offset:s}:Nc(t,i)}function Th(n,e){let t=n.nodeValue.length,r=document.createRange(),i;for(let s=0;s=(o.left+o.right)/2?1:0)};break}}return r.detach(),i||{node:n,offset:0}}function Qs(n,e){return n.left>=e.left-1&&n.left<=e.right+1&&n.top>=e.top-1&&n.top<=e.bottom+1}function Eh(n,e){let t=n.parentNode;return t&&/^li$/i.test(t.nodeName)&&e.left(o.left+o.right)/2?1:-1}return n.docView.posFromDOM(r,i,s)}function Nh(n,e,t,r){let i=-1;for(let s=e,o=!1;s!=n.dom;){let l=n.docView.nearestDesc(s,!0),a;if(!l)return null;if(A(l.dom)&&(l.node.isBlock&&l.parent||!l.contentDOM)&&((a=l.dom.getBoundingClientRect()).width||a.height)&&(l.node.isBlock&&l.parent&&!/^T(R|BODY|HEAD|FOOT)$/.test(l.dom.nodeName)&&(!o&&a.left>r.left||a.top>r.top?i=l.posBefore:(!o&&a.right-1?i:n.docView.posFromDOM(e,t,-1)}function Oc(n,e,t){let r=n.childNodes.length;if(r&&t.tope.top&&i++}let c;pi&&i&&A(r)&&A(c=r.childNodes[i-1])&&c.contentEditable=="false"&&c.getBoundingClientRect().top>=e.top&&i--,r==n.dom&&i==r.childNodes.length-1&&A(r.lastChild)&&e.top>r.lastChild.getBoundingClientRect().bottom?l=n.state.doc.content.size:(i==0||!A(r)||r.childNodes[i-1].nodeName!="BR")&&(l=Nh(n,r,i,e))}l==null&&(l=Ah(n,o,e));let a=n.docView.nearestDesc(o,!0);return{pos:l,inside:a?a.posAtStart-a.border:-1}}function hs(n){return n.top=0&&i==r.nodeValue.length?(a--,u=1):t<0?a--:c++,ln(Qe(We(r,a,c),u),u<0)}if(!n.state.doc.resolve(e-(s||0)).parent.inlineContent){if(s==null&&i&&(t<0||i==le(r))){let a=r.childNodes[i-1];if(A(a))return Ii(a.getBoundingClientRect(),!1)}if(s==null&&i=0)}if(s==null&&i&&(t<0||i==le(r))){let a=r.childNodes[i-1],c=Y(a)?We(a,le(a)-(o?0:1)):A(a)&&(a.nodeName!="BR"||!a.nextSibling)?a:null;if(c)return ln(Qe(c,1),!1)}if(s==null&&i=0)}function ln(n,e){if(n.width==0)return n;let t=e?n.left:n.right;return{top:n.top,bottom:n.bottom,left:t,right:t}}function Ii(n,e){if(n.height==0)return n;let t=e?n.top:n.bottom;return{top:t,bottom:t,left:n.left,right:n.right}}function Dc(n,e,t){let r=n.state,i=n.root.activeElement;r!=e&&n.updateState(e),i!=n.dom&&n.focus();try{return t()}finally{r!=e&&n.updateState(r),i!=n.dom&&i&&i.focus()}}function Dh(n,e,t){let r=e.selection,i=t=="up"?r.$from:r.$to;return Dc(n,e,()=>{let{node:s}=n.docView.domFromPos(i.pos,t=="up"?-1:1);for(;;){let l=n.docView.nearestDesc(s,!0);if(!l)break;if(l.node.isBlock){s=l.contentDOM||l.dom;break}s=l.dom.parentNode}let o=Rc(n,i.pos,1);for(let l=s.firstChild;l;l=l.nextSibling){let a;if(A(l))a=l.getClientRects();else if(Y(l))a=We(l,0,l.nodeValue.length).getClientRects();else continue;for(let c=0;cu.top+1&&(t=="up"?o.top-u.top>(u.bottom-o.top)*2:u.bottom-o.bottom>(o.bottom-u.top)*2))return!1}}return!0})}const Ih=/[\u0590-\u08ac]/;function Lh(n,e,t){let{$head:r}=e.selection;if(!r.parent.isTextblock)return!1;let i=r.parentOffset,s=!i,o=i==r.parent.content.size,l=n.domSelection();return l?!Ih.test(r.parent.textContent)||!l.modify?t=="left"||t=="backward"?s:o:Dc(n,e,()=>{let{focusNode:a,focusOffset:c,anchorNode:u,anchorOffset:d}=n.domSelectionRange(),f=l.caretBidiLevel;l.modify("move",t,"character");let h=r.depth?n.docView.domAfterPos(r.before()):n.dom,{focusNode:p,focusOffset:m}=n.domSelectionRange(),g=p&&!Pt(h,p)||a==p&&c==m;try{l.collapse(u,d),a&&(a!=u||c!=d)&&l.extend&&l.extend(a,c)}catch{}return f!=null&&(l.caretBidiLevel=f),g}):r.pos==r.start()||r.pos==r.end()}let el=null,tl=null,nl=!1;function Ph(n,e,t){return el==e&&tl==t?nl:(el=e,tl=t,nl=t=="up"||t=="down"?Dh(n,e,t):Lh(n,e,t))}const xe=0,rl=1,wt=2,Ae=3;class Un{constructor(e,t,r,i){this.parent=e,this.children=t,this.dom=r,this.contentDOM=i,this.dirty=xe,r.pmViewDesc=this}matchesWidget(e){return!1}matchesMark(e){return!1}matchesNode(e,t,r){return!1}matchesHack(e){return!1}parseRule(e){return null}stopEvent(e){return!1}get size(){let e=0;for(let t=0;tre(this.contentDOM);else if(this.contentDOM&&this.contentDOM!=this.dom&&this.dom.contains(this.contentDOM))i=!!(e.compareDocumentPosition(this.contentDOM)&4);else if(this.dom.firstChild){if(t==0)for(let s=e;;s=s.parentNode){if(s==this.dom){i=!1;break}if(s.previousSibling)break}if(i==null&&t==e.childNodes.length)for(let s=e;;s=s.parentNode){if(s==this.dom){i=!0;break}if(s.nextSibling)break}}return i??r>0?this.posAtEnd:this.posAtStart}nearestDesc(e,t=!1){for(let r=!0,i=e;i;i=i.parentNode){let s=this.getDesc(i),o;if(s&&(!t||s.node))if(r&&(o=s.nodeDOM)&&!(A(o)?Pt(o,e):o==e))r=!1;else return s}}getDesc(e){let t=e.pmViewDesc;for(let r=t;r;r=r.parent)if(r==this)return t}posFromDOM(e,t,r){for(let i=e;i;i=i.parentNode){let s=this.getDesc(i);if(s)return s.localPosFromDOM(e,t,r)}return-1}descAt(e){for(let t=0,r=0;te){i=e-s;break}s=l}if(i)return this.children[r].domFromPos(i-this.children[r].border,t);for(;r>0;r--){let s=this.children[r-1];if(s.size||!(s instanceof Lc||s instanceof Ic&&s.side>=0))break}if(t<=0){let s,o=!0;for(;s=r?this.children[r-1]:null,!(!s||s.dom.parentNode==this.contentDOM);r--,o=!1);return s&&t&&o&&!s.border&&!s.domAtom?s.domFromPos(s.size,t):{node:this.contentDOM,offset:s?re(s.dom)+1:0}}else{let s,o=!0;for(;s=r=u&&t<=c-a.border&&a.node&&a.contentDOM&&this.contentDOM.contains(a.contentDOM))return a.parseRange(e,t,u);e=o;for(let d=l;d>0;d--){let f=this.children[d-1];if(f.size&&f.dom.parentNode==this.contentDOM&&!f.emptyChildAt(1)){i=re(f.dom)+1;break}e-=f.size}i==-1&&(i=0)}if(i>-1&&(c>t||l==this.children.length-1)){t=c;for(let u=l+1;up&&ot){let p=l;l=a,a=p}let h=document.createRange();h.setEnd(a.node,a.offset),h.setStart(l.node,l.offset),c.removeAllRanges(),c.addRange(h)}}ignoreMutation(e){return!this.contentDOM&&e.type!="selection"}get contentLost(){return this.contentDOM&&this.contentDOM!=this.dom&&!this.dom.contains(this.contentDOM)}markDirty(e,t){for(let r=0,i=0;i=r:er){let l=r+s.border,a=o-s.border;if(e>=l&&t<=a){this.dirty=e==r||t==o?wt:rl,e==l&&t==a&&(s.contentLost||s.dom.parentNode!=this.contentDOM)?s.dirty=Ae:s.markDirty(e-l,t-l);return}else s.dirty=s.dom==s.contentDOM&&s.dom.parentNode==this.contentDOM&&!s.children.length?wt:Ae}r=o}this.dirty=wt}markParentsDirty(){let e=1;for(let t=this.parent;t;t=t.parent,e++){let r=e==1?wt:rl;t.dirty{if(!s)return i;if(s.parent)return s.parent.posBeforeChild(s)})),!t.type.spec.raw){let l=A(o)?o:document.createElement("span");l!=o&&l.appendChild(o),l.hasAttribute("contenteditable")||(l.contentEditable="false"),l.classList.add("ProseMirror-widget")}super(e,[],o,null),this.widget=t,this.widget=t,s=this}matchesWidget(e){return this.dirty==xe&&e.type.eq(this.widget.type)}parseRule(){return{ignore:!0}}stopEvent(e){let t=this.widget.spec.stopEvent;return t?t(e):!1}ignoreMutation(e){return e.type!="selection"||this.widget.spec.ignoreSelection}destroy(){this.widget.type.destroy(this.dom),super.destroy()}get domAtom(){return!0}get ignoreForSelection(){return!!this.widget.type.spec.relaxedSide}get side(){return this.widget.type.side}}class zh extends Un{constructor(e,t,r,i){super(e,[],t,null),this.textDOM=r,this.text=i}get size(){return this.text.length}localPosFromDOM(e,t){return e!=this.textDOM?this.posAtStart+(t?this.size:0):this.posAtStart+t}domFromPos(e){return{node:this.textDOM,offset:e}}ignoreMutation(e){return e.type==="characterData"&&e.target.nodeValue==e.oldValue}}class lt extends Un{constructor(e,t,r,i,s){super(e,[],r,i),this.mark=t,this.spec=s}static create(e,t,r,i){let s=i.nodeViews[t.type.name],o=s&&s(t,i,r);return(!o||!o.dom)&&(o=ht.renderSpec(document,t.type.spec.toDOM(t,r),null,t.attrs)),new lt(e,t,o.dom,o.contentDOM||o.dom,o)}parseRule(){return this.dirty&Ae||this.mark.type.spec.reparseInView?null:{mark:this.mark.type.name,attrs:this.mark.attrs,contentElement:this.contentDOM}}matchesMark(e){return this.dirty!=Ae&&this.mark.eq(e)}markDirty(e,t){if(super.markDirty(e,t),this.dirty!=xe){let r=this.parent;for(;!r.node;)r=r.parent;r.dirty0&&(s=ms(s,0,e,r));for(let l=0;l{if(!a)return o;if(a.parent)return a.parent.posBeforeChild(a)},r,i),u=c&&c.dom,d=c&&c.contentDOM;if(t.isText){if(!u)u=document.createTextNode(t.text);else if(!Y(u))throw new RangeError("Text must be rendered as a DOM text node")}else u||({dom:u,contentDOM:d}=ht.renderSpec(document,t.type.spec.toDOM(t),null,t.attrs));!d&&!t.isText&&u.nodeName!="BR"&&(u.hasAttribute("contenteditable")||(u.contentEditable="false"),t.type.spec.draggable&&(u.draggable=!0));let f=u;return u=Bc(u,r,t),c?a=new Bh(e,t,r,i,u,d||null,f,c):t.isText?new mi(e,t,r,i,u,f):new at(e,t,r,i,u,d||null,f)}parseRule(e){if(this.node.type.spec.reparseInView)return null;let t={node:this.node.type.name,attrs:this.node.attrs};if(this.node.type.whitespace=="pre"&&(t.preserveWhitespace="full"),!this.contentDOM)t.getContent=()=>this.node.content;else if(!this.contentLost)t.contentElement=this.contentDOM;else{for(let r=this.children.length-1;r>=0;r--){let i=this.children[r];if(this.dom.contains(i.dom.parentNode)){t.contentElement=i.dom.parentNode;break}}if(!t.contentElement){let r=e&&e.find(i=>A(i)&&e.indexOf(i.parentNode)<0&&this.dom.contains(i));r?t.contentElement=r:t.getContent=()=>b.empty}}return t}matchesNode(e,t,r){return this.dirty==xe&&e.eq(this.node)&&xr(t,this.outerDeco)&&r.eq(this.innerDeco)}get size(){return this.node.nodeSize}get border(){return this.node.isLeaf?0:1}updateChildren(e,t){let r=this.node.inlineContent,i=t,s=e.composing?this.localCompositionInfo(e,t):null,o=s&&s.pos>-1?s:null,l=s&&s.pos<0,a=new Hh(this,o&&o.node,e),c=this.node.inlineContent,u=c&&this.node.isBlock;Wh(this.node,this.innerDeco,(d,f,h)=>{d.spec.marks?a.syncToMarks(d.spec.marks,r,e,f):d.type.side>=0&&!h&&a.syncToMarks(f==this.node.childCount?$.none:this.node.child(f).marks,r,e,f),a.placeWidget(d,e,i)},(d,f,h,p)=>{a.syncToMarks(d.marks,r,e,p),u&&d.isAtom&&!d.isText&&a.addHackNode("IMG",a.top);let m;a.findNodeMatch(d,f,h,p)||l&&e.state.selection.from>i&&e.state.selection.to-1&&a.updateNodeAt(d,f,h,m,e)||a.updateNextNode(d,f,h,e,p,i)||a.addNode(d,f,h,e,i),i+=d.nodeSize,c&&(u=d.isAtom&&!d.isText)}),a.syncToMarks([],r,e,0),this.node.isTextblock&&a.addTextblockHacks(),a.destroyRest(),(a.changed||this.dirty==wt)&&(o&&this.protectLocalComposition(e,o),Pc(this.contentDOM,this.children,e),en&&jh(this.dom))}localCompositionInfo(e,t){let{from:r,to:i}=e.state.selection;if(!(e.state.selection instanceof v)||rt+this.node.content.size)return null;let s=e.input.compositionNode;if(!s||!this.dom.contains(s.parentNode))return null;if(this.node.inlineContent){let o=s.nodeValue,l=_h(this.node.content,o,r-t,i-t);return l<0?null:{node:s,pos:l,text:o}}else return{node:s,pos:-1,text:""}}protectLocalComposition(e,{node:t,pos:r,text:i}){if(this.getDesc(t))return;let s=t;for(;s.parentNode!=this.contentDOM;s=s.parentNode){for(;s.previousSibling;)s.parentNode.removeChild(s.previousSibling);for(;s.nextSibling;)s.parentNode.removeChild(s.nextSibling);s.pmViewDesc&&(s.pmViewDesc=void 0)}let o=new zh(this,s,t,i);e.input.compositionNodes.push(o),this.children=ms(this.children,r,r+i.length,e,o)}update(e,t,r,i){return this.dirty==Ae||!e.sameMarkup(this.node)?!1:(this.updateInner(e,t,r,i),!0)}updateInner(e,t,r,i){this.updateOuterDeco(t),this.node=e,this.innerDeco=r,this.contentDOM&&this.updateChildren(i,this.posAtStart),this.dirty=xe}updateOuterDeco(e){if(xr(e,this.outerDeco))return;let t=!A(this.nodeDOM),r=this.dom;this.dom=zc(this.dom,this.nodeDOM,ps(this.outerDeco,this.node,t),ps(e,this.node,t)),this.dom!=r&&(r.pmViewDesc=void 0,this.dom.pmViewDesc=this),this.outerDeco=e}selectNode(){A(this.nodeDOM)&&(this.nodeDOM.classList.add("ProseMirror-selectednode"),(this.contentDOM||!this.node.type.spec.draggable)&&(this.nodeDOM.draggable=!0))}deselectNode(){A(this.nodeDOM)&&(this.nodeDOM.classList.remove("ProseMirror-selectednode"),(this.contentDOM||!this.node.type.spec.draggable)&&this.nodeDOM.removeAttribute("draggable"))}get domAtom(){return this.node.isAtom}}function il(n,e,t,r,i){Bc(r,e,n);let s=new at(void 0,n,e,t,r,r,r);return s.contentDOM&&s.updateChildren(i,0),s}class mi extends at{constructor(e,t,r,i,s,o){super(e,t,r,i,s,null,o)}parseRule(){let e=this.nodeDOM.parentNode;for(;e&&e!=this.dom&&!e.pmIsDeco;)e=e.parentNode;return{skip:e||!0}}update(e,t,r,i){return this.dirty==Ae||this.dirty!=xe&&!this.inParent()||!e.sameMarkup(this.node)?!1:(this.updateOuterDeco(t),(this.dirty!=xe||e.text!=this.node.text)&&e.text!=this.nodeDOM.nodeValue&&(this.nodeDOM.nodeValue=e.text,i.trackWrites==this.nodeDOM&&(i.trackWrites=null)),this.node=e,this.dirty=xe,!0)}inParent(){let e=this.parent.contentDOM;for(let t=this.nodeDOM;t;t=t.parentNode)if(t==e)return!0;return!1}domFromPos(e){return{node:this.nodeDOM,offset:e}}localPosFromDOM(e,t,r){return e==this.nodeDOM?this.posAtStart+Math.min(t,this.node.text.length):super.localPosFromDOM(e,t,r)}ignoreMutation(e){return e.type!="characterData"&&e.type!="selection"}slice(e,t,r){let i=this.node.cut(e,t),s=document.createTextNode(i.text);return new mi(this.parent,i,this.outerDeco,this.innerDeco,s,s)}markDirty(e,t){super.markDirty(e,t),this.dom!=this.nodeDOM&&(e==0||t==this.nodeDOM.nodeValue.length)&&(this.dirty=Ae)}get domAtom(){return!1}isText(e){return this.node.text==e}}class Lc extends Un{parseRule(){return{ignore:!0}}matchesHack(e){return this.dirty==xe&&this.dom.nodeName==e}get domAtom(){return!0}get ignoreForCoords(){return this.dom.nodeName=="IMG"}}class Bh extends at{constructor(e,t,r,i,s,o,l,a){super(e,t,r,i,s,o,l),this.spec=a}update(e,t,r,i){if(this.dirty==Ae)return!1;if(this.spec.update&&(this.node.type==e.type||this.spec.multiType)){let s=this.spec.update(e,t,r);return s&&this.updateInner(e,t,r,i),s}else return!this.contentDOM&&!e.isLeaf?!1:super.update(e,t,r,i)}selectNode(){this.spec.selectNode?this.spec.selectNode():super.selectNode()}deselectNode(){this.spec.deselectNode?this.spec.deselectNode():super.deselectNode()}setSelection(e,t,r,i){this.spec.setSelection?this.spec.setSelection(e,t,r.root):super.setSelection(e,t,r,i)}destroy(){this.spec.destroy&&this.spec.destroy(),super.destroy()}stopEvent(e){return this.spec.stopEvent?this.spec.stopEvent(e):!1}ignoreMutation(e){return this.spec.ignoreMutation?this.spec.ignoreMutation(e):super.ignoreMutation(e)}}function Pc(n,e,t){let r=n.firstChild,i=!1;for(let s=0;s>1,l=Math.min(o,e.length);for(;s-1)a>this.index&&(this.changed=!0,this.destroyBetween(this.index,a)),this.top=this.top.children[this.index];else{let u=lt.create(this.top,e[o],t,r);this.top.children.splice(this.index,0,u),this.top=u,this.changed=!0}this.index=0,o++}}findNodeMatch(e,t,r,i){let s=-1,o;if(i>=this.preMatch.index&&(o=this.preMatch.matches[i-this.preMatch.index]).parent==this.top&&o.matchesNode(e,t,r))s=this.top.children.indexOf(o,this.index);else for(let l=this.index,a=Math.min(this.top.children.length,l+5);l0;){let l;for(;;)if(r){let c=t.children[r-1];if(c instanceof lt)t=c,r=c.children.length;else{l=c,r--;break}}else{if(t==e)break e;r=t.parent.children.indexOf(t),t=t.parent}let a=l.node;if(a){if(a!=n.child(i-1))break;--i,s.set(l,i),o.push(l)}}return{index:i,matched:s,matches:o.reverse()}}function Vh(n,e){return n.type.side-e.type.side}function Wh(n,e,t,r){let i=e.locals(n),s=0;if(i.length==0){for(let c=0;cs;)l.push(i[o++]);let p=s+f.nodeSize;if(f.isText){let g=p;o!g.inline):l.slice();r(f,m,e.forChild(s,f),h),s=p}}function jh(n){if(n.nodeName=="UL"||n.nodeName=="OL"){let e=n.style.cssText;n.style.cssText=e+"; list-style: square !important",window.getComputedStyle(n).listStyle,n.style.cssText=e}}function _h(n,e,t,r){for(let i=0,s=0;i=t){if(s>=r&&a.slice(r-e.length-l,r-l)==e)return r-e.length;let c=l=0&&c+e.length+l>=t)return l+c;if(t==r&&a.length>=r+e.length-l&&a.slice(r-l,r-l+e.length)==e)return r}}return-1}function ms(n,e,t,r,i){let s=[];for(let o=0,l=0;o=t||u<=e?s.push(a):(ct&&s.push(a.slice(t-c,a.size,r)))}return s}function Zs(n,e=null){let t=n.domSelectionRange(),r=n.state.doc;if(!t.focusNode)return null;let i=n.docView.nearestDesc(t.focusNode),s=i&&i.size==0,o=n.docView.posFromDOM(t.focusNode,t.focusOffset,1);if(o<0)return null;let l=r.resolve(o),a,c;if(hi(t)){for(a=o;i&&!i.node;)i=i.parent;if(i&&i.node.isAtom&&T.isSelectable(i.node)&&i.parent&&!(i.node.isInline&&yh(t.focusNode,t.focusOffset,i.dom))){let d=i.posBefore;c=new T(o==d?l:r.resolve(d))}else if(be&&e=="key"&&o>n.state.selection.to&&A(t.focusNode)&&t.focusOffset==t.focusNode.childNodes.length&&i&&i.posAtStart>n.state.selection.to)for(let d=t.focusNode;;d=d.parentNode){if(getComputedStyle(d).overflow!="visible"){c=N.findFrom(r.resolve(i.posAtStart),1);break}if(d==i.dom||d.nextSibling||!d.parentNode||!A(d.parentNode))break}}else{if(t instanceof n.dom.ownerDocument.defaultView.Selection&&t.rangeCount>1){let d=o,f=o;for(let h=0;h{(t.anchorNode!=r||t.anchorOffset!=i)&&(e.removeEventListener("selectionchange",n.input.hideSelectionGuard),setTimeout(()=>{(!$c(n)||n.state.selection.visible)&&n.dom.classList.remove("ProseMirror-hideselection")},20))})}function Kh(n){let e=n.domSelection();if(!e)return;let t=n.cursorWrapper.dom,r=t.nodeName=="IMG";r?e.collapse(t.parentNode,re(t)+1):e.collapse(t,0),!r&&!n.state.selection.visible&&pe&&ot<=11&&(t.disabled=!0,t.disabled=!1)}function Hc(n,e){if(e instanceof T){let t=n.docView.descAt(e.from);t!=n.lastSelectedViewDesc&&(cl(n),t&&t.selectNode(),n.lastSelectedViewDesc=t)}else cl(n)}function cl(n){n.lastSelectedViewDesc&&(n.lastSelectedViewDesc.parent&&n.lastSelectedViewDesc.deselectNode(),n.lastSelectedViewDesc=void 0)}function eo(n,e,t,r){return n.someProp("createSelectionBetween",i=>i(n,e,t))||v.between(e,t,r)}function ul(n){return n.editable&&!n.hasFocus()?!1:Fc(n)}function Fc(n){let e=n.domSelectionRange();if(!e.anchorNode)return!1;try{return Pt(n.dom,e.anchorNode)&&(n.editable||Pt(n.dom,e.focusNode))}catch{return!1}}function qh(n){let e=n.docView.domFromPos(n.state.selection.anchor,0),t=n.domSelectionRange();return Lt(e.node,e.offset,t.anchorNode,t.anchorOffset)}function gs(n,e){let{$anchor:t,$head:r}=n.selection,i=e>0?t.max(r):t.min(r),s=i.parent.inlineContent?i.depth?n.doc.resolve(e>0?i.after():i.before()):null:i;return s&&N.findFrom(s,e)}function Ze(n,e){return n.dispatch(n.state.tr.setSelection(e).scrollIntoView()),!0}function dl(n,e,t){let r=n.state.selection;if(r instanceof v)if(t.indexOf("s")>-1){let{$head:i}=r,s=i.textOffset?null:e<0?i.nodeBefore:i.nodeAfter;if(!s||s.isText||!s.isLeaf)return!1;let o=n.state.doc.resolve(i.pos+s.nodeSize*(e<0?-1:1));return Ze(n,new v(r.$anchor,o))}else if(r.empty){if(n.endOfTextblock(e>0?"forward":"backward")){let i=gs(n.state,e);return i&&i instanceof T?Ze(n,i):!1}else if(!(Ce&&t.indexOf("m")>-1)){let i=r.$head,s=i.textOffset?null:e<0?i.nodeBefore:i.nodeAfter,o;if(!s||s.isText)return!1;let l=e<0?i.pos-s.nodeSize:i.pos;return s.isAtom||(o=n.docView.descAt(l))&&!o.contentDOM?T.isSelectable(s)?Ze(n,new T(e<0?n.state.doc.resolve(i.pos-s.nodeSize):i)):Ze(n,new v(n.state.doc.resolve(e<0?l:l+s.nodeSize))):!1}}else return!1;else{if(r instanceof T&&r.node.isInline)return Ze(n,new v(e>0?r.$to:r.$from));{let i=gs(n.state,e);return i?Ze(n,i):!1}}}function wn(n,e){let t=n.pmViewDesc;return t?t.size==0&&(e<0||n.nextSibling||n.nodeName!="BR"):A(n)&&n.contentEditable=="false"}function Vt(n,e){return e<0?Jh(n):Gh(n)}function Jh(n){let e=n.domSelectionRange(),t=e.focusNode,r=e.focusOffset;if(!t)return;let i,s,o=!1;for(be&&A(t)&&r0){if(!A(t))break;let l=t.childNodes[r-1];if(wn(l,-1))i=t,s=--r;else if(Y(l))t=l,r=t.nodeValue.length;else break}else{if(Vc(t))break;{let l=t.previousSibling;for(;l&&wn(l,-1);)i=t.parentNode,s=re(l),l=l.previousSibling;if(l)t=l,r=le(t);else{if(t=t.parentNode,t==n.dom)break;r=0}}}o?ys(n,t,r):i&&ys(n,i,s)}function Gh(n){let e=n.domSelectionRange(),t=e.focusNode,r=e.focusOffset;if(!t)return;let i=le(t),s,o;for(;;)if(r{n.state==i&&Je(n)},50)}function fl(n,e){let t=n.state.doc.resolve(e);if(!(se||Tc)&&t.parent.inlineContent){let i=n.coordsAtPos(e);if(e>t.start()){let s=n.coordsAtPos(e-1),o=(s.top+s.bottom)/2;if(o>i.top&&o1)return s.lefti.top&&o1)return s.left>i.left?"ltr":"rtl"}}return getComputedStyle(n.dom).direction=="rtl"?"rtl":"ltr"}function hl(n,e,t){let r=n.state.selection;if(r instanceof v&&!r.empty||t.indexOf("s")>-1||Ce&&t.indexOf("m")>-1)return!1;let{$from:i,$to:s}=r;if(!i.parent.inlineContent||n.endOfTextblock(e<0?"up":"down")){let o=gs(n.state,e);if(o&&o instanceof T)return Ze(n,o)}if(!i.parent.inlineContent){let o=e<0?i:s,l=r instanceof ye?N.near(o,e):N.findFrom(o,e);return l?Ze(n,l):!1}return!1}function pl(n,e){if(!(n.state.selection instanceof v))return!0;let{$head:t,$anchor:r,empty:i}=n.state.selection;if(!t.sameParent(r))return!0;if(!i)return!1;if(n.endOfTextblock(e>0?"forward":"backward"))return!0;let s=!t.textOffset&&(e<0?t.nodeBefore:t.nodeAfter);if(s&&!s.isText){let o=n.state.tr;return e<0?o.delete(t.pos-s.nodeSize,t.pos):o.delete(t.pos,t.pos+s.nodeSize),n.dispatch(o),!0}return!1}function ml(n,e,t){n.domObserver.stop(),e.contentEditable=t,n.domObserver.start()}function Qh(n){if(!ae||n.state.selection.$head.parentOffset>0)return!1;let{focusNode:e,focusOffset:t}=n.domSelectionRange();if(e&&A(e)&&t==0&&e.firstChild&&A(e.firstChild)&&e.firstChild.contentEditable=="false"){let r=e.firstChild;ml(n,r,"true"),setTimeout(()=>ml(n,r,"false"),20)}return!1}function Zh(n){let e="";return n.ctrlKey&&(e+="c"),n.metaKey&&(e+="m"),n.altKey&&(e+="a"),n.shiftKey&&(e+="s"),e}function ep(n,e){let t=e.keyCode,r=Zh(e);if(t==8||Ce&&t==72&&r=="c")return pl(n,-1)||Vt(n,-1);if(t==46&&!e.shiftKey||Ce&&t==68&&r=="c")return pl(n,1)||Vt(n,1);if(t==13||t==27)return!0;if(t==37||Ce&&t==66&&r=="c"){let i=t==37?fl(n,n.state.selection.from)=="ltr"?-1:1:-1;return dl(n,i,r)||Vt(n,i)}else if(t==39||Ce&&t==70&&r=="c"){let i=t==39?fl(n,n.state.selection.from)=="ltr"?1:-1:1;return dl(n,i,r)||Vt(n,i)}else{if(t==38||Ce&&t==80&&r=="c")return hl(n,-1,r)||Vt(n,-1);if(t==40||Ce&&t==78&&r=="c")return Qh(n)||hl(n,1,r)||Vt(n,1);if(r==(Ce?"m":"c")&&(t==66||t==73||t==89||t==90))return!0}return!1}function to(n,e){n.someProp("transformCopied",h=>{e=h(e,n)});let t=[],{content:r,openStart:i,openEnd:s}=e;for(;i>1&&s>1&&r.childCount==1&&r.firstChild.childCount==1;){i--,s--;let h=r.firstChild;t.push(h.type.name,h.attrs!=h.type.defaultAttrs?h.attrs:null),r=h.content}let o=n.someProp("clipboardSerializer")||ht.fromSchema(n.state.schema),l=qc(),a=l.createElement("div");a.appendChild(o.serializeFragment(r,{document:l}));let c=a.firstChild,u,d=0;for(;c&&A(c)&&(u=Kc[c.nodeName.toLowerCase()]);){for(let h=u.length-1;h>=0;h--){let p=l.createElement(u[h]);for(;a.firstChild;)p.appendChild(a.firstChild);a.appendChild(p),d++}c=a.firstChild}c&&A(c)&&c.setAttribute("data-pm-slice",`${i} ${s}${d?` -${d}`:""} ${JSON.stringify(t)}`);let f=n.someProp("clipboardTextSerializer",h=>h(e,n))||e.content.textBetween(0,e.content.size,` -`);return{dom:a,text:f,slice:e}}function Ba(n,e,t,r,i){let s=i.parent.type.spec.code,o,l;if(!t&&!e)return null;let a=!!e&&(r||s||!t);if(a){if(n.someProp("transformPastedText",f=>{e=f(e,s||r,n)}),s)return l=new w(b.from(n.state.schema.text(e.replace(/\r\n?/g,` -`))),0,0),n.someProp("transformPasted",f=>{l=f(l,n,!0)}),l;let d=n.someProp("clipboardTextParser",f=>f(e,i,r,n));if(d)l=d;else{let f=i.marks(),{schema:h}=n.state,p=st.fromSchema(h);o=document.createElement("div"),e.split(/(?:\r\n?|\n)+/).forEach(m=>{let g=o.appendChild(document.createElement("p"));m&&g.appendChild(p.serializeNode(h.text(m,f)))})}}else n.someProp("transformPastedHTML",d=>{t=d(t,n)}),o=Mf(t),Kr&&vf(o);let c=o&&o.querySelector("[data-pm-slice]"),u=c&&/^(\d+) (\d+)(?: -(\d+))? (.*)/.exec(c.getAttribute("data-pm-slice")||"");if(u&&u[3])for(let d=+u[3];d>0;d--){let f=o.firstChild;for(;f&&!v(f);)f=f.nextSibling;if(!f)break;o=f}if(l||(l=(n.someProp("clipboardParser")||n.someProp("domParser")||Xe.fromSchema(n.state.schema)).parseSlice(o,{preserveWhitespace:!!(a||u),context:i,ruleFromNode(f){return f.nodeName=="BR"&&!f.nextSibling&&f.parentNode&&!xf.test(f.parentNode.nodeName)?{ignore:!0}:null}})),u)l=Ef(No(l,+u[1],+u[2]),u[4]);else if(l=w.maxOpen(wf(l.content,i),!0),l.openStart||l.openEnd){let d=0,f=0;for(let h=l.content.firstChild;d{l=d(l,n,a)}),l}const xf=/^(a|abbr|acronym|b|cite|code|del|em|i|ins|kbd|label|output|q|ruby|s|samp|span|strong|sub|sup|time|u|tt|var)$/i;function wf(n,e){if(n.childCount<2)return n;for(let t=e.depth;t>=0;t--){let i=e.node(t).contentMatchAt(e.index(t)),s,o=[];if(n.forEach(l=>{if(!o)return;let a=i.findWrapping(l.type),c;if(!a)return o=null;if(c=o.length&&s.length&&$a(a,s,l,o[o.length-1],0))o[o.length-1]=c;else{o.length&&(o[o.length-1]=Fa(o[o.length-1],s.length));let u=za(l,a);o.push(u),i=i.matchType(u.type),s=a}}),o)return b.from(o)}return n}function za(n,e,t=0){for(let r=e.length-1;r>=t;r--)n=e[r].create(null,b.from(n));return n}function $a(n,e,t,r,i){if(i1&&(s=0),i=t&&(l=e<0?o.contentMatchAt(0).fillBefore(l,s<=i).append(l):l.append(o.contentMatchAt(o.childCount).fillBefore(b.empty,!0))),n.replaceChild(e<0?0:n.childCount-1,o.copy(l))}function No(n,e,t){return et})}return Jt.createHTML(n)}function Mf(n){let e=/^(\s*]*>)*/.exec(n);e&&(n=n.slice(e[0].length));let t=Ha(),r=t.body,i=/<([a-z][^>\s]+)/i.exec(n),s;if((s=i&&Va[i[1].toLowerCase()])&&(n=s.map(o=>"<"+o+">").join("")+n+s.map(o=>"").reverse().join("")),r.innerHTML=Cf(n),s)for(let o=0;o=0;l-=2){let a=t.nodes[r[l]];if(!a||a.hasRequiredAttrs())break;try{i=b.from(a.create(r[l+1],i))}catch{break}s++,o++}return new w(i,s,o)}const le={},ae={},Tf={touchstart:!0,touchmove:!0};class Af{constructor(){this.shiftKey=!1,this.mouseDown=null,this.lastKeyCode=null,this.lastKeyCodeTime=0,this.lastClick={time:0,x:0,y:0,type:"",button:0},this.lastSelectionOrigin=null,this.lastSelectionTime=0,this.lastIOSEnter=0,this.lastIOSEnterFallbackTimeout=-1,this.lastFocus=0,this.lastTouch=0,this.lastChromeDelete=0,this.composing=!1,this.compositionNode=null,this.composingTimeout=-1,this.compositionNodes=[],this.compositionEndedAt=-2e8,this.compositionID=1,this.badSafariComposition=!1,this.compositionPendingChanges=0,this.domChangeCount=0,this.eventHandlers=Object.create(null),this.hideSelectionGuard=null}}function Of(n){for(let e in le){let t=le[e];n.dom.addEventListener(e,n.input.eventHandlers[e]=r=>{Df(n,r)&&!bs(n,r)&&(n.editable||!(r.type in ae))&&t(n,r)},Tf[e]?{passive:!0}:void 0)}ie&&n.dom.addEventListener("input",()=>null),Wi(n)}function $e(n,e){n.input.lastSelectionOrigin=e,n.input.lastSelectionTime=Date.now()}function Nf(n){n.input.mouseDown&&n.input.mouseDown.done(),n.domObserver.stop();for(let e in n.input.eventHandlers)n.dom.removeEventListener(e,n.input.eventHandlers[e]);clearTimeout(n.input.composingTimeout),clearTimeout(n.input.lastIOSEnterFallbackTimeout)}function Wi(n){n.someProp("handleDOMEvents",e=>{for(let t in e)n.input.eventHandlers[t]||n.dom.addEventListener(t,n.input.eventHandlers[t]=r=>bs(n,r))})}function bs(n,e){return n.someProp("handleDOMEvents",t=>{let r=t[e.type];return r?r(n,e)||e.defaultPrevented:!1})}function Df(n,e){if(!e.bubbles)return!0;if(e.defaultPrevented)return!1;for(let t=e.target;t!=n.dom;t=t.parentNode)if(!t||t.nodeType==11||t.pmViewDesc&&t.pmViewDesc.stopEvent(e))return!1;return!0}function If(n,e){!bs(n,e)&&le[e.type]&&(n.editable||!(e.type in ae))&&le[e.type](n,e)}ae.keydown=(n,e)=>{let t=e;if(n.input.shiftKey=t.keyCode==16||t.shiftKey,!_a(n)&&(n.input.lastKeyCode=t.keyCode,n.input.lastKeyCodeTime=Date.now(),!(ze&&te&&t.keyCode==13)))if(t.keyCode!=229&&n.domObserver.forceFlush(),jt&&t.keyCode==13&&!t.ctrlKey&&!t.altKey&&!t.metaKey){let r=Date.now();n.input.lastIOSEnter=r,n.input.lastIOSEnterFallbackTimeout=setTimeout(()=>{n.input.lastIOSEnter==r&&(n.someProp("handleKeyDown",i=>i(n,ut(13,"Enter"))),n.input.lastIOSEnter=0)},200)}else n.someProp("handleKeyDown",r=>r(n,t))||Sf(n,t)?t.preventDefault():$e(n,"key")};ae.keyup=(n,e)=>{e.keyCode==16&&(n.input.shiftKey=!1)};ae.keypress=(n,e)=>{let t=e;if(_a(n)||!t.charCode||t.ctrlKey&&!t.altKey||be&&t.metaKey)return;if(n.someProp("handleKeyPress",i=>i(n,t))){t.preventDefault();return}let r=n.state.selection;if(!(r instanceof T)||!r.$from.sameParent(r.$to)){let i=String.fromCharCode(t.charCode),s=()=>n.state.tr.insertText(i).scrollIntoView();!/[\r\n]/.test(i)&&!n.someProp("handleTextInput",o=>o(n,r.$from.pos,r.$to.pos,i,s))&&n.dispatch(s()),t.preventDefault()}};function On(n){return{left:n.clientX,top:n.clientY}}function Rf(n,e){let t=e.x-n.clientX,r=e.y-n.clientY;return t*t+r*r<100}function ks(n,e,t,r,i){if(r==-1)return!1;let s=n.state.doc.resolve(r);for(let o=s.depth+1;o>0;o--)if(n.someProp(e,l=>o>s.depth?l(n,t,s.nodeAfter,s.before(o),i,!0):l(n,t,s.node(o),s.before(o),i,!1)))return!0;return!1}function Nn(n,e,t){if(n.focused||n.focus(),n.state.selection.eq(e))return;let r=n.state.tr.setSelection(e);r.setMeta("pointer",!0),n.dispatch(r)}function Lf(n,e){if(e==-1)return!1;let t=n.state.doc.resolve(e),r=t.nodeAfter;return r&&r.isAtom&&E.isSelectable(r)?(Nn(n,new E(t)),!0):!1}function Pf(n,e){if(e==-1)return!1;let t=n.state.selection,r,i;t instanceof E&&(r=t.node);let s=n.state.doc.resolve(e);for(let o=s.depth+1;o>0;o--){let l=o>s.depth?s.nodeAfter:s.node(o);if(E.isSelectable(l)){r&&t.$from.depth>0&&o>=t.$from.depth&&s.before(t.$from.depth+1)==t.$from.pos?i=s.before(t.$from.depth):i=s.before(o);break}}return i!=null?(Nn(n,E.create(n.state.doc,i)),!0):!1}function Bf(n,e,t,r,i){return ks(n,"handleClickOn",e,t,r)||n.someProp("handleClick",s=>s(n,e,r))||(i?Pf(n,t):Lf(n,t))}function zf(n,e,t,r){return ks(n,"handleDoubleClickOn",e,t,r)||n.someProp("handleDoubleClick",i=>i(n,e,r))}function $f(n,e,t,r){return ks(n,"handleTripleClickOn",e,t,r)||n.someProp("handleTripleClick",i=>i(n,e,r))||Ff(n,t,r)}function Ff(n,e,t){if(t.button!=0)return!1;let r=ja(n,e,!0),i=n.state.doc;return r?(Nn(n,r),r instanceof T&&i.eq(n.state.doc)&&(n.input.mouseDown=new Hf(n,r)),!0):!1}function ja(n,e,t){let r=n.state.doc;if(e==-1)return r.inlineContent?T.create(r,0,r.content.size):null;let i=r.resolve(e);for(let s=i.depth+1;s>0;s--){let o=s>i.depth?i.nodeAfter:i.node(s),l=i.before(s);if(o.inlineContent)return T.create(r,l+1,l+1+o.content.size);if(t&&E.isSelectable(o))return E.create(r,l)}return null}function Ss(n){return nr(n)}const Wa=be?"metaKey":"ctrlKey";le.mousedown=(n,e)=>{let t=e;n.input.shiftKey=t.shiftKey;let r=Ss(n),i=Date.now(),s="singleClick";i-n.input.lastClick.time<500&&Rf(t,n.input.lastClick)&&!t[Wa]&&n.input.lastClick.button==t.button&&(n.input.lastClick.type=="singleClick"?s="doubleClick":n.input.lastClick.type=="doubleClick"&&(s="tripleClick")),n.input.lastClick={time:i,x:t.clientX,y:t.clientY,type:s,button:t.button},n.input.mouseDown&&n.input.mouseDown.done();let o=n.posAtCoords(On(t));o&&(s=="singleClick"?n.input.mouseDown=new Vf(n,o,t,!!r):(s=="doubleClick"?zf:$f)(n,o.pos,o.inside,t)?t.preventDefault():$e(n,"pointer"))};class Ka{constructor(e){this.view=e,this.mightDrag=null,e.root.addEventListener("mouseup",this.up=this.up.bind(this)),e.root.addEventListener("mousemove",this.move=this.move.bind(this))}up(e){this.done()}move(e){e.buttons==0&&this.done()}done(){this.view.root.removeEventListener("mouseup",this.up),this.view.root.removeEventListener("mousemove",this.move),this.view.input.mouseDown==this&&(this.view.input.mouseDown=null)}delaySelUpdate(){return!1}}class Vf extends Ka{constructor(e,t,r,i){super(e),this.pos=t,this.event=r,this.flushed=i,this.delayedSelectionSync=!1,this.startDoc=e.state.doc,this.selectNode=!!r[Wa],this.allowDefault=r.shiftKey;let s,o;if(t.inside>-1)s=e.state.doc.nodeAt(t.inside),o=t.inside;else{let u=e.state.doc.resolve(t.pos);s=u.parent,o=u.depth?u.before():0}const l=i?null:r.target,a=l?e.docView.nearestDesc(l,!0):null;this.target=a&&v(a.nodeDOM)?a.nodeDOM:null;let{selection:c}=e.state;r.button==0&&(s.type.spec.draggable&&s.type.spec.selectable!==!1||c instanceof E&&c.from<=o&&c.to>o)&&(this.mightDrag={node:s,pos:o,addAttr:!!(this.target&&!this.target.draggable),setUneditable:!!(this.target&&he&&!this.target.hasAttribute("contentEditable"))}),this.target&&this.mightDrag&&(this.mightDrag.addAttr||this.mightDrag.setUneditable)&&(this.view.domObserver.stop(),this.mightDrag.addAttr&&(this.target.draggable=!0),this.mightDrag.setUneditable&&setTimeout(()=>{this.view.input.mouseDown==this&&this.target.setAttribute("contentEditable","false")},20),this.view.domObserver.start()),$e(e,"pointer")}done(){super.done(),this.mightDrag&&this.target&&(this.view.domObserver.stop(),this.mightDrag.addAttr&&this.target.removeAttribute("draggable"),this.mightDrag.setUneditable&&this.target.removeAttribute("contentEditable"),this.view.domObserver.start()),this.delayedSelectionSync&&setTimeout(()=>{this.view.isDestroyed||Ve(this.view)})}up(e){if(this.done(),!this.view.dom.contains(e.target))return;let t=this.pos;this.view.state.doc!=this.startDoc&&(t=this.view.posAtCoords(On(e))),this.updateAllowDefault(e),this.allowDefault||!t?$e(this.view,"pointer"):Bf(this.view,t.pos,t.inside,e,this.selectNode)?e.preventDefault():e.button==0&&(this.flushed||ie&&this.mightDrag&&!this.mightDrag.node.isAtom||te&&!this.view.state.selection.visible&&Math.min(Math.abs(t.pos-this.view.state.selection.from),Math.abs(t.pos-this.view.state.selection.to))<=2)?(Nn(this.view,O.near(this.view.state.doc.resolve(t.pos))),e.preventDefault()):$e(this.view,"pointer")}move(e){this.updateAllowDefault(e),$e(this.view,"pointer"),super.move(e)}updateAllowDefault(e){!this.allowDefault&&(Math.abs(this.event.x-e.clientX)>4||Math.abs(this.event.y-e.clientY)>4)&&(this.allowDefault=!0)}delaySelUpdate(){return this.allowDefault?(this.delayedSelectionSync=!0,!0):!1}}class Hf extends Ka{constructor(e,t){super(e),this.startSelection=t,this.startDoc=e.state.doc}move(e){if(e.buttons==0||this.view.isDestroyed||!this.view.state.doc.eq(this.startDoc)){this.done();return}e.preventDefault(),$e(this.view,"pointer");let t=this.view.posAtCoords(On(e)),r=t&&ja(this.view,t.inside,!1);if(!r)return;let{doc:i}=this.view.state,s=this.startSelection,[o,l]=r.from{n.input.lastTouch=Date.now(),Ss(n),$e(n,"pointer")};le.touchmove=n=>{n.input.lastTouch=Date.now(),$e(n,"pointer")};le.contextmenu=n=>Ss(n);function _a(n,e){return n.composing?!0:ie&&Math.abs(Date.now()-n.input.compositionEndedAt)<500?(n.input.compositionEndedAt=-2e8,!0):!1}const jf=ze?5e3:-1;ae.compositionstart=ae.compositionupdate=n=>{if(!n.composing){n.domObserver.flush();let{state:e}=n,t=e.selection.$to;if(e.selection instanceof T&&e.selection.empty&&(e.storedMarks||!t.textOffset&&t.parentOffset&&t.nodeBefore.marks.some(r=>r.type.spec.inclusive===!1)||te&&Sa&&Wf(n)))n.markCursor=n.state.storedMarks||t.marks(),nr(n,!0),n.markCursor=null;else if(nr(n,!e.selection.empty),he&&e.selection.empty&&t.parentOffset&&!t.textOffset&&t.nodeBefore.marks.length){let r=n.domSelectionRange();for(let i=r.focusNode,s=r.focusOffset;i&&v(i)&&s!=0;){let o=s<0?i.lastChild:i.childNodes[s-1];if(!o)break;if(U(o)){let l=n.domSelection();l&&l.collapse(o,o.nodeValue.length);break}else i=o,s=-1}}n.input.composing=!0}Ua(n,jf)};function Wf(n){let{focusNode:e,focusOffset:t}=n.domSelectionRange();if(!e||!v(e)||t>=e.childNodes.length)return!1;let r=e.childNodes[t];return v(r)&&r.contentEditable=="false"}ae.compositionend=(n,e)=>{n.composing&&(n.input.composing=!1,n.input.compositionEndedAt=Date.now(),n.input.compositionPendingChanges=n.domObserver.pendingRecords().length?n.input.compositionID:0,n.input.compositionNode=null,n.input.badSafariComposition?n.domObserver.forceFlush():n.input.compositionPendingChanges&&Promise.resolve().then(()=>n.domObserver.flush()),n.input.compositionID++,Ua(n,20))};function Ua(n,e){clearTimeout(n.input.composingTimeout),e>-1&&(n.input.composingTimeout=setTimeout(()=>nr(n),e))}function qa(n){for(n.composing&&(n.input.composing=!1,n.input.compositionEndedAt=Date.now());n.input.compositionNodes.length>0;)n.input.compositionNodes.pop().markParentsDirty()}function Kf(n){let e=n.domSelectionRange();if(!e.focusNode)return null;let t=Ld(e.focusNode,e.focusOffset),r=Pd(e.focusNode,e.focusOffset);if(t&&r&&t!=r){let i=r.pmViewDesc,s=n.domObserver.lastChangedTextNode;if(t==s||r==s)return s;if(!i||!i.isText(r.nodeValue))return r;if(n.input.compositionNode==r){let o=t.pmViewDesc;if(!(!o||!o.isText(t.nodeValue)))return r}}return t||r}function nr(n,e=!1){if(!(ze&&n.domObserver.flushingSoon>=0)){if(n.domObserver.forceFlush(),qa(n),e||n.docView&&n.docView.dirty){let t=ms(n),r=n.state.selection;return t&&!t.eq(r)?n.dispatch(n.state.tr.setSelection(t)):(n.markCursor||e)&&!r.$from.node(r.$from.sharedDepth(r.to)).inlineContent?n.dispatch(n.state.tr.deleteSelection()):n.updateState(n.state),!0}return!1}}function _f(n,e){if(!n.dom.parentNode)return;let t=n.dom.parentNode.appendChild(document.createElement("div"));t.appendChild(e),t.style.cssText="position: fixed; left: -10000px; top: 10px";let r=getSelection(),i=document.createRange();i.selectNodeContents(e),n.dom.blur(),r.removeAllRanges(),r.addRange(i),setTimeout(()=>{t.parentNode&&t.parentNode.removeChild(t),n.focus()},50)}const xn=ue&&Qe<15||jt&&Fd<604;le.copy=ae.cut=(n,e)=>{let t=e,r=n.state.selection,i=t.type=="cut";if(r.empty)return;let s=xn?null:t.clipboardData,o=r.content(),{dom:l,text:a}=ys(n,o);s?(t.preventDefault(),s.clearData(),s.setData("text/html",l.innerHTML),s.setData("text/plain",a)):_f(n,l),i&&n.dispatch(n.state.tr.deleteSelection().scrollIntoView().setMeta("uiEvent","cut"))};function Uf(n){return n.openStart==0&&n.openEnd==0&&n.content.childCount==1?n.content.firstChild:null}function qf(n,e){if(!n.dom.parentNode)return;let t=n.input.shiftKey||n.state.selection.$from.parent.type.spec.code,r=n.dom.parentNode.appendChild(document.createElement(t?"textarea":"div"));t||(r.contentEditable="true"),r.style.cssText="position: fixed; left: -10000px; top: 10px",r.focus();let i=n.input.shiftKey&&n.input.lastKeyCode!=45;setTimeout(()=>{n.focus(),r.parentNode&&r.parentNode.removeChild(r),t?wn(n,r.value,null,i,e):wn(n,r.textContent,r.innerHTML,i,e)},50)}function wn(n,e,t,r,i){let s=Ba(n,e,t,r,n.state.selection.$from);if(n.someProp("handlePaste",a=>a(n,i,s||w.empty)))return!0;if(!s)return!1;let o=Uf(s),l=o?n.state.tr.replaceSelectionWith(o,r):n.state.tr.replaceSelection(s);return n.dispatch(l.scrollIntoView().setMeta("paste",!0).setMeta("uiEvent","paste")),!0}function Ja(n){let e=n.getData("text/plain")||n.getData("Text");if(e)return e;let t=n.getData("text/uri-list");return t?t.replace(/\r?\n/g," "):""}ae.paste=(n,e)=>{let t=e;if(n.composing&&!ze)return;let r=xn?null:t.clipboardData,i=n.input.shiftKey&&n.input.lastKeyCode!=45;r&&wn(n,Ja(r),r.getData("text/html"),i,t)?t.preventDefault():qf(n,t)};class Ga{constructor(e,t,r){this.slice=e,this.move=t,this.node=r}}const Jf=be?"altKey":"ctrlKey";function Ya(n,e){let t;return n.someProp("dragCopies",r=>{t=t||r(e)}),t!=null?!t:!e[Jf]}le.dragstart=(n,e)=>{let t=e,r=n.input.mouseDown;if(r&&r.done(),!t.dataTransfer)return;let i=n.state.selection,s=i.empty?null:n.posAtCoords(On(t)),o;if(!(s&&s.pos>=i.from&&s.pos<=(i instanceof E?i.to-1:i.to))){if(r&&r.mightDrag)o=E.create(n.state.doc,r.mightDrag.pos);else if(t.target&&v(t.target)){let d=n.docView.nearestDesc(t.target,!0);d&&d.node.type.spec.draggable&&d!=n.docView&&(o=E.create(n.state.doc,d.posBefore))}}let l=(o||n.state.selection).content(),{dom:a,text:c,slice:u}=ys(n,l);(!t.dataTransfer.files.length||!te||ka>120)&&t.dataTransfer.clearData(),t.dataTransfer.setData(xn?"Text":"text/html",a.innerHTML),t.dataTransfer.effectAllowed="copyMove",xn||t.dataTransfer.setData("text/plain",c),n.dragging=new Ga(u,Ya(n,t),o)};le.dragend=n=>{let e=n.dragging;window.setTimeout(()=>{n.dragging==e&&(n.dragging=null)},50)};ae.dragover=ae.dragenter=(n,e)=>e.preventDefault();ae.drop=(n,e)=>{try{Gf(n,e,n.dragging)}finally{n.dragging=null}};function Gf(n,e,t){if(!e.dataTransfer)return;let r=n.posAtCoords(On(e));if(!r)return;let i=n.state.doc.resolve(r.pos),s=t&&t.slice;s?n.someProp("transformPasted",h=>{s=h(s,n,!1)}):s=Ba(n,Ja(e.dataTransfer),xn?null:e.dataTransfer.getData("text/html"),!1,i);let o=!!(t&&Ya(n,e));if(n.someProp("handleDrop",h=>h(n,e,s||w.empty,o))){e.preventDefault();return}if(!s)return;e.preventDefault();let l=s?Xl(n.state.doc,i.pos,s):i.pos;l==null&&(l=i.pos);let a=n.state.tr;if(o){let{node:h}=t;h?h.replace(a):a.deleteSelection()}let c=a.mapping.map(l),u=s.openStart==0&&s.openEnd==0&&s.content.childCount==1,d=a.doc;if(u?a.replaceRangeWith(c,c,s.content.firstChild):a.replaceRange(c,c,s),a.doc.eq(d))return;let f=a.doc.resolve(c);if(u&&E.isSelectable(s.content.firstChild)&&f.nodeAfter&&f.nodeAfter.sameMarkup(s.content.firstChild))a.setSelection(new E(f));else{let h=a.mapping.map(l);a.mapping.maps[a.mapping.maps.length-1].forEach((p,m,g,y)=>h=y),a.setSelection(gs(n,f,a.doc.resolve(h)))}n.focus(),n.dispatch(a.setMeta("uiEvent","drop"))}le.focus=n=>{n.input.lastFocus=Date.now(),n.focused||(n.domObserver.stop(),n.dom.classList.add("ProseMirror-focused"),n.domObserver.start(),n.focused=!0,setTimeout(()=>{n.docView&&n.hasFocus()&&!n.domObserver.currentSelection.eq(n.domSelectionRange())&&Ve(n)},20))};le.blur=(n,e)=>{let t=e;n.focused&&(n.domObserver.stop(),n.dom.classList.remove("ProseMirror-focused"),n.domObserver.start(),t.relatedTarget&&n.dom.contains(t.relatedTarget)&&n.domObserver.currentSelection.clear(),n.focused=!1)};le.beforeinput=(n,e)=>{if(ze&&e.inputType=="deleteContentBackward"){n.domObserver.flushSoon();let{domChangeCount:r}=n.input;setTimeout(()=>{if(n.input.domChangeCount!=r||(n.dom.blur(),n.focus(),n.someProp("handleKeyDown",s=>s(n,ut(8,"Backspace")))))return;let{$cursor:i}=n.state.selection;i&&i.pos>0&&n.dispatch(n.state.tr.delete(i.pos-1,i.pos).scrollIntoView())},50)}};for(let n in ae)le[n]=ae[n];function Cn(n,e){if(n==e)return!0;for(let t in n)if(n[t]!==e[t])return!1;for(let t in e)if(!(t in n))return!1;return!0}class rr{constructor(e,t){this.toDOM=e,this.spec=t||kt,this.side=this.spec.side||0}map(e,t,r,i){let{pos:s,deleted:o}=e.mapResult(t.from+i,this.side<0?-1:1);return o?null:new oe(s-r,s-r,this)}valid(){return!0}eq(e){return this==e||e instanceof rr&&(this.spec.key&&this.spec.key==e.spec.key||this.toDOM==e.toDOM&&Cn(this.spec,e.spec))}destroy(e){this.spec.destroy&&this.spec.destroy(e)}}class tt{constructor(e,t){this.attrs=e,this.spec=t||kt}map(e,t,r,i){let s=e.map(t.from+i,this.spec.inclusiveStart?-1:1)-r,o=e.map(t.to+i,this.spec.inclusiveEnd?1:-1)-r;return s>=o?null:new oe(s,o,this)}valid(e,t){return t.from=e&&(!s||s(l.spec))&&r.push(l.copy(l.from+i,l.to+i))}for(let o=0;oe){let l=this.children[o]+1;this.children[o+2].findInner(e-l,t-l,r,i+l,s)}}map(e,t,r){return this==ne||e.maps.length==0?this:this.mapInner(e,t,0,0,r||kt)}mapInner(e,t,r,i,s){let o;for(let l=0;l{let c=a+r,u;if(u=Qa(t,l,c)){for(i||(i=this.children.slice());sl&&d.to=e){this.children[l]==e&&(r=this.children[l+2]);break}let s=e+1,o=s+t.content.size;for(let l=0;ls&&a.type instanceof tt){let c=Math.max(s,a.from)-s,u=Math.min(o,a.to)-s;ci.map(e,t,kt));return Je.from(r)}forChild(e,t){if(t.isLeaf)return D.empty;let r=[];for(let i=0;it instanceof D)?e:e.reduce((t,r)=>t.concat(r instanceof D?r:r.members),[]))}}forEachSet(e){for(let t=0;t{let g=m-p-(h-f);for(let y=0;yS+u-d)continue;let x=l[y]+u-d;h>=x?l[y+1]=f<=x?-2:-1:f>=u&&g&&(l[y]+=g,l[y+1]+=g)}d+=g}),u=t.maps[c].map(u,-1)}let a=!1;for(let c=0;c=r.content.size){a=!0;continue}let f=t.map(n[c+1]+s,-1),h=f-i,{index:p,offset:m}=r.content.findIndex(d),g=r.maybeChild(p);if(g&&m==d&&m+g.nodeSize==h){let y=l[c+2].mapInner(t,g,u+1,n[c]+s+1,o);y!=ne?(l[c]=d,l[c+1]=h,l[c+2]=y):(l[c+1]=-2,a=!0)}else a=!0}if(a){let c=Xf(l,n,e,t,i,s,o),u=ir(c,r,0,o);e=u.local;for(let d=0;dt&&o.to{let c=Qa(n,l,a+t);if(c){s=!0;let u=ir(c,l,t+a+1,r);u!=ne&&i.push(a,a+l.nodeSize,u)}});let o=Xa(s?Za(n):n,-t).sort(St);for(let l=0;l0;)e++;n.splice(e,0,t)}function ui(n){let e=[];return n.someProp("decorations",t=>{let r=t(n.state);r&&r!=ne&&e.push(r)}),n.cursorWrapper&&e.push(D.create(n.state.doc,[n.cursorWrapper.deco])),Je.from(e)}const Qf={childList:!0,characterData:!0,characterDataOldValue:!0,attributes:!0,attributeOldValue:!0,subtree:!0},Zf=ue&&Qe<=11;class eh{constructor(){this.anchorNode=null,this.anchorOffset=0,this.focusNode=null,this.focusOffset=0}set(e){this.anchorNode=e.anchorNode,this.anchorOffset=e.anchorOffset,this.focusNode=e.focusNode,this.focusOffset=e.focusOffset}clear(){this.anchorNode=this.focusNode=null}eq(e){return e.anchorNode==this.anchorNode&&e.anchorOffset==this.anchorOffset&&e.focusNode==this.focusNode&&e.focusOffset==this.focusOffset}}class th{constructor(e,t){this.view=e,this.handleDOMChange=t,this.queue=[],this.flushingSoon=-1,this.observer=null,this.currentSelection=new eh,this.onCharData=null,this.suppressingSelectionUpdates=!1,this.lastChangedTextNode=null,this.observer=window.MutationObserver&&new window.MutationObserver(r=>{for(let i=0;ii.type=="childList"&&i.removedNodes.length||i.type=="characterData"&&i.oldValue.length>i.target.nodeValue.length)?this.flushSoon():ie&&e.composing&&r.some(i=>i.type=="childList"&&i.target.nodeName=="TR")?(e.input.badSafariComposition=!0,this.flushSoon()):this.flush()}),Zf&&(this.onCharData=r=>{this.queue.push({target:r.target,type:"characterData",oldValue:r.prevValue}),this.flushSoon()}),this.onSelectionChange=this.onSelectionChange.bind(this)}flushSoon(){this.flushingSoon<0&&(this.flushingSoon=window.setTimeout(()=>{this.flushingSoon=-1,this.flush()},20))}forceFlush(){this.flushingSoon>-1&&(window.clearTimeout(this.flushingSoon),this.flushingSoon=-1,this.flush())}start(){this.observer&&(this.observer.takeRecords(),this.observer.observe(this.view.dom,Qf)),this.onCharData&&this.view.dom.addEventListener("DOMCharacterDataModified",this.onCharData),this.connectSelection()}stop(){if(this.observer){let e=this.observer.takeRecords();if(e.length){for(let t=0;tthis.flush(),20)}this.observer.disconnect()}this.onCharData&&this.view.dom.removeEventListener("DOMCharacterDataModified",this.onCharData),this.disconnectSelection()}connectSelection(){this.view.dom.ownerDocument.addEventListener("selectionchange",this.onSelectionChange)}disconnectSelection(){this.view.dom.ownerDocument.removeEventListener("selectionchange",this.onSelectionChange)}suppressSelectionUpdates(){this.suppressingSelectionUpdates=!0,setTimeout(()=>this.suppressingSelectionUpdates=!1,50)}onSelectionChange(){if(Mo(this.view)){if(this.suppressingSelectionUpdates)return Ve(this.view);if(ue&&Qe<=11&&!this.view.state.selection.empty){let e=this.view.domSelectionRange();if(e.focusNode&&Ct(e.focusNode,e.focusOffset,e.anchorNode,e.anchorOffset))return this.flushSoon()}this.flush()}}setCurSelection(){this.currentSelection.set(this.view.domSelectionRange())}ignoreSelectionChange(e){if(!e.focusNode)return!0;let t=new Set,r;for(let s=e.focusNode;s;s=Ht(s))t.add(s);for(let s=e.anchorNode;s;s=Ht(s))if(t.has(s)){r=s;break}let i=r&&this.view.docView.nearestDesc(r);if(i&&i.ignoreMutation({type:"selection",target:U(r)?r.parentNode:r}))return this.setCurSelection(),!0}pendingRecords(){if(this.observer)for(let e of this.observer.takeRecords())this.queue.push(e);return this.queue}flush(){let{view:e}=this;if(!e.docView||this.flushingSoon>-1)return;let t=this.pendingRecords();t.length&&(this.queue=[]);let r=e.domSelectionRange(),i=!this.suppressingSelectionUpdates&&!this.currentSelection.eq(r)&&Mo(e)&&!this.ignoreSelectionChange(r),s=-1,o=-1,l=!1,a=[];if(e.editable)for(let u=0;uu.nodeName=="BR")&&(e.input.lastKeyCode==8||e.input.lastKeyCode==46||te&&(e.composing||e.input.compositionEndedAt>Date.now()-50)&&t.some(u=>u.type=="childList"&&u.removedNodes.length))){for(let u of a)if(u.nodeName=="BR"&&u.parentNode){let d=u.nextSibling;for(;d&&v(d);){if(d.contentEditable=="false"){u.parentNode.removeChild(u);break}d=d.firstChild}}}else if(he&&a.length){let u=a.filter(d=>d.nodeName=="BR");if(u.length==2){let[d,f]=u;d.parentNode&&d.parentNode.parentNode==f.parentNode?f.remove():d.remove()}else{let{focusNode:d}=this.currentSelection;for(let f of u){let h=f.parentNode;h&&h.nodeName=="LI"&&(!d||ih(e,d)!=h)&&f.remove()}}}let c=null;s<0&&i&&e.input.lastFocus>Date.now()-200&&Math.max(e.input.lastTouch,e.input.lastClick.time)-1||i)&&(s>-1&&(e.docView.markDirty(s,o),nh(e)),e.input.badSafariComposition&&(e.input.badSafariComposition=!1,sh(e,a)),this.handleDOMChange(s,o,l,a),e.docView&&e.docView.dirty?e.updateState(e.state):this.currentSelection.eq(r)||Ve(e),this.currentSelection.set(r))}registerMutation(e,t){if(t.indexOf(e.target)>-1)return null;let r=this.view.docView.nearestDesc(e.target);if(e.type=="attributes"&&(r==this.view.docView||e.attributeName=="contenteditable"||e.attributeName=="style"&&!e.oldValue&&!e.target.getAttribute("style"))||!r||r.ignoreMutation(e))return null;if(e.type=="childList"){for(let u=0;us;y--){let S=i.childNodes[y-1],x=S.pmViewDesc;if(S.nodeName=="BR"&&!x){o=y;break}if(!x||x.size)break}let f=n.state.doc,h=n.someProp("domParser")||Xe.fromSchema(n.state.schema),p=f.resolve(l),m=null,g=h.parse(i,{topNode:p.parent,topMatch:p.parent.contentMatchAt(p.index()),topOpen:!0,from:s,to:o,preserveWhitespace:p.parent.type.whitespace=="pre"?"full":!0,findPositions:u,ruleFromNode:lh(r),context:p});if(u&&u[0].pos!=null){let y=u[0].pos,S=u[1]&&u[1].pos;S==null&&(S=y),m={anchor:y+l,head:S+l}}return{doc:g,sel:m,from:l,to:a}}const lh=n=>e=>{let t=e.pmViewDesc;if(t)return t.parseRule(n);if(e.nodeName=="BR"&&e.parentNode){if(ie&&/^(ul|ol)$/i.test(e.parentNode.nodeName)){let r=document.createElement("div");return r.appendChild(document.createElement("li")),{skip:r}}else if(e.parentNode.lastChild==e||ie&&/^(tr|table)$/i.test(e.parentNode.nodeName))return{ignore:!0}}else if(e.nodeName=="IMG"&&e.getAttribute("mark-placeholder"))return{ignore:!0};return null},ah=/^(a|abbr|acronym|b|bd[io]|big|br|button|cite|code|data(list)?|del|dfn|em|i|img|ins|kbd|label|map|mark|meter|output|q|ruby|s|samp|small|span|strong|su[bp]|time|u|tt|var)$/i;function ch(n,e,t,r,i){let s=n.input.compositionPendingChanges||(n.composing?n.input.compositionID:0);if(n.input.compositionPendingChanges=0,e<0){let A=n.input.lastSelectionTime>Date.now()-50?n.input.lastSelectionOrigin:null,R=ms(n,A);if(R&&!n.state.selection.eq(R)){if(te&&ze&&n.input.lastKeyCode===13&&Date.now()-100X(n,ut(13,"Enter"))))return;let P=n.state.tr.setSelection(R);A=="pointer"?P.setMeta("pointer",!0):A=="key"&&P.scrollIntoView(),s&&P.setMeta("composition",s),n.dispatch(P)}return}let o=n.state.doc.resolve(e),l=o.sharedDepth(t);e=o.before(l+1),t=n.state.doc.resolve(t).after(l+1);let a=n.state.selection,c=oh(n,e,t,i),u=n.state.doc,d=u.slice(c.from,c.to),f,h;n.input.lastKeyCode===8&&Date.now()-100Date.now()-225||ze)&&i.some(A=>v(A)&&!ah.test(A.nodeName))&&(!p||p.endA>=p.endB)&&n.someProp("handleKeyDown",A=>A(n,ut(13,"Enter")))){n.input.lastIOSEnter=0;return}if(!p)if(r&&a instanceof T&&!a.empty&&a.$head.sameParent(a.$anchor)&&!n.composing&&!(c.sel&&c.sel.anchor!=c.sel.head))p={start:a.from,endA:a.to,endB:a.to};else{if(c.sel){let A=Po(n,n.state.doc,c.sel);if(A&&!A.eq(n.state.selection)){let R=n.state.tr.setSelection(A);s&&R.setMeta("composition",s),n.dispatch(R)}}return}n.state.selection.fromn.state.selection.from&&p.start<=n.state.selection.from+2&&n.state.selection.from>=c.from?p.start=n.state.selection.from:p.endA=n.state.selection.to-2&&n.state.selection.to<=c.to&&(p.endB+=n.state.selection.to-p.endA,p.endA=n.state.selection.to)),ue&&Qe<=11&&p.endB==p.start+1&&p.endA==p.start&&p.start>c.from&&c.doc.textBetween(p.start-c.from-1,p.start-c.from+1)=="  "&&(p.start--,p.endA--,p.endB--);let m=c.doc.resolveNoCache(p.start-c.from),g=c.doc.resolveNoCache(p.endB-c.from),y=u.resolve(p.start),S=m.sameParent(g)&&m.parent.inlineContent&&y.end()>=p.endA;if((jt&&n.input.lastIOSEnter>Date.now()-225&&(!S||i.some(A=>A.nodeName=="DIV"||A.nodeName=="P"))||!S&&fh(c.doc,m.pos,g.pos))&&n.someProp("handleKeyDown",A=>A(n,ut(13,"Enter")))){n.input.lastIOSEnter=0;return}if(n.state.selection.anchor>p.start&&dh(u,p.start,p.endA,m,g)&&n.someProp("handleKeyDown",A=>A(n,ut(8,"Backspace")))){ze&&te&&n.domObserver.suppressSelectionUpdates();return}te&&p.endB==p.start&&(n.input.lastChromeDelete=Date.now()),ze&&!S&&m.start()!=g.start()&&g.parentOffset==0&&m.depth==g.depth&&c.sel&&c.sel.anchor==c.sel.head&&c.sel.head==p.endA&&(p.endB-=2,g=c.doc.resolveNoCache(p.endB-c.from),setTimeout(()=>{n.someProp("handleKeyDown",function(A){return A(n,ut(13,"Enter"))})},20));let x=p.start,C=p.endA,I=A=>{let R=A||n.state.tr.replace(x,C,c.doc.slice(p.start-c.from,p.endB-c.from));if(c.sel){let P=Po(n,R.doc,c.sel);P&&!(te&&n.composing&&P.empty&&(p.start!=p.endB||n.input.lastChromeDeleteVe(n),20));let A=I(n.state.tr.delete(x,C)),R=u.resolve(p.start).marksAcross(u.resolve(p.endA));R&&A.ensureMarks(R),n.dispatch(A)}else if(p.endA==p.endB&&(F=uh(m.parent.content.cut(m.parentOffset,g.parentOffset),y.parent.content.cut(y.parentOffset,p.endA-y.start())))){let A=I(n.state.tr);F.type=="add"?A.addMark(x,C,F.mark):A.removeMark(x,C,F.mark),n.dispatch(A)}else if(m.parent.child(m.index()).isText&&m.index()==g.index()-(g.textOffset?0:1)){let A=m.parent.textBetween(m.parentOffset,g.parentOffset),R=()=>I(n.state.tr.insertText(A,x,C));n.someProp("handleTextInput",P=>P(n,x,C,A,R))||n.dispatch(R())}else n.dispatch(I());else n.dispatch(I())}function Po(n,e,t){return Math.max(t.anchor,t.head)>e.content.size?null:gs(n,e.resolve(t.anchor),e.resolve(t.head))}function uh(n,e){let t=n.firstChild.marks,r=e.firstChild.marks,i=t,s=r,o,l,a;for(let u=0;uu.mark(l.addToSet(u.marks));else if(i.length==0&&s.length==1)l=s[0],o="remove",a=u=>u.mark(l.removeFromSet(u.marks));else return null;let c=[];for(let u=0;ut||di(o,!0,!1){s.isTextblock&&o>=e&&o0&&(e||n.indexAfter(r)==n.node(r).childCount);)r--,i++,e=!1;if(t){let s=n.node(r).maybeChild(n.indexAfter(r));for(;s&&!s.isLeaf;)s=s.firstChild,i++}return i}function hh(n,e,t,r,i){let s=n.findDiffStart(e,t),o=t+n.size,l=t+e.size;if(s==null)return null;let{a,b:c}=n.findDiffEnd(e,o,l);if(i=="end"){let u=Math.max(0,s-Math.min(a,c));r-=a+u-s}if(a=a?s-r:0;s-=u,c=s+(c-a),a=s}else if(c=c?s-r:0;s-=u,a=s+(a-c),c=s}return{start:s,endA:a,endB:c}}class ec{constructor(e,t){this._root=null,this.focused=!1,this.trackWrites=null,this.mounted=!1,this.markCursor=null,this.cursorWrapper=null,this.lastSelectedViewDesc=void 0,this.input=new Af,this.prevDirectPlugins=[],this.pluginViews=[],this.requiresGeckoHackNode=!1,this.dragging=null,this._props=t,this.state=t.state,this.directPlugins=t.plugins||[],this.directPlugins.forEach(Vo),this.dispatch=this.dispatch.bind(this),this.dom=e&&e.mount||document.createElement("div"),e&&(e.appendChild?e.appendChild(this.dom):typeof e=="function"?e(this.dom):e.mount&&(this.mounted=!0)),this.editable=$o(this),zo(this),this.nodeViews=Fo(this),this.docView=bo(this.state.doc,Bo(this),ui(this),this.dom,this),this.domObserver=new th(this,(r,i,s,o)=>ch(this,r,i,s,o)),this.domObserver.start(),Of(this),this.updatePluginViews()}get composing(){return this.input.composing}get props(){if(this._props.state!=this.state){let e=this._props;this._props={};for(let t in e)this._props[t]=e[t];this._props.state=this.state}return this._props}update(e){e.handleDOMEvents!=this._props.handleDOMEvents&&Wi(this);let t=this._props;this._props=e,e.plugins&&(e.plugins.forEach(Vo),this.directPlugins=e.plugins),this.updateStateInner(e.state,t)}setProps(e){let t={};for(let r in this._props)t[r]=this._props[r];t.state=this.state;for(let r in e)t[r]=e[r];this.update(t)}updateState(e){this.updateStateInner(e,this._props)}updateStateInner(e,t){var r;let i=this.state,s=!1,o=!1;e.storedMarks&&this.composing&&(qa(this),o=!0),this.state=e;let l=i.plugins!=e.plugins||this._props.plugins!=t.plugins;if(l||this._props.plugins!=t.plugins||this._props.nodeViews!=t.nodeViews){let h=Fo(this);mh(h,this.nodeViews)&&(this.nodeViews=h,s=!0)}(l||t.handleDOMEvents!=this._props.handleDOMEvents)&&Wi(this),this.editable=$o(this),zo(this);let a=ui(this),c=Bo(this),u=i.plugins!=e.plugins&&!i.doc.eq(e.doc)?"reset":e.scrollToSelection>i.scrollToSelection?"to selection":"preserve",d=s||!this.docView.matchesNode(e.doc,c,a);(d||!e.selection.eq(i.selection))&&(o=!0);let f=u=="preserve"&&o&&this.dom.style.overflowAnchor==null&&jd(this);if(o){this.domObserver.stop();let h=d&&(ue||te)&&!this.composing&&!i.selection.empty&&!e.selection.empty&&ph(i.selection,e.selection);if(d){let m=te?this.trackWrites=this.domSelectionRange().focusNode:null;this.composing&&(this.input.compositionNode=Kf(this)),(s||!this.docView.update(e.doc,c,a,this))&&(this.docView.updateOuterDeco(c),this.docView.destroy(),this.docView=bo(e.doc,c,a,this.dom,this)),m&&(!this.trackWrites||!this.dom.contains(this.trackWrites))&&(h=!0)}let p=this.input.mouseDown;h||!(p&&this.domObserver.currentSelection.eq(this.domSelectionRange())&&hf(this)&&p.delaySelUpdate())?Ve(this,h):(Ra(this,e.selection),this.domObserver.setCurSelection()),this.domObserver.start()}this.updatePluginViews(i),!((r=this.dragging)===null||r===void 0)&&r.node&&!i.doc.eq(e.doc)&&this.updateDraggedNode(this.dragging,i),u=="reset"?this.dom.scrollTop=0:u=="to selection"?this.scrollToSelection():f&&Wd(f)}scrollToSelection(){let e=this.domSelectionRange().focusNode;if(!(!e||!Mt(this.dom,e))){if(!this.someProp("handleScrollToSelection",t=>t(this)))if(this.state.selection instanceof E){let t=this.docView.domAfterPos(this.state.selection.from);v(t)&&ho(this,t.getBoundingClientRect(),e)}else ho(this,this.coordsAtPos(this.state.selection.head,1),e)}}destroyPluginViews(){let e;for(;e=this.pluginViews.pop();)e.destroy&&e.destroy()}updatePluginViews(e){if(!e||e.plugins!=this.state.plugins||this.directPlugins!=this.prevDirectPlugins){this.prevDirectPlugins=this.directPlugins,this.destroyPluginViews();for(let t=0;t0&&st.ownerDocument.getSelection()),this._root=t}return e||document}updateRoot(){this._root=null}posAtCoords(e){return Gd(this,e)}coordsAtPos(e,t=1){return va(this,e,t)}domAtPos(e,t=0){return this.docView.domFromPos(e,t)}nodeDOM(e){let t=this.docView.descAt(e);return t?t.nodeDOM:null}posAtDOM(e,t,r=-1){let i=this.docView.posFromDOM(e,t,r);if(i==null)throw new RangeError("DOM position not inside the editor");return i}endOfTextblock(e,t){return ef(this,t||this.state,e)}pasteHTML(e,t){return wn(this,"",e,!1,t||new ClipboardEvent("paste"))}pasteText(e,t){return wn(this,e,null,!0,t||new ClipboardEvent("paste"))}serializeForClipboard(e){return ys(this,e)}destroy(){this.docView&&(Nf(this),this.destroyPluginViews(),this.mounted?(this.docView.update(this.state.doc,[],ui(this),this),this.dom.textContent=""):this.dom.parentNode&&this.dom.parentNode.removeChild(this.dom),this.docView.destroy(),this.docView=null,Id())}get isDestroyed(){return this.docView==null}dispatchEvent(e){return If(this,e)}domSelectionRange(){let e=this.dom.isConnected!==!1&&this.domSelection();return e?ie&&this.root.nodeType===11&&zd(this.dom.ownerDocument)==this.dom&&rh(this,e)||e:{focusNode:null,focusOffset:0,anchorNode:null,anchorOffset:0}}domSelection(){return this.root.getSelection()}}ec.prototype.dispatch=function(n){let e=this._props.dispatchTransaction;e?e.call(this,n):this.updateState(this.state.apply(n))};function Bo(n){let e=Object.create(null);return e.class="ProseMirror",e.contenteditable=String(n.editable),n.someProp("attributes",t=>{if(typeof t=="function"&&(t=t(n.state)),t)for(let r in t)r=="class"?e.class+=" "+t[r]:r=="style"?e.style=(e.style?e.style+";":"")+t[r]:!e[r]&&r!="contenteditable"&&r!="nodeName"&&(e[r]=String(t[r]))}),e.translate||(e.translate="no"),[oe.node(0,n.state.doc.content.size,e)]}function zo(n){if(n.markCursor){let e=document.createElement("img");e.className="ProseMirror-separator",e.setAttribute("mark-placeholder","true"),e.setAttribute("alt",""),n.cursorWrapper={dom:e,deco:oe.widget(n.state.selection.from,e,{raw:!0,marks:n.markCursor})}}else n.cursorWrapper=null}function $o(n){return!n.someProp("editable",e=>e(n.state)===!1)}function ph(n,e){let t=Math.min(n.$anchor.sharedDepth(n.head),e.$anchor.sharedDepth(e.head));return n.$anchor.start(t)!=e.$anchor.start(t)}function Fo(n){let e=Object.create(null);function t(r){for(let i in r)Object.prototype.hasOwnProperty.call(e,i)||(e[i]=r[i])}return n.someProp("nodeViews",t),n.someProp("markViews",t),e}function mh(n,e){let t=0,r=0;for(let i in n){if(n[i]!=e[i])return!0;t++}for(let i in e)r++;return t!=r}function Vo(n){if(n.spec.state||n.spec.filterTransaction||n.spec.appendTransaction)throw new RangeError("Plugins passed directly to the view must not have a state component")}var rt={8:"Backspace",9:"Tab",10:"Enter",12:"NumLock",13:"Enter",16:"Shift",17:"Control",18:"Alt",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",44:"PrintScreen",45:"Insert",46:"Delete",59:";",61:"=",91:"Meta",92:"Meta",106:"*",107:"+",108:",",109:"-",110:".",111:"/",144:"NumLock",145:"ScrollLock",160:"Shift",161:"Shift",162:"Control",163:"Control",164:"Alt",165:"Alt",173:"-",186:";",187:"=",188:",",189:"-",190:".",191:"/",192:"`",219:"[",220:"\\",221:"]",222:"'"},sr={48:")",49:"!",50:"@",51:"#",52:"$",53:"%",54:"^",55:"&",56:"*",57:"(",59:":",61:"+",173:"_",186:":",187:"+",188:"<",189:"_",190:">",191:"?",192:"~",219:"{",220:"|",221:"}",222:'"'},gh=typeof navigator<"u"&&/Mac/.test(navigator.platform),yh=typeof navigator<"u"&&/MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent);for(var ee=0;ee<10;ee++)rt[48+ee]=rt[96+ee]=String(ee);for(var ee=1;ee<=24;ee++)rt[ee+111]="F"+ee;for(var ee=65;ee<=90;ee++)rt[ee]=String.fromCharCode(ee+32),sr[ee]=String.fromCharCode(ee);for(var fi in rt)sr.hasOwnProperty(fi)||(sr[fi]=rt[fi]);function bh(n){var e=gh&&n.metaKey&&n.shiftKey&&!n.ctrlKey&&!n.altKey||yh&&n.shiftKey&&n.key&&n.key.length==1||n.key=="Unidentified",t=!e&&n.key||(n.shiftKey?sr:rt)[n.keyCode]||n.key||"Unidentified";return t=="Esc"&&(t="Escape"),t=="Del"&&(t="Delete"),t=="Left"&&(t="ArrowLeft"),t=="Up"&&(t="ArrowUp"),t=="Right"&&(t="ArrowRight"),t=="Down"&&(t="ArrowDown"),t}const kh=typeof navigator<"u"&&/Mac|iP(hone|[oa]d)/.test(navigator.platform),Sh=typeof navigator<"u"&&/Win/.test(navigator.platform);function xh(n){let e=n.split(/-(?!$)/),t=e[e.length-1];t=="Space"&&(t=" ");let r,i,s,o;for(let l=0;l=t?Y.empty:this.sliceInner(Math.max(0,e),Math.min(this.length,t))};Y.prototype.get=function(e){if(!(e<0||e>=this.length))return this.getInner(e)};Y.prototype.forEach=function(e,t,r){t===void 0&&(t=0),r===void 0&&(r=this.length),t<=r?this.forEachInner(e,t,r,0):this.forEachInvertedInner(e,t,r,0)};Y.prototype.map=function(e,t,r){t===void 0&&(t=0),r===void 0&&(r=this.length);var i=[];return this.forEach(function(s,o){return i.push(e(s,o))},t,r),i};Y.from=function(e){return e instanceof Y?e:e&&e.length?new nc(e):Y.empty};var nc=(function(n){function e(r){n.call(this),this.values=r}n&&(e.__proto__=n),e.prototype=Object.create(n&&n.prototype),e.prototype.constructor=e;var t={length:{configurable:!0},depth:{configurable:!0}};return e.prototype.flatten=function(){return this.values},e.prototype.sliceInner=function(i,s){return i==0&&s==this.length?this:new e(this.values.slice(i,s))},e.prototype.getInner=function(i){return this.values[i]},e.prototype.forEachInner=function(i,s,o,l){for(var a=s;a=o;a--)if(i(this.values[a],l+a)===!1)return!1},e.prototype.leafAppend=function(i){if(this.length+i.length<=or)return new e(this.values.concat(i.flatten()))},e.prototype.leafPrepend=function(i){if(this.length+i.length<=or)return new e(i.flatten().concat(this.values))},t.length.get=function(){return this.values.length},t.depth.get=function(){return 0},Object.defineProperties(e.prototype,t),e})(Y);Y.empty=new nc([]);var Mh=(function(n){function e(t,r){n.call(this),this.left=t,this.right=r,this.length=t.length+r.length,this.depth=Math.max(t.depth,r.depth)+1}return n&&(e.__proto__=n),e.prototype=Object.create(n&&n.prototype),e.prototype.constructor=e,e.prototype.flatten=function(){return this.left.flatten().concat(this.right.flatten())},e.prototype.getInner=function(r){return rl&&this.right.forEachInner(r,Math.max(i-l,0),Math.min(this.length,s)-l,o+l)===!1)return!1},e.prototype.forEachInvertedInner=function(r,i,s,o){var l=this.left.length;if(i>l&&this.right.forEachInvertedInner(r,i-l,Math.max(s,l)-l,o+l)===!1||s=s?this.right.slice(r-s,i-s):this.left.slice(r,s).append(this.right.slice(0,i-s))},e.prototype.leafAppend=function(r){var i=this.right.leafAppend(r);if(i)return new e(this.left,i)},e.prototype.leafPrepend=function(r){var i=this.left.leafPrepend(r);if(i)return new e(i,this.right)},e.prototype.appendInner=function(r){return this.left.depth>=Math.max(this.right.depth,r.depth)+1?new e(this.left,new e(this.right,r)):new e(this,r)},e})(Y);const vh=500;class we{constructor(e,t){this.items=e,this.eventCount=t}popEvent(e,t){if(this.eventCount==0)return null;let r=this.items.length;for(;;r--)if(this.items.get(r-1).selection){--r;break}let i,s;t&&(i=this.remapping(r,this.items.length),s=i.maps.length);let o=e.tr,l,a,c=[],u=[];return this.items.forEach((d,f)=>{if(!d.step){i||(i=this.remapping(r,f+1),s=i.maps.length),s--,u.push(d);return}if(i){u.push(new ve(d.map));let h=d.step.map(i.slice(s)),p;h&&o.maybeStep(h).doc&&(p=o.mapping.maps[o.mapping.maps.length-1],c.push(new ve(p,void 0,void 0,c.length+u.length))),s--,p&&i.appendMap(p,s)}else o.maybeStep(d.step);if(d.selection)return l=i?d.selection.map(i.slice(s)):d.selection,a=new we(this.items.slice(0,r).append(u.reverse().concat(c)),this.eventCount-1),!1},this.items.length,0),{remaining:a,transform:o,selection:l}}addTransform(e,t,r,i){let s=[],o=this.eventCount,l=this.items,a=!i&&l.length?l.get(l.length-1):null;for(let u=0;uTh&&(l=Eh(l,c),o-=c),new we(l.append(s),o)}remapping(e,t){let r=new kn;return this.items.forEach((i,s)=>{let o=i.mirrorOffset!=null&&s-i.mirrorOffset>=e?r.maps.length-i.mirrorOffset:void 0;r.appendMap(i.map,o)},e,t),r}addMaps(e){return this.eventCount==0?this:new we(this.items.append(e.map(t=>new ve(t))),this.eventCount)}rebased(e,t){if(!this.eventCount)return this;t=Math.min(this.items.length,t);let r=[],i=this.items.length-t,s=e.mapping,o=e.steps.length,l=this.eventCount;this.items.forEach(f=>{f.selection&&l--},i);let a=t;this.items.forEach(f=>{let h=s.getMirror(--a);if(h==null)return;o=Math.min(o,h);let p=s.maps[h];if(f.step){let m=e.steps[h].invert(e.docs[h]),g=f.selection&&f.selection.map(s.slice(a+1,h));g&&l++,r.push(new ve(p,m,g))}else r.push(new ve(p))},i);let c=[];for(let f=t;fvh&&(d=d.compress(this.items.length-r.length)),d}emptyItemCount(){let e=0;return this.items.forEach(t=>{t.step||e++}),e}compress(e=this.items.length){let t=this.remapping(0,e),r=t.maps.length,i=[],s=0;return this.items.forEach((o,l)=>{if(l>=e)i.push(o),o.selection&&s++;else if(o.step){let a=o.step.map(t.slice(r)),c=a&&a.getMap();if(r--,c&&t.appendMap(c,r),a){let u=o.selection&&o.selection.map(t.slice(r));u&&s++;let d=new ve(c.invert(),a,u),f,h=i.length-1;(f=i.length&&i[h].merge(d))?i[h]=f:i.push(d)}}else o.map&&r--},this.items.length,0),new we(Y.from(i.reverse()),s)}}we.empty=new we(Y.empty,0);function Eh(n,e){let t;return n.forEach((r,i)=>{if(r.selection&&e--==0)return t=i,!1}),n.slice(t)}class ve{constructor(e,t,r,i){this.map=e,this.step=t,this.selection=r,this.mirrorOffset=i}merge(e){if(this.step&&e.step&&!e.selection){let t=e.step.merge(this.step);if(t)return new ve(t.getMap().invert(),t,this.selection)}}}class Ue{constructor(e,t,r,i,s){this.done=e,this.undone=t,this.prevRanges=r,this.prevTime=i,this.prevComposition=s}}const Th=20;function Ah(n,e,t,r){let i=t.getMeta(nt),s;if(i)return i.historyState;t.getMeta(rc)&&(n=new Ue(n.done,n.undone,null,0,-1));let o=t.getMeta("appendedTransaction");if(t.steps.length==0)return n;if(o&&o.getMeta(nt))return o.getMeta(nt).redo?new Ue(n.done.addTransform(t,void 0,r,Jn(e)),n.undone,Ho(t.mapping.maps),n.prevTime,n.prevComposition):new Ue(n.done,n.undone.addTransform(t,void 0,r,Jn(e)),null,n.prevTime,n.prevComposition);if(t.getMeta("addToHistory")!==!1&&!(o&&o.getMeta("addToHistory")===!1)){let l=t.getMeta("composition"),a=n.prevTime==0||!o&&n.prevComposition!=l&&(n.prevTime<(t.time||0)-r.newGroupDelay||!Oh(t,n.prevRanges)),c=o?pi(n.prevRanges,t.mapping):Ho(t.mapping.maps);return new Ue(n.done.addTransform(t,a?e.selection.getBookmark():void 0,r,Jn(e)),we.empty,c,t.time,l??n.prevComposition)}else return(s=t.getMeta("rebased"))?new Ue(n.done.rebased(t,s),n.undone.rebased(t,s),pi(n.prevRanges,t.mapping),n.prevTime,n.prevComposition):new Ue(n.done.addMaps(t.mapping.maps),n.undone.addMaps(t.mapping.maps),pi(n.prevRanges,t.mapping),n.prevTime,n.prevComposition)}function Oh(n,e){if(!e)return!1;if(!n.docChanged)return!0;let t=!1;return n.mapping.maps[0].forEach((r,i)=>{for(let s=0;s=e[s]&&(t=!0)}),t}function Ho(n){let e=[];for(let t=n.length-1;t>=0&&e.length==0;t--)n[t].forEach((r,i,s,o)=>e.push(s,o));return e}function pi(n,e){if(!n)return null;let t=[];for(let r=0;r{let i=nt.getState(t);if(!i||(n?i.undone:i.done).eventCount==0)return!1;if(r){let s=Nh(i,t,n);s&&r(e?s.scrollIntoView():s)}return!0}}const sc=ic(!1,!0),oc=ic(!0,!0);function Rh(n){return n.getMeta(nt)!=null}function Ur(n){const{state:e,transaction:t}=n;let{selection:r}=t,{doc:i}=t,{storedMarks:s}=t;return{...e,apply:e.apply.bind(e),applyTransaction:e.applyTransaction.bind(e),plugins:e.plugins,schema:e.schema,reconfigure:e.reconfigure.bind(e),toJSON:e.toJSON.bind(e),get storedMarks(){return s},get selection(){return r},get doc(){return i},get tr(){return r=t.selection,i=t.doc,s=t.storedMarks,t}}}var $t=class lc{constructor(e){this.editor=e.editor,this.rawCommands=this.editor.extensionManager.commands,this.customState=e.state}get hasCustomState(){return!!this.customState}get state(){return this.customState||this.editor.state}get commands(){const{rawCommands:e,editor:t,state:r}=this,{view:i}=t,{tr:s}=r,o=this.buildProps(s);return Object.fromEntries(Object.entries(e).map(([l,a])=>[l,(...u)=>{const d=a(...u)(o);return!s.getMeta("preventDispatch")&&!this.hasCustomState&&i.dispatch(s),d}]))}get chain(){return()=>this.createChain()}get can(){return()=>this.createCan()}createChain(e,t=!0){const{rawCommands:r,editor:i,state:s}=this,{view:o}=i,l=[],a=!!e,c=e||s.tr,u=()=>(!a&&t&&!c.getMeta("preventDispatch")&&!this.hasCustomState&&o.dispatch(c),l.every(f=>f===!0)),d={...Object.fromEntries(Object.entries(r).map(([f,h])=>[f,(...m)=>{const g=this.buildProps(c,t),y=h(...m)(g);return l.push(y),d}])),run:u};return d}static createFakeChain(){const e=new Proxy({},{get:(t,r)=>{if(r!=="then")return r==="run"?()=>!1:()=>e}});return e}createCan(e){const{rawCommands:t,state:r}=this,i=!1,s=e||r.tr,o=this.buildProps(s,i);return{...Object.fromEntries(Object.entries(t).map(([l,a])=>[l,(...c)=>a(...c)({...o,dispatch:void 0})])),chain:()=>this.createChain(s,i)}}static createFallbackCan(){const e=lc.createFakeChain();return new Proxy({chain:()=>e},{get:(t,r)=>{if(r!=="then")return r==="chain"?t.chain:()=>!1}})}buildProps(e,t=!0){const{rawCommands:r,editor:i,state:s}=this,{view:o}=i,l={tr:e,editor:i,view:o,state:Ur({state:s,transaction:e}),dispatch:t?()=>{}:void 0,chain:()=>this.createChain(e,t),can:()=>this.createCan(e),get commands(){return Object.fromEntries(Object.entries(r).map(([a,c])=>[a,(...u)=>c(...u)(l)]))}};return l}};const Lh=()=>({editor:n,view:e})=>(requestAnimationFrame(()=>{if(!n.isDestroyed){var t;e.dom.blur(),(t=window)===null||t===void 0||(t=t.getSelection())===null||t===void 0||t.removeAllRanges()}}),!0),Ph=(n=!0)=>({commands:e})=>e.setContent("",{emitUpdate:n}),Bh=()=>({state:n,tr:e,dispatch:t})=>{const{selection:r}=e,{ranges:i}=r;return t&&i.forEach(({$from:s,$to:o})=>{n.doc.nodesBetween(s.pos,o.pos,(l,a)=>{if(l.type.isText)return;const{doc:c,mapping:u}=e,d=c.resolve(u.map(a)),f=c.resolve(u.map(a+l.nodeSize)),h=d.blockRange(f);if(!h)return;const p=Ut(h);if(l.type.isTextblock){const{defaultType:m}=d.parent.contentMatchAt(d.index());e.setNodeMarkup(h.start,m)}(p||p===0)&&e.lift(h,p)})}),!0},zh=n=>e=>n(e),$h=()=>({state:n,dispatch:e})=>pa(n,e),Fh=(n,e)=>({editor:t,tr:r})=>{const{state:i}=t,s=i.doc.slice(n.from,n.to);r.deleteRange(n.from,n.to);const o=r.mapping.map(e);return r.insert(o,s.content),r.setSelection(new T(r.doc.resolve(Math.max(o-1,0)))),!0},Vh=()=>({tr:n,dispatch:e})=>{const{selection:t}=n,r=t.$anchor.node();if(r.content.size>0)return!1;const i=n.selection.$anchor;for(let s=i.depth;s>0;s-=1)if(i.node(s).type===r.type){if(e){const o=i.before(s),l=i.after(s);n.delete(o,l).scrollIntoView()}return!0}return!1};function q(n,e){if(typeof n=="string"){if(!e.nodes[n])throw Error(`There is no node type named '${n}'. Maybe you forgot to add the extension?`);return e.nodes[n]}return n}const Hh=n=>({tr:e,state:t,dispatch:r})=>{const i=q(n,t.schema),s=e.selection.$anchor;for(let o=s.depth;o>0;o-=1)if(s.node(o).type===i){if(r){const l=s.before(o),a=s.after(o);e.delete(l,a).scrollIntoView()}return!0}return!1},jh=n=>({tr:e,dispatch:t})=>{const{from:r,to:i}=n;return t&&e.delete(r,i),!0},Wh=n=>n.content?/^text(\*|\+)/.test(n.content):!1,Wo=(n,e,t)=>{if(!n.parent.isInline||t==="left"&&n.pos>n.start()||t==="right"&&n.pos({from:Wo(n,t,"left"),to:Wo(e,t,"right")}),_h=()=>({state:n,dispatch:e})=>{if(n.selection.empty)return!1;if(e){const t=n.tr,{ranges:r}=n.selection,i=t.steps.length;r.forEach(s=>{const o=t.mapping.slice(i),l=t.doc.resolve(o.map(s.$from.pos)),a=t.doc.resolve(o.map(s.$to.pos)),{from:c,to:u}=Kh(l,a,n.schema);t.deleteRange(c,u)}),t.selection.empty||t.setSelection(T.near(t.doc.resolve(t.selection.from))),t.scrollIntoView(),e(t)}return!0},Uh=()=>({commands:n})=>n.keyboardShortcut("Enter"),qh=()=>({state:n,dispatch:e})=>yd(n,e);function Cs(n){return Object.prototype.toString.call(n)==="[object RegExp]"}function lr(n,e,t={strict:!0}){const r=Object.keys(e);return r.length?r.every(i=>t.strict?e[i]===n[i]:Cs(e[i])?e[i].test(n[i]):e[i]===n[i]):!0}function ac(n,e,t={}){return n.find(r=>r.type===e&&lr(Object.fromEntries(Object.keys(t).map(i=>[i,r.attrs[i]])),t))}function Ko(n,e,t={}){return!!ac(n,e,t)}function Ms(n,e,t){if(!n||!e)return;let r=n.parent.childAfter(n.parentOffset);if((!r.node||!r.node.marks.some(a=>a.type===e))&&(r=n.parent.childBefore(n.parentOffset)),!r.node||!r.node.marks.some(a=>a.type===e))return;if(!t){const a=r.node.marks.find(c=>c.type===e);a&&(t=a.attrs)}if(!ac([...r.node.marks],e,t))return;let i=r.index,s=n.start()+r.offset,o=i+1,l=s+r.node.nodeSize;for(;i>0&&Ko([...n.parent.child(i-1).marks],e,t);)i-=1,s-=n.parent.child(i).nodeSize;for(;o({tr:t,state:r,dispatch:i})=>{const s=je(n,r.schema),{doc:o,selection:l}=t,{$from:a,from:c,to:u}=l;if(i){const d=Ms(a,s,e);if(d&&d.from<=c&&d.to>=u){const f=T.create(o,d.from,d.to);t.setSelection(f)}}return!0},Gh=n=>e=>{const t=typeof n=="function"?n(e):n;for(let r=0;r({editor:t,view:r,tr:i,dispatch:s})=>{e={scrollIntoView:!0,...e};const o=()=>{(ar()||_o())&&r.dom.focus(),Yh()&&!ar()&&!_o()&&r.dom.focus({preventScroll:!0}),requestAnimationFrame(()=>{t.isDestroyed||(r.focus(),e?.scrollIntoView&&t.commands.scrollIntoView())})};try{if(r.hasFocus()&&n===null||n===!1)return!0}catch{return!1}if(s&&n===null&&!cc(t.state.selection))return o(),!0;const l=Ki(i.doc,n)||t.state.selection,a=t.state.selection.eq(l);return s&&(a||i.setSelection(l),a&&i.storedMarks&&i.setStoredMarks(i.storedMarks),o()),!0},Qh=(n,e)=>t=>n.every((r,i)=>e(r,{...t,index:i})),Zh=(n,e)=>({tr:t,commands:r})=>r.insertContentAt({from:t.selection.from,to:t.selection.to},n,e),uc=n=>{const e=n.childNodes;for(let t=e.length-1;t>=0;t-=1){const r=e[t];r.nodeType===3&&r.nodeValue&&/^(\n\s\s|\n)$/.test(r.nodeValue)?n.removeChild(r):r.nodeType===1&&uc(r)}return n};function zn(n){if(typeof window>"u")throw new Error("[tiptap error]: there is no window object available, so this function cannot be used");const e=`${n}`,t=new window.DOMParser().parseFromString(e,"text/html").body;return uc(t)}function dc(n){return typeof n?.nodesBetween=="function"}function Wt(n,e,t){if(dc(n))return n;const r=typeof n=="object"&&n!==null;t={slice:!0,parseOptions:{},...t};const i=typeof n=="string";if(r)try{if(Array.isArray(n)&&n.length>0)return b.fromArray(n.map(o=>e.nodeFromJSON(o)));const s=e.nodeFromJSON(n);return t.errorOnInvalidContent&&s.check(),s}catch(s){if(t.errorOnInvalidContent)throw new Error("[tiptap error]: Invalid JSON content",{cause:s});return console.warn("[tiptap warn]: Invalid content.","Passed value:",n,"Error:",s),Wt("",e,t)}if(i){if(t.errorOnInvalidContent){let o=!1,l="";const a=new Vl({topNode:e.spec.topNode,marks:e.spec.marks,nodes:e.spec.nodes.append({__tiptap__private__unknown__catch__all__node:{content:"inline*",group:"block",parseDOM:[{tag:"*",getAttrs:c=>(o=!0,l=typeof c=="string"?c:c.outerHTML,null)}]}})});if(t.slice?Xe.fromSchema(a).parseSlice(zn(n),t.parseOptions):Xe.fromSchema(a).parse(zn(n),t.parseOptions),t.errorOnInvalidContent&&o)throw new Error("[tiptap error]: Invalid HTML content",{cause:new Error(`Invalid element found: ${l}`)})}const s=Xe.fromSchema(e);return t.slice?s.parseSlice(zn(n),t.parseOptions).content:s.parse(zn(n),t.parseOptions)}return Wt("",e,t)}function fc(n){return!("type"in n)}function hc(n,e,t){const r=n.steps.length-1;if(r{o===0&&(o=u)}),n.setSelection(O.near(n.doc.resolve(o),t))}const ep=(n,e,t)=>({tr:r,dispatch:i,editor:s})=>{if(i){t={parseOptions:s.options.parseOptions,updateSelection:!0,applyInputRules:!1,applyPasteRules:!1,...t};let l;const a=g=>{s.emit("contentError",{editor:s,error:g,disableCollaboration:()=>{"collaboration"in s.storage&&typeof s.storage.collaboration=="object"&&s.storage.collaboration&&(s.storage.collaboration.isDisabled=!0)}})},c={preserveWhitespace:"full",...t.parseOptions};if(!t.errorOnInvalidContent&&!s.options.enableContentCheck&&s.options.emitContentError)try{Wt(e,s.schema,{parseOptions:c,errorOnInvalidContent:!0})}catch(g){a(g)}try{var o;l=Wt(e,s.schema,{parseOptions:c,errorOnInvalidContent:(o=t.errorOnInvalidContent)!==null&&o!==void 0?o:s.options.enableContentCheck})}catch(g){return a(g),!1}let{from:u,to:d}=typeof n=="number"?{from:n,to:n}:{from:n.from,to:n.to},f=!0,h=!0;const p=fc(l)?l.content:[l];if(p.forEach(g=>{g.check(),f=f?g.isText&&g.marks.length===0:!1,h=h?g.isBlock:!1}),u===d&&h){const{parent:g}=r.doc.resolve(u);g.isTextblock&&!g.type.spec.code&&!g.childCount&&(u-=1,d+=1)}let m;if(f)Array.isArray(e)?m=e.map(g=>g.text||"").join(""):dc(e)?m=p.map(g=>{var y;return(y=g.text)!==null&&y!==void 0?y:""}).join(""):typeof e=="object"&&e&&e.text?m=e.text:m=e,r.insertText(m,u,d);else{m=b.from(p);const g=r.doc.resolve(u),y=g.node(),S=g.parentOffset===0,x=y.isText||y.isTextblock,C=y.content.size>0;S&&x&&C&&h&&(u=Math.max(0,u-1)),r.replaceWith(u,d,p)}t.updateSelection&&hc(r,r.steps.length-1,-1),t.applyInputRules&&r.setMeta("applyInputRules",{from:u,text:m}),t.applyPasteRules&&r.setMeta("applyPasteRules",{from:u,text:m})}return!0};function pc(n){for(let e=0;e({tr:e,dispatch:t,editor:r})=>{const{pos:i,attrs:s,content:o,updateSelection:l=!0}=n;let a;typeof i=="number"?a=e.doc.resolve(i):i?a=i:a=e.selection.$from;const c=pc(a.parent.contentMatchAt(a.index()));if(!c)return!1;const u=Object.keys(c.spec.attrs||{}),d=s?Object.fromEntries(Object.entries(s).filter(([h])=>u.includes(h))):{};let f;if(o){const h=Wt(o,r.schema);f=c.createAndFill(d,h)}else f=c.createAndFill(d);return f?(t&&(e.insert(a.pos,f),l&&hc(e,e.steps.length-1,-1)),!0):!1},np=()=>({state:n,dispatch:e})=>pd(n,e),rp=()=>({state:n,dispatch:e})=>md(n,e),ip=()=>({state:n,dispatch:e})=>la(n,e),sp=()=>({state:n,dispatch:e})=>da(n,e),mc=(n,e)=>{const t=n.resolve(e),r=t.nodeBefore,i=t.nodeAfter;return!r||!i?!1:!r.type.spec.isolating&&!i.type.spec.isolating},op=()=>({state:n,dispatch:e,tr:t})=>{try{const r=Vr(n.doc,n.selection.$from.pos,-1);return r==null||!mc(n.doc,r)?!1:(t.join(r,2),e&&e(t),!0)}catch{return!1}},lp=()=>({state:n,dispatch:e,tr:t})=>{try{const r=Vr(n.doc,n.selection.$from.pos,1);return r==null||!mc(n.doc,r)?!1:(t.join(r,2),e&&e(t),!0)}catch{return!1}},ap=()=>({state:n,dispatch:e})=>fd(n,e),cp=()=>({state:n,dispatch:e})=>hd(n,e);function gc(){return typeof navigator<"u"?/Mac/.test(navigator.platform):!1}function up(n){const e=n.split(/-(?!$)/);let t=e[e.length-1];t==="Space"&&(t=" ");let r,i,s,o;for(let l=0;l({editor:e,view:t,tr:r,dispatch:i})=>{const s=up(n).split(/-(?!$)/),o=s.find(c=>!["Alt","Ctrl","Meta","Shift"].includes(c)),l=new KeyboardEvent("keydown",{key:o==="Space"?" ":o,altKey:s.includes("Alt"),ctrlKey:s.includes("Ctrl"),metaKey:s.includes("Meta"),shiftKey:s.includes("Shift"),bubbles:!0,cancelable:!0}),a=e.captureTransaction(()=>{t.someProp("handleKeyDown",c=>c(t,l))});return a?.steps.forEach(c=>{const u=c.map(r.mapping);u&&i&&r.maybeStep(u)}),!0};function He(n,e,t={}){const{from:r,to:i,empty:s}=n.selection,o=e?q(e,n.schema):null,l=[];n.doc.nodesBetween(r,i,(u,d)=>{if(u.isText)return;const f=Math.max(r,d),h=Math.min(i,d+u.nodeSize);l.push({node:u,from:f,to:h})});const a=i-r,c=l.filter(u=>o?o.name===u.node.type.name:!0).filter(u=>lr(u.node.attrs,t,{strict:!1}));return s?!!c.length:c.reduce((u,d)=>u+d.to-d.from,0)>=a}const fp=(n,e={})=>({state:t,dispatch:r})=>He(t,q(n,t.schema),e)?gd(t,r):!1,hp=()=>({state:n,dispatch:e})=>ma(n,e),pp=n=>({state:e,dispatch:t})=>{const r=q(n,e.schema);return Ad(r)(e,t)},mp=()=>({state:n,dispatch:e})=>ha(n,e);function qr(n,e){return e.nodes[n]?"node":e.marks[n]?"mark":null}function Uo(n,e){const t=typeof e=="string"?[e]:e;return Object.keys(n).reduce((r,i)=>(t.includes(i)||(r[i]=n[i]),r),{})}const gp=(n,e)=>({tr:t,state:r,dispatch:i})=>{let s=null,o=null;const l=qr(typeof n=="string"?n:n.name,r.schema);if(!l)return!1;l==="node"&&(s=q(n,r.schema)),l==="mark"&&(o=je(n,r.schema));let a=!1;return t.selection.ranges.forEach(c=>{r.doc.nodesBetween(c.$from.pos,c.$to.pos,(u,d)=>{s&&s===u.type&&(a=!0,i&&t.setNodeMarkup(d,void 0,Uo(u.attrs,e))),o&&u.marks.length&&u.marks.forEach(f=>{o===f.type&&(a=!0,i&&t.addMark(d,d+u.nodeSize,o.create(Uo(f.attrs,e))))})})}),a},yp=()=>({tr:n,dispatch:e})=>(e&&n.scrollIntoView(),!0),bp=()=>({tr:n,dispatch:e})=>{if(e){const t=new fe(n.doc);n.setSelection(t)}return!0},kp=()=>({state:n,dispatch:e})=>ca(n,e),Sp=()=>({state:n,dispatch:e})=>fa(n,e),xp=()=>({state:n,dispatch:e})=>Sd(n,e),wp=()=>({state:n,dispatch:e})=>Cd(n,e),Cp=()=>({state:n,dispatch:e})=>wd(n,e);function _i(n,e,t={},r={}){return Wt(n,e,{slice:!1,parseOptions:t,errorOnInvalidContent:r.errorOnInvalidContent})}const Mp=(n,{errorOnInvalidContent:e,emitUpdate:t=!0,parseOptions:r={}}={})=>({editor:i,tr:s,dispatch:o,commands:l})=>{const{doc:a}=s;if(r.preserveWhitespace!=="full"){const c=_i(n,i.schema,r,{errorOnInvalidContent:e??i.options.enableContentCheck});if(o){const u=fc(c)?c.content:[c];s.replaceWith(0,a.content.size,u).setMeta("preventUpdate",!t)}return!0}return o&&s.setMeta("preventUpdate",!t),l.insertContentAt({from:0,to:a.content.size},n,{parseOptions:r,errorOnInvalidContent:e??i.options.enableContentCheck})};function yc(n,e){const t=je(e,n.schema),{from:r,to:i,empty:s}=n.selection,o=[];s?(n.storedMarks&&o.push(...n.storedMarks),o.push(...n.selection.$head.marks())):n.doc.nodesBetween(r,i,a=>{o.push(...a.marks)});const l=o.find(a=>a.type.name===t.name);return l?{...l.attrs}:{}}function bc(n,e){const t=new na(n);return e.forEach(r=>{r.steps.forEach(i=>{t.step(i)})}),t}function vp(n,e,t){const r=[];return n.nodesBetween(e.from,e.to,(i,s)=>{t(i)&&r.push({node:i,pos:s})}),r}function Ep(n,e){for(let t=n.depth;t>0;t-=1){const r=n.node(t);if(e(r))return{pos:t>0?n.before(t):0,start:n.start(t),depth:t,node:r}}}function Jr(n){return e=>Ep(e.$from,n)}function M(n,e,t){return n.config[e]===void 0&&n.parent?M(n.parent,e,t):typeof n.config[e]=="function"?n.config[e].bind({...t,parent:n.parent?M(n.parent,e,t):null}):n.config[e]}function vs(n){return n.map(e=>{const t=M(e,"addExtensions",{name:e.name,options:e.options,storage:e.storage});return t?[e,...vs(t())]:e}).flat(10)}function Es(n,e){const t=st.fromSchema(e).serializeFragment(n),r=document.implementation.createHTMLDocument().createElement("div");return r.appendChild(t),r.innerHTML}function Ui(n){return typeof n=="function"}function L(n,e=void 0,...t){return Ui(n)?e?n.bind(e)(...t):n(...t):n}function Tp(n={}){return Object.keys(n).length===0&&n.constructor===Object}function Kt(n){return{baseExtensions:n.filter(e=>e.type==="extension"),nodeExtensions:n.filter(e=>e.type==="node"),markExtensions:n.filter(e=>e.type==="mark")}}function kc(n){const e=[],{nodeExtensions:t,markExtensions:r}=Kt(n),i=[...t,...r],s={default:null,validate:void 0,rendered:!0,renderHTML:null,parseHTML:null,keepOnSplit:!0,isRequired:!1},o=t.filter(c=>c.name!=="text").map(c=>c.name),l=r.map(c=>c.name),a=[...o,...l];return n.forEach(c=>{const u=M(c,"addGlobalAttributes",{name:c.name,options:c.options,storage:c.storage,extensions:i});u&&u().forEach(d=>{let f;Array.isArray(d.types)?f=d.types:d.types==="*"?f=a:d.types==="nodes"?f=o:d.types==="marks"?f=l:f=[],f.forEach(h=>{Object.entries(d.attributes).forEach(([p,m])=>{e.push({type:h,name:p,attribute:{...s,...m}})})})})}),i.forEach(c=>{const u=M(c,"addAttributes",{name:c.name,options:c.options,storage:c.storage});if(!u)return;const d=u();Object.entries(d).forEach(([f,h])=>{const p={...s,...h};typeof p?.default=="function"&&(p.default=p.default()),p?.isRequired&&p?.default===void 0&&delete p.default,e.push({type:c.name,name:f,attribute:p})})}),e}function Ap(n){const e=[];let t="",r=!1,i=!1,s=0;const o=n.length;for(let l=0;l0){s-=1,t+=a;continue}if(a===";"&&s===0){e.push(t),t="";continue}}t+=a}return t&&e.push(t),e}function qo(n){const e=[],t=Ap(n||""),r=t.length;for(let i=0;i!!e).reduce((e,t)=>{const r={...e};return Object.entries(t).forEach(([i,s])=>{if(i==="__proto__"){Object.defineProperty(r,i,{configurable:!0,enumerable:!0,value:s,writable:!0});return}if(!r[i]){r[i]=s;return}if(i==="class"){const o=s?String(s).split(" "):[],l=r[i]?r[i].split(" "):[],a=o.filter(c=>!l.includes(c));r[i]=[...l,...a].join(" ")}else if(i==="style"){const o=new Map([...qo(r[i]),...qo(s)]);r[i]=Array.from(o.entries()).map(([l,a])=>`${l}: ${a}`).join("; ")}else r[i]=s}),r},{})}function Mn(n,e){return e.filter(t=>t.type===n.type.name).filter(t=>t.attribute.rendered).map(t=>t.attribute.renderHTML?t.attribute.renderHTML(n.attrs)||{}:{[t.name]:n.attrs[t.name]}).reduce((t,r)=>J(t,r),{})}function Op(n){return typeof n!="string"?n:n.match(/^[+-]?(?:\d*\.)?\d+$/)?Number(n):n==="true"?!0:n==="false"?!1:n}function Jo(n,e){return"style"in n?n:{...n,getAttrs:t=>{const r=n.getAttrs?n.getAttrs(t):n.attrs;if(r===!1)return!1;const i=e.reduce((s,o)=>{const l=o.attribute.parseHTML?o.attribute.parseHTML(t):Op(t.getAttribute(o.name));return l==null?s:{...s,[o.name]:l}},{});return{...r,...i}}}}function Go(n){return Object.fromEntries(Object.entries(n).filter(([e,t])=>e==="attrs"&&Tp(t)?!1:t!=null))}function Yo(n){var e,t;const r={};return!(!(n==null||(e=n.attribute)===null||e===void 0)&&e.isRequired)&&"default"in(n?.attribute||{})&&(r.default=n.attribute.default),(n==null||(t=n.attribute)===null||t===void 0?void 0:t.validate)!==void 0&&(r.validate=n.attribute.validate),[n.name,r]}function Np(n,e){var t;const r=kc(n),{nodeExtensions:i,markExtensions:s}=Kt(n),o=(t=i.find(c=>M(c,"topNode")))===null||t===void 0?void 0:t.name,l=Object.fromEntries(i.map(c=>{const u=r.filter(g=>g.type===c.name),d={name:c.name,options:c.options,storage:c.storage,editor:e},f=Go({...n.reduce((g,y)=>{const S=M(y,"extendNodeSchema",d);return{...g,...S?S(c):{}}},{}),content:L(M(c,"content",d)),marks:L(M(c,"marks",d)),group:L(M(c,"group",d)),inline:L(M(c,"inline",d)),atom:L(M(c,"atom",d)),selectable:L(M(c,"selectable",d)),draggable:L(M(c,"draggable",d)),code:L(M(c,"code",d)),whitespace:L(M(c,"whitespace",d)),linebreakReplacement:L(M(c,"linebreakReplacement",d)),defining:L(M(c,"defining",d)),isolating:L(M(c,"isolating",d)),attrs:Object.fromEntries(u.map(Yo))}),h=L(M(c,"parseHTML",d));h&&(f.parseDOM=h.map(g=>Jo(g,u)));const p=M(c,"renderHTML",d);p&&(f.toDOM=g=>p({node:g,HTMLAttributes:Mn(g,u)}));const m=M(c,"renderText",d);return m&&(f.toText=m),[c.name,f]})),a=Object.fromEntries(s.map(c=>{const u=r.filter(m=>m.type===c.name),d={name:c.name,options:c.options,storage:c.storage,editor:e},f=Go({...n.reduce((m,g)=>{const y=M(g,"extendMarkSchema",d);return{...m,...y?y(c):{}}},{}),inclusive:L(M(c,"inclusive",d)),excludes:L(M(c,"excludes",d)),group:L(M(c,"group",d)),spanning:L(M(c,"spanning",d)),code:L(M(c,"code",d)),attrs:Object.fromEntries(u.map(Yo))}),h=L(M(c,"parseHTML",d));h&&(f.parseDOM=h.map(m=>Jo(m,u)));const p=M(c,"renderHTML",d);return p&&(f.toDOM=m=>p({mark:m,HTMLAttributes:Mn(m,u)})),[c.name,f]}));return new Vl({topNode:o,nodes:l,marks:a})}function Dp(n){const e=n.filter((t,r)=>n.indexOf(t)!==r);return Array.from(new Set(e))}function ln(n){return n.sort((t,r)=>{const i=M(t,"priority")||100,s=M(r,"priority")||100;return i>s?-1:ir.name));return t.length&&console.warn(`[tiptap warn]: Duplicate extension names found: [${t.map(r=>`'${r}'`).join(", ")}]. This can lead to issues.`),e}function xc(n,e,t){const{from:r,to:i}=e,{blockSeparator:s=` +`);return{dom:a,text:f,slice:e}}function Wc(n,e,t,r,i){let s=i.parent.type.spec.code,o,l;if(!t&&!e)return null;let a=!!e&&(r||s||!t);if(a){if(n.someProp("transformPastedText",f=>{e=f(e,s||r,n)}),s)return l=new x(b.from(n.state.schema.text(e.replace(/\r\n?/g,` +`))),0,0),n.someProp("transformPasted",f=>{l=f(l,n,!0)}),l;let d=n.someProp("clipboardTextParser",f=>f(e,i,r,n));if(d)l=d;else{let f=i.marks(),{schema:h}=n.state,p=ht.fromSchema(h);o=document.createElement("div"),e.split(/(?:\r\n?|\n)+/).forEach(m=>{let g=o.appendChild(document.createElement("p"));m&&g.appendChild(p.serializeNode(h.text(m,f)))})}}else n.someProp("transformPastedHTML",d=>{t=d(t,n)}),o=ip(t),pi&&sp(o);let c=o&&o.querySelector("[data-pm-slice]"),u=c&&/^(\d+) (\d+)(?: -(\d+))? (.*)/.exec(c.getAttribute("data-pm-slice")||"");if(u&&u[3])for(let d=+u[3];d>0;d--){let f=o.firstChild;for(;f&&!A(f);)f=f.nextSibling;if(!f)break;o=f}if(l||(l=(n.someProp("clipboardParser")||n.someProp("domParser")||Ke.fromSchema(n.state.schema)).parseSlice(o,{preserveWhitespace:!!(a||u),context:i,ruleFromNode(f){return f.nodeName=="BR"&&!f.nextSibling&&f.parentNode&&!tp.test(f.parentNode.nodeName)?{ignore:!0}:null}})),u)l=op(gl(l,+u[1],+u[2]),u[4]);else if(l=x.maxOpen(np(l.content,i),!0),l.openStart||l.openEnd){let d=0,f=0;for(let h=l.content.firstChild;d{l=d(l,n,a)}),l}const tp=/^(a|abbr|acronym|b|cite|code|del|em|i|ins|kbd|label|output|q|ruby|s|samp|span|strong|sub|sup|time|u|tt|var)$/i;function np(n,e){if(n.childCount<2)return n;for(let t=e.depth;t>=0;t--){let i=e.node(t).contentMatchAt(e.index(t)),s,o=[];if(n.forEach(l=>{if(!o)return;let a=i.findWrapping(l.type),c;if(!a)return o=null;if(c=o.length&&s.length&&_c(a,s,l,o[o.length-1],0))o[o.length-1]=c;else{o.length&&(o[o.length-1]=Uc(o[o.length-1],s.length));let u=jc(l,a);o.push(u),i=i.matchType(u.type),s=a}}),o)return b.from(o)}return n}function jc(n,e,t=0){for(let r=e.length-1;r>=t;r--)n=e[r].create(null,b.from(n));return n}function _c(n,e,t,r,i){if(i1&&(s=0),i=t&&(l=e<0?o.contentMatchAt(0).fillBefore(l,s<=i).append(l):l.append(o.contentMatchAt(o.childCount).fillBefore(b.empty,!0))),n.replaceChild(e<0?0:n.childCount-1,o.copy(l))}function gl(n,e,t){return et})}return an.createHTML(n)}function ip(n){let e=/^(\s*]*>)*/.exec(n);e&&(n=n.slice(e[0].length));let t=qc(),r=t.body,i=/<([a-z][^>\s]+)/i.exec(n),s;if((s=i&&Kc[i[1].toLowerCase()])&&(n=s.map(o=>"<"+o+">").join("")+n+s.map(o=>"").reverse().join("")),r.innerHTML=rp(n),s)for(let o=0;o=0;l-=2){let a=t.nodes[r[l]];if(!a||a.hasRequiredAttrs())break;try{i=b.from(a.create(r[l+1],i))}catch{break}s++,o++}return new x(i,s,o)}const de={},fe={},lp={touchstart:!0,touchmove:!0};class ap{constructor(){this.shiftKey=!1,this.mouseDown=null,this.lastKeyCode=null,this.lastKeyCodeTime=0,this.lastClick={time:0,x:0,y:0,type:"",button:0},this.lastSelectionOrigin=null,this.lastSelectionTime=0,this.lastIOSEnter=0,this.lastIOSEnterFallbackTimeout=-1,this.lastFocus=0,this.lastTouch=0,this.lastChromeDelete=0,this.composing=!1,this.compositionNode=null,this.composingTimeout=-1,this.compositionNodes=[],this.compositionEndedAt=-2e8,this.compositionID=1,this.badSafariComposition=!1,this.compositionPendingChanges=0,this.domChangeCount=0,this.eventHandlers=Object.create(null),this.hideSelectionGuard=null}}function cp(n){for(let e in de){let t=de[e];n.dom.addEventListener(e,n.input.eventHandlers[e]=r=>{dp(n,r)&&!no(n,r)&&(n.editable||!(r.type in fe))&&t(n,r)},lp[e]?{passive:!0}:void 0)}ae&&n.dom.addEventListener("input",()=>null),ks(n)}function Ue(n,e){n.input.lastSelectionOrigin=e,n.input.lastSelectionTime=Date.now()}function up(n){n.input.mouseDown&&n.input.mouseDown.done(),n.domObserver.stop();for(let e in n.input.eventHandlers)n.dom.removeEventListener(e,n.input.eventHandlers[e]);clearTimeout(n.input.composingTimeout),clearTimeout(n.input.lastIOSEnterFallbackTimeout)}function ks(n){n.someProp("handleDOMEvents",e=>{for(let t in e)n.input.eventHandlers[t]||n.dom.addEventListener(t,n.input.eventHandlers[t]=r=>no(n,r))})}function no(n,e){return n.someProp("handleDOMEvents",t=>{let r=t[e.type];return r?r(n,e)||e.defaultPrevented:!1})}function dp(n,e){if(!e.bubbles)return!0;if(e.defaultPrevented)return!1;for(let t=e.target;t!=n.dom;t=t.parentNode)if(!t||t.nodeType==11||t.pmViewDesc&&t.pmViewDesc.stopEvent(e))return!1;return!0}function fp(n,e){!no(n,e)&&de[e.type]&&(n.editable||!(e.type in fe))&&de[e.type](n,e)}fe.keydown=(n,e)=>{let t=e;if(n.input.shiftKey=t.keyCode==16||t.shiftKey,!Xc(n)&&(n.input.lastKeyCode=t.keyCode,n.input.lastKeyCodeTime=Date.now(),!(_e&&se&&t.keyCode==13)))if(t.keyCode!=229&&n.domObserver.forceFlush(),en&&t.keyCode==13&&!t.ctrlKey&&!t.altKey&&!t.metaKey){let r=Date.now();n.input.lastIOSEnter=r,n.input.lastIOSEnterFallbackTimeout=setTimeout(()=>{n.input.lastIOSEnter==r&&(n.someProp("handleKeyDown",i=>i(n,kt(13,"Enter"))),n.input.lastIOSEnter=0)},200)}else n.someProp("handleKeyDown",r=>r(n,t))||ep(n,t)?t.preventDefault():Ue(n,"key")};fe.keyup=(n,e)=>{e.keyCode==16&&(n.input.shiftKey=!1)};fe.keypress=(n,e)=>{let t=e;if(Xc(n)||!t.charCode||t.ctrlKey&&!t.altKey||Ce&&t.metaKey)return;if(n.someProp("handleKeyPress",i=>i(n,t))){t.preventDefault();return}let r=n.state.selection;if(!(r instanceof v)||!r.$from.sameParent(r.$to)){let i=String.fromCharCode(t.charCode),s=()=>n.state.tr.insertText(i).scrollIntoView();!/[\r\n]/.test(i)&&!n.someProp("handleTextInput",o=>o(n,r.$from.pos,r.$to.pos,i,s))&&n.dispatch(s()),t.preventDefault()}};function Kn(n){return{left:n.clientX,top:n.clientY}}function hp(n,e){let t=e.x-n.clientX,r=e.y-n.clientY;return t*t+r*r<100}function ro(n,e,t,r,i){if(r==-1)return!1;let s=n.state.doc.resolve(r);for(let o=s.depth+1;o>0;o--)if(n.someProp(e,l=>o>s.depth?l(n,t,s.nodeAfter,s.before(o),i,!0):l(n,t,s.node(o),s.before(o),i,!1)))return!0;return!1}function qn(n,e,t){if(n.focused||n.focus(),n.state.selection.eq(e))return;let r=n.state.tr.setSelection(e);r.setMeta("pointer",!0),n.dispatch(r)}function pp(n,e){if(e==-1)return!1;let t=n.state.doc.resolve(e),r=t.nodeAfter;return r&&r.isAtom&&T.isSelectable(r)?(qn(n,new T(t)),!0):!1}function mp(n,e){if(e==-1)return!1;let t=n.state.selection,r,i;t instanceof T&&(r=t.node);let s=n.state.doc.resolve(e);for(let o=s.depth+1;o>0;o--){let l=o>s.depth?s.nodeAfter:s.node(o);if(T.isSelectable(l)){r&&t.$from.depth>0&&o>=t.$from.depth&&s.before(t.$from.depth+1)==t.$from.pos?i=s.before(t.$from.depth):i=s.before(o);break}}return i!=null?(qn(n,T.create(n.state.doc,i)),!0):!1}function gp(n,e,t,r,i){return ro(n,"handleClickOn",e,t,r)||n.someProp("handleClick",s=>s(n,e,r))||(i?mp(n,t):pp(n,t))}function yp(n,e,t,r){return ro(n,"handleDoubleClickOn",e,t,r)||n.someProp("handleDoubleClick",i=>i(n,e,r))}function bp(n,e,t,r){return ro(n,"handleTripleClickOn",e,t,r)||n.someProp("handleTripleClick",i=>i(n,e,r))||kp(n,t,r)}function kp(n,e,t){if(t.button!=0)return!1;let r=Jc(n,e,!0),i=n.state.doc;return r?(qn(n,r),r instanceof v&&i.eq(n.state.doc)&&(n.input.mouseDown=new Sp(n,r)),!0):!1}function Jc(n,e,t){let r=n.state.doc;if(e==-1)return r.inlineContent?v.create(r,0,r.content.size):null;let i=r.resolve(e);for(let s=i.depth+1;s>0;s--){let o=s>i.depth?i.nodeAfter:i.node(s),l=i.before(s);if(o.inlineContent)return v.create(r,l+1,l+1+o.content.size);if(t&&T.isSelectable(o))return T.create(r,l)}return null}function io(n){return vr(n)}const Gc=Ce?"metaKey":"ctrlKey";de.mousedown=(n,e)=>{let t=e;n.input.shiftKey=t.shiftKey;let r=io(n),i=Date.now(),s="singleClick";i-n.input.lastClick.time<500&&hp(t,n.input.lastClick)&&!t[Gc]&&n.input.lastClick.button==t.button&&(n.input.lastClick.type=="singleClick"?s="doubleClick":n.input.lastClick.type=="doubleClick"&&(s="tripleClick")),n.input.lastClick={time:i,x:t.clientX,y:t.clientY,type:s,button:t.button},n.input.mouseDown&&n.input.mouseDown.done();let o=n.posAtCoords(Kn(t));o&&(s=="singleClick"?n.input.mouseDown=new wp(n,o,t,!!r):(s=="doubleClick"?yp:bp)(n,o.pos,o.inside,t)?t.preventDefault():Ue(n,"pointer"))};class Yc{constructor(e){this.view=e,this.mightDrag=null,e.root.addEventListener("mouseup",this.up=this.up.bind(this)),e.root.addEventListener("mousemove",this.move=this.move.bind(this))}up(e){this.done()}move(e){e.buttons==0&&this.done()}done(){this.view.root.removeEventListener("mouseup",this.up),this.view.root.removeEventListener("mousemove",this.move),this.view.input.mouseDown==this&&(this.view.input.mouseDown=null)}delaySelUpdate(){return!1}}class wp extends Yc{constructor(e,t,r,i){super(e),this.pos=t,this.event=r,this.flushed=i,this.delayedSelectionSync=!1,this.startDoc=e.state.doc,this.selectNode=!!r[Gc],this.allowDefault=r.shiftKey;let s,o;if(t.inside>-1)s=e.state.doc.nodeAt(t.inside),o=t.inside;else{let u=e.state.doc.resolve(t.pos);s=u.parent,o=u.depth?u.before():0}const l=i?null:r.target,a=l?e.docView.nearestDesc(l,!0):null;this.target=a&&A(a.nodeDOM)?a.nodeDOM:null;let{selection:c}=e.state;r.button==0&&(s.type.spec.draggable&&s.type.spec.selectable!==!1||c instanceof T&&c.from<=o&&c.to>o)&&(this.mightDrag={node:s,pos:o,addAttr:!!(this.target&&!this.target.draggable),setUneditable:!!(this.target&&be&&!this.target.hasAttribute("contentEditable"))}),this.target&&this.mightDrag&&(this.mightDrag.addAttr||this.mightDrag.setUneditable)&&(this.view.domObserver.stop(),this.mightDrag.addAttr&&(this.target.draggable=!0),this.mightDrag.setUneditable&&setTimeout(()=>{this.view.input.mouseDown==this&&this.target.setAttribute("contentEditable","false")},20),this.view.domObserver.start()),Ue(e,"pointer")}done(){super.done(),this.mightDrag&&this.target&&(this.view.domObserver.stop(),this.mightDrag.addAttr&&this.target.removeAttribute("draggable"),this.mightDrag.setUneditable&&this.target.removeAttribute("contentEditable"),this.view.domObserver.start()),this.delayedSelectionSync&&setTimeout(()=>{this.view.isDestroyed||Je(this.view)})}up(e){if(this.done(),!this.view.dom.contains(e.target))return;let t=this.pos;this.view.state.doc!=this.startDoc&&(t=this.view.posAtCoords(Kn(e))),this.updateAllowDefault(e),this.allowDefault||!t?Ue(this.view,"pointer"):gp(this.view,t.pos,t.inside,e,this.selectNode)?e.preventDefault():e.button==0&&(this.flushed||ae&&this.mightDrag&&!this.mightDrag.node.isAtom||se&&!this.view.state.selection.visible&&Math.min(Math.abs(t.pos-this.view.state.selection.from),Math.abs(t.pos-this.view.state.selection.to))<=2)?(qn(this.view,N.near(this.view.state.doc.resolve(t.pos))),e.preventDefault()):Ue(this.view,"pointer")}move(e){this.updateAllowDefault(e),Ue(this.view,"pointer"),super.move(e)}updateAllowDefault(e){!this.allowDefault&&(Math.abs(this.event.x-e.clientX)>4||Math.abs(this.event.y-e.clientY)>4)&&(this.allowDefault=!0)}delaySelUpdate(){return this.allowDefault?(this.delayedSelectionSync=!0,!0):!1}}class Sp extends Yc{constructor(e,t){super(e),this.startSelection=t,this.startDoc=e.state.doc}move(e){if(e.buttons==0||this.view.isDestroyed||!this.view.state.doc.eq(this.startDoc)){this.done();return}e.preventDefault(),Ue(this.view,"pointer");let t=this.view.posAtCoords(Kn(e)),r=t&&Jc(this.view,t.inside,!1);if(!r)return;let{doc:i}=this.view.state,s=this.startSelection,[o,l]=r.from{n.input.lastTouch=Date.now(),io(n),Ue(n,"pointer")};de.touchmove=n=>{n.input.lastTouch=Date.now(),Ue(n,"pointer")};de.contextmenu=n=>io(n);function Xc(n,e){return n.composing?!0:ae&&Math.abs(Date.now()-n.input.compositionEndedAt)<500?(n.input.compositionEndedAt=-2e8,!0):!1}const Cp=_e?5e3:-1;fe.compositionstart=fe.compositionupdate=n=>{if(!n.composing){n.domObserver.flush();let{state:e}=n,t=e.selection.$to;if(e.selection instanceof v&&e.selection.empty&&(e.storedMarks||!t.textOffset&&t.parentOffset&&t.nodeBefore.marks.some(r=>r.type.spec.inclusive===!1)||se&&Tc&&xp(n)))n.markCursor=n.state.storedMarks||t.marks(),vr(n,!0),n.markCursor=null;else if(vr(n,!e.selection.empty),be&&e.selection.empty&&t.parentOffset&&!t.textOffset&&t.nodeBefore.marks.length){let r=n.domSelectionRange();for(let i=r.focusNode,s=r.focusOffset;i&&A(i)&&s!=0;){let o=s<0?i.lastChild:i.childNodes[s-1];if(!o)break;if(Y(o)){let l=n.domSelection();l&&l.collapse(o,o.nodeValue.length);break}else i=o,s=-1}}n.input.composing=!0}Qc(n,Cp)};function xp(n){let{focusNode:e,focusOffset:t}=n.domSelectionRange();if(!e||!A(e)||t>=e.childNodes.length)return!1;let r=e.childNodes[t];return A(r)&&r.contentEditable=="false"}fe.compositionend=(n,e)=>{n.composing&&(n.input.composing=!1,n.input.compositionEndedAt=Date.now(),n.input.compositionPendingChanges=n.domObserver.pendingRecords().length?n.input.compositionID:0,n.input.compositionNode=null,n.input.badSafariComposition?n.domObserver.forceFlush():n.input.compositionPendingChanges&&Promise.resolve().then(()=>n.domObserver.flush()),n.input.compositionID++,Qc(n,20))};function Qc(n,e){clearTimeout(n.input.composingTimeout),e>-1&&(n.input.composingTimeout=setTimeout(()=>vr(n),e))}function Zc(n){for(n.composing&&(n.input.composing=!1,n.input.compositionEndedAt=Date.now());n.input.compositionNodes.length>0;)n.input.compositionNodes.pop().markParentsDirty()}function vp(n){let e=n.domSelectionRange();if(!e.focusNode)return null;let t=mh(e.focusNode,e.focusOffset),r=gh(e.focusNode,e.focusOffset);if(t&&r&&t!=r){let i=r.pmViewDesc,s=n.domObserver.lastChangedTextNode;if(t==s||r==s)return s;if(!i||!i.isText(r.nodeValue))return r;if(n.input.compositionNode==r){let o=t.pmViewDesc;if(!(!o||!o.isText(t.nodeValue)))return r}}return t||r}function vr(n,e=!1){if(!(_e&&n.domObserver.flushingSoon>=0)){if(n.domObserver.forceFlush(),Zc(n),e||n.docView&&n.docView.dirty){let t=Zs(n),r=n.state.selection;return t&&!t.eq(r)?n.dispatch(n.state.tr.setSelection(t)):(n.markCursor||e)&&!r.$from.node(r.$from.sharedDepth(r.to)).inlineContent?n.dispatch(n.state.tr.deleteSelection()):n.updateState(n.state),!0}return!1}}function Mp(n,e){if(!n.dom.parentNode)return;let t=n.dom.parentNode.appendChild(document.createElement("div"));t.appendChild(e),t.style.cssText="position: fixed; left: -10000px; top: 10px";let r=getSelection(),i=document.createRange();i.selectNodeContents(e),n.dom.blur(),r.removeAllRanges(),r.addRange(i),setTimeout(()=>{t.parentNode&&t.parentNode.removeChild(t),n.focus()},50)}const Pn=pe&&ot<15||en&&wh<604;de.copy=fe.cut=(n,e)=>{let t=e,r=n.state.selection,i=t.type=="cut";if(r.empty)return;let s=Pn?null:t.clipboardData,o=r.content(),{dom:l,text:a}=to(n,o);s?(t.preventDefault(),s.clearData(),s.setData("text/html",l.innerHTML),s.setData("text/plain",a)):Mp(n,l),i&&n.dispatch(n.state.tr.deleteSelection().scrollIntoView().setMeta("uiEvent","cut"))};function Tp(n){return n.openStart==0&&n.openEnd==0&&n.content.childCount==1?n.content.firstChild:null}function Ep(n,e){if(!n.dom.parentNode)return;let t=n.input.shiftKey||n.state.selection.$from.parent.type.spec.code,r=n.dom.parentNode.appendChild(document.createElement(t?"textarea":"div"));t||(r.contentEditable="true"),r.style.cssText="position: fixed; left: -10000px; top: 10px",r.focus();let i=n.input.shiftKey&&n.input.lastKeyCode!=45;setTimeout(()=>{n.focus(),r.parentNode&&r.parentNode.removeChild(r),t?zn(n,r.value,null,i,e):zn(n,r.textContent,r.innerHTML,i,e)},50)}function zn(n,e,t,r,i){let s=Wc(n,e,t,r,n.state.selection.$from);if(n.someProp("handlePaste",a=>a(n,i,s||x.empty)))return!0;if(!s)return!1;let o=Tp(s),l=o?n.state.tr.replaceSelectionWith(o,r):n.state.tr.replaceSelection(s);return n.dispatch(l.scrollIntoView().setMeta("paste",!0).setMeta("uiEvent","paste")),!0}function eu(n){let e=n.getData("text/plain")||n.getData("Text");if(e)return e;let t=n.getData("text/uri-list");return t?t.replace(/\r?\n/g," "):""}fe.paste=(n,e)=>{let t=e;if(n.composing&&!_e)return;let r=Pn?null:t.clipboardData,i=n.input.shiftKey&&n.input.lastKeyCode!=45;r&&zn(n,eu(r),r.getData("text/html"),i,t)?t.preventDefault():Ep(n,t)};class tu{constructor(e,t,r){this.slice=e,this.move=t,this.node=r}}const Ap=Ce?"altKey":"ctrlKey";function nu(n,e){let t;return n.someProp("dragCopies",r=>{t=t||r(e)}),t!=null?!t:!e[Ap]}de.dragstart=(n,e)=>{let t=e,r=n.input.mouseDown;if(r&&r.done(),!t.dataTransfer)return;let i=n.state.selection,s=i.empty?null:n.posAtCoords(Kn(t)),o;if(!(s&&s.pos>=i.from&&s.pos<=(i instanceof T?i.to-1:i.to))){if(r&&r.mightDrag)o=T.create(n.state.doc,r.mightDrag.pos);else if(t.target&&A(t.target)){let d=n.docView.nearestDesc(t.target,!0);d&&d.node.type.spec.draggable&&d!=n.docView&&(o=T.create(n.state.doc,d.posBefore))}}let l=(o||n.state.selection).content(),{dom:a,text:c,slice:u}=to(n,l);(!t.dataTransfer.files.length||!se||Mc>120)&&t.dataTransfer.clearData(),t.dataTransfer.setData(Pn?"Text":"text/html",a.innerHTML),t.dataTransfer.effectAllowed="copyMove",Pn||t.dataTransfer.setData("text/plain",c),n.dragging=new tu(u,nu(n,t),o)};de.dragend=n=>{let e=n.dragging;window.setTimeout(()=>{n.dragging==e&&(n.dragging=null)},50)};fe.dragover=fe.dragenter=(n,e)=>e.preventDefault();fe.drop=(n,e)=>{try{Np(n,e,n.dragging)}finally{n.dragging=null}};function Np(n,e,t){if(!e.dataTransfer)return;let r=n.posAtCoords(Kn(e));if(!r)return;let i=n.state.doc.resolve(r.pos),s=t&&t.slice;s?n.someProp("transformPasted",h=>{s=h(s,n,!1)}):s=Wc(n,eu(e.dataTransfer),Pn?null:e.dataTransfer.getData("text/html"),!1,i);let o=!!(t&&nu(n,e));if(n.someProp("handleDrop",h=>h(n,e,s||x.empty,o))){e.preventDefault();return}if(!s)return;e.preventDefault();let l=s?rc(n.state.doc,i.pos,s):i.pos;l==null&&(l=i.pos);let a=n.state.tr;if(o){let{node:h}=t;h?h.replace(a):a.deleteSelection()}let c=a.mapping.map(l),u=s.openStart==0&&s.openEnd==0&&s.content.childCount==1,d=a.doc;if(u?a.replaceRangeWith(c,c,s.content.firstChild):a.replaceRange(c,c,s),a.doc.eq(d))return;let f=a.doc.resolve(c);if(u&&T.isSelectable(s.content.firstChild)&&f.nodeAfter&&f.nodeAfter.sameMarkup(s.content.firstChild))a.setSelection(new T(f));else{let h=a.mapping.map(l);a.mapping.maps[a.mapping.maps.length-1].forEach((p,m,g,y)=>h=y),a.setSelection(eo(n,f,a.doc.resolve(h)))}n.focus(),n.dispatch(a.setMeta("uiEvent","drop"))}de.focus=n=>{n.input.lastFocus=Date.now(),n.focused||(n.domObserver.stop(),n.dom.classList.add("ProseMirror-focused"),n.domObserver.start(),n.focused=!0,setTimeout(()=>{n.docView&&n.hasFocus()&&!n.domObserver.currentSelection.eq(n.domSelectionRange())&&Je(n)},20))};de.blur=(n,e)=>{let t=e;n.focused&&(n.domObserver.stop(),n.dom.classList.remove("ProseMirror-focused"),n.domObserver.start(),t.relatedTarget&&n.dom.contains(t.relatedTarget)&&n.domObserver.currentSelection.clear(),n.focused=!1)};de.beforeinput=(n,e)=>{if(_e&&e.inputType=="deleteContentBackward"){n.domObserver.flushSoon();let{domChangeCount:r}=n.input;setTimeout(()=>{if(n.input.domChangeCount!=r||(n.dom.blur(),n.focus(),n.someProp("handleKeyDown",s=>s(n,kt(8,"Backspace")))))return;let{$cursor:i}=n.state.selection;i&&i.pos>0&&n.dispatch(n.state.tr.delete(i.pos-1,i.pos).scrollIntoView())},50)}};for(let n in fe)de[n]=fe[n];function Bn(n,e){if(n==e)return!0;for(let t in n)if(n[t]!==e[t])return!1;for(let t in e)if(!(t in n))return!1;return!0}class Mr{constructor(e,t){this.toDOM=e,this.spec=t||Nt,this.side=this.spec.side||0}map(e,t,r,i){let{pos:s,deleted:o}=e.mapResult(t.from+i,this.side<0?-1:1);return o?null:new Q(s-r,s-r,this)}valid(){return!0}eq(e){return this==e||e instanceof Mr&&(this.spec.key&&this.spec.key==e.spec.key||this.toDOM==e.toDOM&&Bn(this.spec,e.spec))}destroy(e){this.spec.destroy&&this.spec.destroy(e)}}class ct{constructor(e,t){this.attrs=e,this.spec=t||Nt}map(e,t,r,i){let s=e.map(t.from+i,this.spec.inclusiveStart?-1:1)-r,o=e.map(t.to+i,this.spec.inclusiveEnd?1:-1)-r;return s>=o?null:new Q(s,o,this)}valid(e,t){return t.from=e&&(!s||s(l.spec))&&r.push(l.copy(l.from+i,l.to+i))}for(let o=0;oe){let l=this.children[o]+1;this.children[o+2].findInner(e-l,t-l,r,i+l,s)}}map(e,t,r){return this==oe||e.maps.length==0?this:this.mapInner(e,t,0,0,r||Nt)}mapInner(e,t,r,i,s){let o;for(let l=0;l{let c=a+r,u;if(u=iu(t,l,c)){for(i||(i=this.children.slice());sl&&d.to=e){this.children[l]==e&&(r=this.children[l+2]);break}let s=e+1,o=s+t.content.size;for(let l=0;ls&&a.type instanceof ct){let c=Math.max(s,a.from)-s,u=Math.min(o,a.to)-s;ci.map(e,t,Nt));return nt.from(r)}forChild(e,t){if(t.isLeaf)return I.empty;let r=[];for(let i=0;it instanceof I)?e:e.reduce((t,r)=>t.concat(r instanceof I?r:r.members),[]))}}forEachSet(e){for(let t=0;t{let g=m-p-(h-f);for(let y=0;yk+u-d)continue;let w=l[y]+u-d;h>=w?l[y+1]=f<=w?-2:-1:f>=u&&g&&(l[y]+=g,l[y+1]+=g)}d+=g}),u=t.maps[c].map(u,-1)}let a=!1;for(let c=0;c=r.content.size){a=!0;continue}let f=t.map(n[c+1]+s,-1),h=f-i,{index:p,offset:m}=r.content.findIndex(d),g=r.maybeChild(p);if(g&&m==d&&m+g.nodeSize==h){let y=l[c+2].mapInner(t,g,u+1,n[c]+s+1,o);y!=oe?(l[c]=d,l[c+1]=h,l[c+2]=y):(l[c+1]=-2,a=!0)}else a=!0}if(a){let c=Rp(l,n,e,t,i,s,o),u=Tr(c,r,0,o);e=u.local;for(let d=0;dt&&o.to{let c=iu(n,l,a+t);if(c){s=!0;let u=Tr(c,l,t+a+1,r);u!=oe&&i.push(a,a+l.nodeSize,u)}});let o=ru(s?su(n):n,-t).sort(Ot);for(let l=0;l0;)e++;n.splice(e,0,t)}function Pi(n){let e=[];return n.someProp("decorations",t=>{let r=t(n.state);r&&r!=oe&&e.push(r)}),n.cursorWrapper&&e.push(I.create(n.state.doc,[n.cursorWrapper.deco])),nt.from(e)}const Dp={childList:!0,characterData:!0,characterDataOldValue:!0,attributes:!0,attributeOldValue:!0,subtree:!0},Ip=pe&&ot<=11;class Lp{constructor(){this.anchorNode=null,this.anchorOffset=0,this.focusNode=null,this.focusOffset=0}set(e){this.anchorNode=e.anchorNode,this.anchorOffset=e.anchorOffset,this.focusNode=e.focusNode,this.focusOffset=e.focusOffset}clear(){this.anchorNode=this.focusNode=null}eq(e){return e.anchorNode==this.anchorNode&&e.anchorOffset==this.anchorOffset&&e.focusNode==this.focusNode&&e.focusOffset==this.focusOffset}}class Pp{constructor(e,t){this.view=e,this.handleDOMChange=t,this.queue=[],this.flushingSoon=-1,this.observer=null,this.currentSelection=new Lp,this.onCharData=null,this.suppressingSelectionUpdates=!1,this.lastChangedTextNode=null,this.observer=window.MutationObserver&&new window.MutationObserver(r=>{for(let i=0;ii.type=="childList"&&i.removedNodes.length||i.type=="characterData"&&i.oldValue.length>i.target.nodeValue.length)?this.flushSoon():ae&&e.composing&&r.some(i=>i.type=="childList"&&i.target.nodeName=="TR")?(e.input.badSafariComposition=!0,this.flushSoon()):this.flush()}),Ip&&(this.onCharData=r=>{this.queue.push({target:r.target,type:"characterData",oldValue:r.prevValue}),this.flushSoon()}),this.onSelectionChange=this.onSelectionChange.bind(this)}flushSoon(){this.flushingSoon<0&&(this.flushingSoon=window.setTimeout(()=>{this.flushingSoon=-1,this.flush()},20))}forceFlush(){this.flushingSoon>-1&&(window.clearTimeout(this.flushingSoon),this.flushingSoon=-1,this.flush())}start(){this.observer&&(this.observer.takeRecords(),this.observer.observe(this.view.dom,Dp)),this.onCharData&&this.view.dom.addEventListener("DOMCharacterDataModified",this.onCharData),this.connectSelection()}stop(){if(this.observer){let e=this.observer.takeRecords();if(e.length){for(let t=0;tthis.flush(),20)}this.observer.disconnect()}this.onCharData&&this.view.dom.removeEventListener("DOMCharacterDataModified",this.onCharData),this.disconnectSelection()}connectSelection(){this.view.dom.ownerDocument.addEventListener("selectionchange",this.onSelectionChange)}disconnectSelection(){this.view.dom.ownerDocument.removeEventListener("selectionchange",this.onSelectionChange)}suppressSelectionUpdates(){this.suppressingSelectionUpdates=!0,setTimeout(()=>this.suppressingSelectionUpdates=!1,50)}onSelectionChange(){if(ul(this.view)){if(this.suppressingSelectionUpdates)return Je(this.view);if(pe&&ot<=11&&!this.view.state.selection.empty){let e=this.view.domSelectionRange();if(e.focusNode&&Lt(e.focusNode,e.focusOffset,e.anchorNode,e.anchorOffset))return this.flushSoon()}this.flush()}}setCurSelection(){this.currentSelection.set(this.view.domSelectionRange())}ignoreSelectionChange(e){if(!e.focusNode)return!0;let t=new Set,r;for(let s=e.focusNode;s;s=Zt(s))t.add(s);for(let s=e.anchorNode;s;s=Zt(s))if(t.has(s)){r=s;break}let i=r&&this.view.docView.nearestDesc(r);if(i&&i.ignoreMutation({type:"selection",target:Y(r)?r.parentNode:r}))return this.setCurSelection(),!0}pendingRecords(){if(this.observer)for(let e of this.observer.takeRecords())this.queue.push(e);return this.queue}flush(){let{view:e}=this;if(!e.docView||this.flushingSoon>-1)return;let t=this.pendingRecords();t.length&&(this.queue=[]);let r=e.domSelectionRange(),i=!this.suppressingSelectionUpdates&&!this.currentSelection.eq(r)&&ul(e)&&!this.ignoreSelectionChange(r),s=-1,o=-1,l=!1,a=[];if(e.editable)for(let u=0;uu.nodeName=="BR")&&(e.input.lastKeyCode==8||e.input.lastKeyCode==46||se&&(e.composing||e.input.compositionEndedAt>Date.now()-50)&&t.some(u=>u.type=="childList"&&u.removedNodes.length))){for(let u of a)if(u.nodeName=="BR"&&u.parentNode){let d=u.nextSibling;for(;d&&A(d);){if(d.contentEditable=="false"){u.parentNode.removeChild(u);break}d=d.firstChild}}}else if(be&&a.length){let u=a.filter(d=>d.nodeName=="BR");if(u.length==2){let[d,f]=u;d.parentNode&&d.parentNode.parentNode==f.parentNode?f.remove():d.remove()}else{let{focusNode:d}=this.currentSelection;for(let f of u){let h=f.parentNode;h&&h.nodeName=="LI"&&(!d||$p(e,d)!=h)&&f.remove()}}}let c=null;s<0&&i&&e.input.lastFocus>Date.now()-200&&Math.max(e.input.lastTouch,e.input.lastClick.time)-1||i)&&(s>-1&&(e.docView.markDirty(s,o),zp(e)),e.input.badSafariComposition&&(e.input.badSafariComposition=!1,Hp(e,a)),this.handleDOMChange(s,o,l,a),e.docView&&e.docView.dirty?e.updateState(e.state):this.currentSelection.eq(r)||Je(e),this.currentSelection.set(r))}registerMutation(e,t){if(t.indexOf(e.target)>-1)return null;let r=this.view.docView.nearestDesc(e.target);if(e.type=="attributes"&&(r==this.view.docView||e.attributeName=="contenteditable"||e.attributeName=="style"&&!e.oldValue&&!e.target.getAttribute("style"))||!r||r.ignoreMutation(e))return null;if(e.type=="childList"){for(let u=0;us;y--){let k=i.childNodes[y-1],w=k.pmViewDesc;if(k.nodeName=="BR"&&!w){o=y;break}if(!w||w.size)break}let f=n.state.doc,h=n.someProp("domParser")||Ke.fromSchema(n.state.schema),p=f.resolve(l),m=null,g=h.parse(i,{topNode:p.parent,topMatch:p.parent.contentMatchAt(p.index()),topOpen:!0,from:s,to:o,preserveWhitespace:p.parent.type.whitespace=="pre"?"full":!0,findPositions:u,ruleFromNode:Vp(r),context:p});if(u&&u[0].pos!=null){let y=u[0].pos,k=u[1]&&u[1].pos;k==null&&(k=y),m={anchor:y+l,head:k+l}}return{doc:g,sel:m,from:l,to:a}}const Vp=n=>e=>{let t=e.pmViewDesc;if(t)return t.parseRule(n);if(e.nodeName=="BR"&&e.parentNode){if(ae&&/^(ul|ol)$/i.test(e.parentNode.nodeName)){let r=document.createElement("div");return r.appendChild(document.createElement("li")),{skip:r}}else if(e.parentNode.lastChild==e||ae&&/^(tr|table)$/i.test(e.parentNode.nodeName))return{ignore:!0}}else if(e.nodeName=="IMG"&&e.getAttribute("mark-placeholder"))return{ignore:!0};return null},Wp=/^(a|abbr|acronym|b|bd[io]|big|br|button|cite|code|data(list)?|del|dfn|em|i|img|ins|kbd|label|map|mark|meter|output|q|ruby|s|samp|small|span|strong|su[bp]|time|u|tt|var)$/i;function jp(n,e,t,r,i){let s=n.input.compositionPendingChanges||(n.composing?n.input.compositionID:0);if(n.input.compositionPendingChanges=0,e<0){let E=n.input.lastSelectionTime>Date.now()-50?n.input.lastSelectionOrigin:null,D=Zs(n,E);if(D&&!n.state.selection.eq(D)){if(se&&_e&&n.input.lastKeyCode===13&&Date.now()-100te(n,kt(13,"Enter"))))return;let P=n.state.tr.setSelection(D);E=="pointer"?P.setMeta("pointer",!0):E=="key"&&P.scrollIntoView(),s&&P.setMeta("composition",s),n.dispatch(P)}return}let o=n.state.doc.resolve(e),l=o.sharedDepth(t);e=o.before(l+1),t=n.state.doc.resolve(t).after(l+1);let a=n.state.selection,c=Fp(n,e,t,i),u=n.state.doc,d=u.slice(c.from,c.to),f,h;n.input.lastKeyCode===8&&Date.now()-100Date.now()-225||_e)&&i.some(E=>A(E)&&!Wp.test(E.nodeName))&&(!p||p.endA>=p.endB)&&n.someProp("handleKeyDown",E=>E(n,kt(13,"Enter")))){n.input.lastIOSEnter=0;return}if(!p)if(r&&a instanceof v&&!a.empty&&a.$head.sameParent(a.$anchor)&&!n.composing&&!(c.sel&&c.sel.anchor!=c.sel.head))p={start:a.from,endA:a.to,endB:a.to};else{if(c.sel){let E=Sl(n,n.state.doc,c.sel);if(E&&!E.eq(n.state.selection)){let D=n.state.tr.setSelection(E);s&&D.setMeta("composition",s),n.dispatch(D)}}return}n.state.selection.fromn.state.selection.from&&p.start<=n.state.selection.from+2&&n.state.selection.from>=c.from?p.start=n.state.selection.from:p.endA=n.state.selection.to-2&&n.state.selection.to<=c.to&&(p.endB+=n.state.selection.to-p.endA,p.endA=n.state.selection.to)),pe&&ot<=11&&p.endB==p.start+1&&p.endA==p.start&&p.start>c.from&&c.doc.textBetween(p.start-c.from-1,p.start-c.from+1)=="  "&&(p.start--,p.endA--,p.endB--);let m=c.doc.resolveNoCache(p.start-c.from),g=c.doc.resolveNoCache(p.endB-c.from),y=u.resolve(p.start),k=m.sameParent(g)&&m.parent.inlineContent&&y.end()>=p.endA;if((en&&n.input.lastIOSEnter>Date.now()-225&&(!k||i.some(E=>E.nodeName=="DIV"||E.nodeName=="P"))||!k&&Kp(c.doc,m.pos,g.pos))&&n.someProp("handleKeyDown",E=>E(n,kt(13,"Enter")))){n.input.lastIOSEnter=0;return}if(n.state.selection.anchor>p.start&&Up(u,p.start,p.endA,m,g)&&n.someProp("handleKeyDown",E=>E(n,kt(8,"Backspace")))){_e&&se&&n.domObserver.suppressSelectionUpdates();return}se&&p.endB==p.start&&(n.input.lastChromeDelete=Date.now()),_e&&!k&&m.start()!=g.start()&&g.parentOffset==0&&m.depth==g.depth&&c.sel&&c.sel.anchor==c.sel.head&&c.sel.head==p.endA&&(p.endB-=2,g=c.doc.resolveNoCache(p.endB-c.from),setTimeout(()=>{n.someProp("handleKeyDown",function(E){return E(n,kt(13,"Enter"))})},20));let w=p.start,C=p.endA,O=E=>{let D=E||n.state.tr.replace(w,C,c.doc.slice(p.start-c.from,p.endB-c.from));if(c.sel){let P=Sl(n,D.doc,c.sel);P&&!(se&&n.composing&&P.empty&&(p.start!=p.endB||n.input.lastChromeDeleteJe(n),20));let E=O(n.state.tr.delete(w,C)),D=u.resolve(p.start).marksAcross(u.resolve(p.endA));D&&E.ensureMarks(D),n.dispatch(E)}else if(p.endA==p.endB&&(B=_p(m.parent.content.cut(m.parentOffset,g.parentOffset),y.parent.content.cut(y.parentOffset,p.endA-y.start())))){let E=O(n.state.tr);B.type=="add"?E.addMark(w,C,B.mark):E.removeMark(w,C,B.mark),n.dispatch(E)}else if(m.parent.child(m.index()).isText&&m.index()==g.index()-(g.textOffset?0:1)){let E=m.parent.textBetween(m.parentOffset,g.parentOffset),D=()=>O(n.state.tr.insertText(E,w,C));n.someProp("handleTextInput",P=>P(n,w,C,E,D))||n.dispatch(D())}else n.dispatch(O());else n.dispatch(O())}function Sl(n,e,t){return Math.max(t.anchor,t.head)>e.content.size?null:eo(n,e.resolve(t.anchor),e.resolve(t.head))}function _p(n,e){let t=n.firstChild.marks,r=e.firstChild.marks,i=t,s=r,o,l,a;for(let u=0;uu.mark(l.addToSet(u.marks));else if(i.length==0&&s.length==1)l=s[0],o="remove",a=u=>u.mark(l.removeFromSet(u.marks));else return null;let c=[];for(let u=0;ut||zi(o,!0,!1){s.isTextblock&&o>=e&&o0&&(e||n.indexAfter(r)==n.node(r).childCount);)r--,i++,e=!1;if(t){let s=n.node(r).maybeChild(n.indexAfter(r));for(;s&&!s.isLeaf;)s=s.firstChild,i++}return i}function qp(n,e,t,r,i){let s=n.findDiffStart(e,t),o=t+n.size,l=t+e.size;if(s==null)return null;let{a,b:c}=n.findDiffEnd(e,o,l);if(i=="end"){let u=Math.max(0,s-Math.min(a,c));r-=a+u-s}if(a=a?s-r:0;s-=u,c=s+(c-a),a=s}else if(c=c?s-r:0;s-=u,a=s+(a-c),c=s}return{start:s,endA:a,endB:c}}class ou{constructor(e,t){this._root=null,this.focused=!1,this.trackWrites=null,this.mounted=!1,this.markCursor=null,this.cursorWrapper=null,this.lastSelectedViewDesc=void 0,this.input=new ap,this.prevDirectPlugins=[],this.pluginViews=[],this.requiresGeckoHackNode=!1,this.dragging=null,this._props=t,this.state=t.state,this.directPlugins=t.plugins||[],this.directPlugins.forEach(Tl),this.dispatch=this.dispatch.bind(this),this.dom=e&&e.mount||document.createElement("div"),e&&(e.appendChild?e.appendChild(this.dom):typeof e=="function"?e(this.dom):e.mount&&(this.mounted=!0)),this.editable=vl(this),xl(this),this.nodeViews=Ml(this),this.docView=il(this.state.doc,Cl(this),Pi(this),this.dom,this),this.domObserver=new Pp(this,(r,i,s,o)=>jp(this,r,i,s,o)),this.domObserver.start(),cp(this),this.updatePluginViews()}get composing(){return this.input.composing}get props(){if(this._props.state!=this.state){let e=this._props;this._props={};for(let t in e)this._props[t]=e[t];this._props.state=this.state}return this._props}update(e){e.handleDOMEvents!=this._props.handleDOMEvents&&ks(this);let t=this._props;this._props=e,e.plugins&&(e.plugins.forEach(Tl),this.directPlugins=e.plugins),this.updateStateInner(e.state,t)}setProps(e){let t={};for(let r in this._props)t[r]=this._props[r];t.state=this.state;for(let r in e)t[r]=e[r];this.update(t)}updateState(e){this.updateStateInner(e,this._props)}updateStateInner(e,t){var r;let i=this.state,s=!1,o=!1;e.storedMarks&&this.composing&&(Zc(this),o=!0),this.state=e;let l=i.plugins!=e.plugins||this._props.plugins!=t.plugins;if(l||this._props.plugins!=t.plugins||this._props.nodeViews!=t.nodeViews){let h=Ml(this);Gp(h,this.nodeViews)&&(this.nodeViews=h,s=!0)}(l||t.handleDOMEvents!=this._props.handleDOMEvents)&&ks(this),this.editable=vl(this),xl(this);let a=Pi(this),c=Cl(this),u=i.plugins!=e.plugins&&!i.doc.eq(e.doc)?"reset":e.scrollToSelection>i.scrollToSelection?"to selection":"preserve",d=s||!this.docView.matchesNode(e.doc,c,a);(d||!e.selection.eq(i.selection))&&(o=!0);let f=u=="preserve"&&o&&this.dom.style.overflowAnchor==null&&xh(this);if(o){this.domObserver.stop();let h=d&&(pe||se)&&!this.composing&&!i.selection.empty&&!e.selection.empty&&Jp(i.selection,e.selection);if(d){let m=se?this.trackWrites=this.domSelectionRange().focusNode:null;this.composing&&(this.input.compositionNode=vp(this)),(s||!this.docView.update(e.doc,c,a,this))&&(this.docView.updateOuterDeco(c),this.docView.destroy(),this.docView=il(e.doc,c,a,this.dom,this)),m&&(!this.trackWrites||!this.dom.contains(this.trackWrites))&&(h=!0)}let p=this.input.mouseDown;h||!(p&&this.domObserver.currentSelection.eq(this.domSelectionRange())&&qh(this)&&p.delaySelUpdate())?Je(this,h):(Hc(this,e.selection),this.domObserver.setCurSelection()),this.domObserver.start()}this.updatePluginViews(i),!((r=this.dragging)===null||r===void 0)&&r.node&&!i.doc.eq(e.doc)&&this.updateDraggedNode(this.dragging,i),u=="reset"?this.dom.scrollTop=0:u=="to selection"?this.scrollToSelection():f&&vh(f)}scrollToSelection(){let e=this.domSelectionRange().focusNode;if(!(!e||!Pt(this.dom,e))){if(!this.someProp("handleScrollToSelection",t=>t(this)))if(this.state.selection instanceof T){let t=this.docView.domAfterPos(this.state.selection.from);A(t)&&Zo(this,t.getBoundingClientRect(),e)}else Zo(this,this.coordsAtPos(this.state.selection.head,1),e)}}destroyPluginViews(){let e;for(;e=this.pluginViews.pop();)e.destroy&&e.destroy()}updatePluginViews(e){if(!e||e.plugins!=this.state.plugins||this.directPlugins!=this.prevDirectPlugins){this.prevDirectPlugins=this.directPlugins,this.destroyPluginViews();for(let t=0;t0&&st.ownerDocument.getSelection()),this._root=t}return e||document}updateRoot(){this._root=null}posAtCoords(e){return Oh(this,e)}coordsAtPos(e,t=1){return Rc(this,e,t)}domAtPos(e,t=0){return this.docView.domFromPos(e,t)}nodeDOM(e){let t=this.docView.descAt(e);return t?t.nodeDOM:null}posAtDOM(e,t,r=-1){let i=this.docView.posFromDOM(e,t,r);if(i==null)throw new RangeError("DOM position not inside the editor");return i}endOfTextblock(e,t){return Ph(this,t||this.state,e)}pasteHTML(e,t){return zn(this,"",e,!1,t||new ClipboardEvent("paste"))}pasteText(e,t){return zn(this,e,null,!0,t||new ClipboardEvent("paste"))}serializeForClipboard(e){return to(this,e)}destroy(){this.docView&&(up(this),this.destroyPluginViews(),this.mounted?(this.docView.update(this.state.doc,[],Pi(this),this),this.dom.textContent=""):this.dom.parentNode&&this.dom.parentNode.removeChild(this.dom),this.docView.destroy(),this.docView=null,hh())}get isDestroyed(){return this.docView==null}dispatchEvent(e){return fp(this,e)}domSelectionRange(){let e=this.dom.isConnected!==!1&&this.domSelection();return e?ae&&this.root.nodeType===11&&bh(this.dom.ownerDocument)==this.dom&&Bp(this,e)||e:{focusNode:null,focusOffset:0,anchorNode:null,anchorOffset:0}}domSelection(){return this.root.getSelection()}}ou.prototype.dispatch=function(n){let e=this._props.dispatchTransaction;e?e.call(this,n):this.updateState(this.state.apply(n))};function Cl(n){let e=Object.create(null);return e.class="ProseMirror",e.contenteditable=String(n.editable),n.someProp("attributes",t=>{if(typeof t=="function"&&(t=t(n.state)),t)for(let r in t)r=="class"?e.class+=" "+t[r]:r=="style"?e.style=(e.style?e.style+";":"")+t[r]:!e[r]&&r!="contenteditable"&&r!="nodeName"&&(e[r]=String(t[r]))}),e.translate||(e.translate="no"),[Q.node(0,n.state.doc.content.size,e)]}function xl(n){if(n.markCursor){let e=document.createElement("img");e.className="ProseMirror-separator",e.setAttribute("mark-placeholder","true"),e.setAttribute("alt",""),n.cursorWrapper={dom:e,deco:Q.widget(n.state.selection.from,e,{raw:!0,marks:n.markCursor})}}else n.cursorWrapper=null}function vl(n){return!n.someProp("editable",e=>e(n.state)===!1)}function Jp(n,e){let t=Math.min(n.$anchor.sharedDepth(n.head),e.$anchor.sharedDepth(e.head));return n.$anchor.start(t)!=e.$anchor.start(t)}function Ml(n){let e=Object.create(null);function t(r){for(let i in r)Object.prototype.hasOwnProperty.call(e,i)||(e[i]=r[i])}return n.someProp("nodeViews",t),n.someProp("markViews",t),e}function Gp(n,e){let t=0,r=0;for(let i in n){if(n[i]!=e[i])return!0;t++}for(let i in e)r++;return t!=r}function Tl(n){if(n.spec.state||n.spec.filterTransaction||n.spec.appendTransaction)throw new RangeError("Plugins passed directly to the view must not have a state component")}var dt={8:"Backspace",9:"Tab",10:"Enter",12:"NumLock",13:"Enter",16:"Shift",17:"Control",18:"Alt",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",44:"PrintScreen",45:"Insert",46:"Delete",59:";",61:"=",91:"Meta",92:"Meta",106:"*",107:"+",108:",",109:"-",110:".",111:"/",144:"NumLock",145:"ScrollLock",160:"Shift",161:"Shift",162:"Control",163:"Control",164:"Alt",165:"Alt",173:"-",186:";",187:"=",188:",",189:"-",190:".",191:"/",192:"`",219:"[",220:"\\",221:"]",222:"'"},Er={48:")",49:"!",50:"@",51:"#",52:"$",53:"%",54:"^",55:"&",56:"*",57:"(",59:":",61:"+",173:"_",186:":",187:"+",188:"<",189:"_",190:">",191:"?",192:"~",219:"{",220:"|",221:"}",222:'"'},Yp=typeof navigator<"u"&&/Mac/.test(navigator.platform),Xp=typeof navigator<"u"&&/MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent);for(var ie=0;ie<10;ie++)dt[48+ie]=dt[96+ie]=String(ie);for(var ie=1;ie<=24;ie++)dt[ie+111]="F"+ie;for(var ie=65;ie<=90;ie++)dt[ie]=String.fromCharCode(ie+32),Er[ie]=String.fromCharCode(ie);for(var Bi in dt)Er.hasOwnProperty(Bi)||(Er[Bi]=dt[Bi]);function Qp(n){var e=Yp&&n.metaKey&&n.shiftKey&&!n.ctrlKey&&!n.altKey||Xp&&n.shiftKey&&n.key&&n.key.length==1||n.key=="Unidentified",t=!e&&n.key||(n.shiftKey?Er:dt)[n.keyCode]||n.key||"Unidentified";return t=="Esc"&&(t="Escape"),t=="Del"&&(t="Delete"),t=="Left"&&(t="ArrowLeft"),t=="Up"&&(t="ArrowUp"),t=="Right"&&(t="ArrowRight"),t=="Down"&&(t="ArrowDown"),t}const Zp=typeof navigator<"u"&&/Mac|iP(hone|[oa]d)/.test(navigator.platform),em=typeof navigator<"u"&&/Win/.test(navigator.platform);function tm(n){let e=n.split(/-(?!$)/),t=e[e.length-1];t=="Space"&&(t=" ");let r,i,s,o;for(let l=0;l=t?ee.empty:this.sliceInner(Math.max(0,e),Math.min(this.length,t))};ee.prototype.get=function(e){if(!(e<0||e>=this.length))return this.getInner(e)};ee.prototype.forEach=function(e,t,r){t===void 0&&(t=0),r===void 0&&(r=this.length),t<=r?this.forEachInner(e,t,r,0):this.forEachInvertedInner(e,t,r,0)};ee.prototype.map=function(e,t,r){t===void 0&&(t=0),r===void 0&&(r=this.length);var i=[];return this.forEach(function(s,o){return i.push(e(s,o))},t,r),i};ee.from=function(e){return e instanceof ee?e:e&&e.length?new lu(e):ee.empty};var lu=(function(n){function e(r){n.call(this),this.values=r}n&&(e.__proto__=n),e.prototype=Object.create(n&&n.prototype),e.prototype.constructor=e;var t={length:{configurable:!0},depth:{configurable:!0}};return e.prototype.flatten=function(){return this.values},e.prototype.sliceInner=function(i,s){return i==0&&s==this.length?this:new e(this.values.slice(i,s))},e.prototype.getInner=function(i){return this.values[i]},e.prototype.forEachInner=function(i,s,o,l){for(var a=s;a=o;a--)if(i(this.values[a],l+a)===!1)return!1},e.prototype.leafAppend=function(i){if(this.length+i.length<=Ar)return new e(this.values.concat(i.flatten()))},e.prototype.leafPrepend=function(i){if(this.length+i.length<=Ar)return new e(i.flatten().concat(this.values))},t.length.get=function(){return this.values.length},t.depth.get=function(){return 0},Object.defineProperties(e.prototype,t),e})(ee);ee.empty=new lu([]);var im=(function(n){function e(t,r){n.call(this),this.left=t,this.right=r,this.length=t.length+r.length,this.depth=Math.max(t.depth,r.depth)+1}return n&&(e.__proto__=n),e.prototype=Object.create(n&&n.prototype),e.prototype.constructor=e,e.prototype.flatten=function(){return this.left.flatten().concat(this.right.flatten())},e.prototype.getInner=function(r){return rl&&this.right.forEachInner(r,Math.max(i-l,0),Math.min(this.length,s)-l,o+l)===!1)return!1},e.prototype.forEachInvertedInner=function(r,i,s,o){var l=this.left.length;if(i>l&&this.right.forEachInvertedInner(r,i-l,Math.max(s,l)-l,o+l)===!1||s=s?this.right.slice(r-s,i-s):this.left.slice(r,s).append(this.right.slice(0,i-s))},e.prototype.leafAppend=function(r){var i=this.right.leafAppend(r);if(i)return new e(this.left,i)},e.prototype.leafPrepend=function(r){var i=this.left.leafPrepend(r);if(i)return new e(i,this.right)},e.prototype.appendInner=function(r){return this.left.depth>=Math.max(this.right.depth,r.depth)+1?new e(this.left,new e(this.right,r)):new e(this,r)},e})(ee);const sm=500;class Te{constructor(e,t){this.items=e,this.eventCount=t}popEvent(e,t){if(this.eventCount==0)return null;let r=this.items.length;for(;;r--)if(this.items.get(r-1).selection){--r;break}let i,s;t&&(i=this.remapping(r,this.items.length),s=i.maps.length);let o=e.tr,l,a,c=[],u=[];return this.items.forEach((d,f)=>{if(!d.step){i||(i=this.remapping(r,f+1),s=i.maps.length),s--,u.push(d);return}if(i){u.push(new Oe(d.map));let h=d.step.map(i.slice(s)),p;h&&o.maybeStep(h).doc&&(p=o.mapping.maps[o.mapping.maps.length-1],c.push(new Oe(p,void 0,void 0,c.length+u.length))),s--,p&&i.appendMap(p,s)}else o.maybeStep(d.step);if(d.selection)return l=i?d.selection.map(i.slice(s)):d.selection,a=new Te(this.items.slice(0,r).append(u.reverse().concat(c)),this.eventCount-1),!1},this.items.length,0),{remaining:a,transform:o,selection:l}}addTransform(e,t,r,i){let s=[],o=this.eventCount,l=this.items,a=!i&&l.length?l.get(l.length-1):null;for(let u=0;ulm&&(l=om(l,c),o-=c),new Te(l.append(s),o)}remapping(e,t){let r=new In;return this.items.forEach((i,s)=>{let o=i.mirrorOffset!=null&&s-i.mirrorOffset>=e?r.maps.length-i.mirrorOffset:void 0;r.appendMap(i.map,o)},e,t),r}addMaps(e){return this.eventCount==0?this:new Te(this.items.append(e.map(t=>new Oe(t))),this.eventCount)}rebased(e,t){if(!this.eventCount)return this;t=Math.min(this.items.length,t);let r=[],i=this.items.length-t,s=e.mapping,o=e.steps.length,l=this.eventCount;this.items.forEach(f=>{f.selection&&l--},i);let a=t;this.items.forEach(f=>{let h=s.getMirror(--a);if(h==null)return;o=Math.min(o,h);let p=s.maps[h];if(f.step){let m=e.steps[h].invert(e.docs[h]),g=f.selection&&f.selection.map(s.slice(a+1,h));g&&l++,r.push(new Oe(p,m,g))}else r.push(new Oe(p))},i);let c=[];for(let f=t;fsm&&(d=d.compress(this.items.length-r.length)),d}emptyItemCount(){let e=0;return this.items.forEach(t=>{t.step||e++}),e}compress(e=this.items.length){let t=this.remapping(0,e),r=t.maps.length,i=[],s=0;return this.items.forEach((o,l)=>{if(l>=e)i.push(o),o.selection&&s++;else if(o.step){let a=o.step.map(t.slice(r)),c=a&&a.getMap();if(r--,c&&t.appendMap(c,r),a){let u=o.selection&&o.selection.map(t.slice(r));u&&s++;let d=new Oe(c.invert(),a,u),f,h=i.length-1;(f=i.length&&i[h].merge(d))?i[h]=f:i.push(d)}}else o.map&&r--},this.items.length,0),new Te(ee.from(i.reverse()),s)}}Te.empty=new Te(ee.empty,0);function om(n,e){let t;return n.forEach((r,i)=>{if(r.selection&&e--==0)return t=i,!1}),n.slice(t)}class Oe{constructor(e,t,r,i){this.map=e,this.step=t,this.selection=r,this.mirrorOffset=i}merge(e){if(this.step&&e.step&&!e.selection){let t=e.step.merge(this.step);if(t)return new Oe(t.getMap().invert(),t,this.selection)}}}class et{constructor(e,t,r,i,s){this.done=e,this.undone=t,this.prevRanges=r,this.prevTime=i,this.prevComposition=s}}const lm=20;function am(n,e,t,r){let i=t.getMeta(ut),s;if(i)return i.historyState;t.getMeta(au)&&(n=new et(n.done,n.undone,null,0,-1));let o=t.getMeta("appendedTransaction");if(t.steps.length==0)return n;if(o&&o.getMeta(ut))return o.getMeta(ut).redo?new et(n.done.addTransform(t,void 0,r,pr(e)),n.undone,El(t.mapping.maps),n.prevTime,n.prevComposition):new et(n.done,n.undone.addTransform(t,void 0,r,pr(e)),null,n.prevTime,n.prevComposition);if(t.getMeta("addToHistory")!==!1&&!(o&&o.getMeta("addToHistory")===!1)){let l=t.getMeta("composition"),a=n.prevTime==0||!o&&n.prevComposition!=l&&(n.prevTime<(t.time||0)-r.newGroupDelay||!cm(t,n.prevRanges)),c=o?Hi(n.prevRanges,t.mapping):El(t.mapping.maps);return new et(n.done.addTransform(t,a?e.selection.getBookmark():void 0,r,pr(e)),Te.empty,c,t.time,l??n.prevComposition)}else return(s=t.getMeta("rebased"))?new et(n.done.rebased(t,s),n.undone.rebased(t,s),Hi(n.prevRanges,t.mapping),n.prevTime,n.prevComposition):new et(n.done.addMaps(t.mapping.maps),n.undone.addMaps(t.mapping.maps),Hi(n.prevRanges,t.mapping),n.prevTime,n.prevComposition)}function cm(n,e){if(!e)return!1;if(!n.docChanged)return!0;let t=!1;return n.mapping.maps[0].forEach((r,i)=>{for(let s=0;s=e[s]&&(t=!0)}),t}function El(n){let e=[];for(let t=n.length-1;t>=0&&e.length==0;t--)n[t].forEach((r,i,s,o)=>e.push(s,o));return e}function Hi(n,e){if(!n)return null;let t=[];for(let r=0;r{let i=ut.getState(t);if(!i||(n?i.undone:i.done).eventCount==0)return!1;if(r){let s=um(i,t,n);s&&r(e?s.scrollIntoView():s)}return!0}}const uu=cu(!1,!0),du=cu(!0,!0);function hm(n){return n.getMeta(ut)!=null}function gi(n){const{state:e,transaction:t}=n;let{selection:r}=t,{doc:i}=t,{storedMarks:s}=t;return{...e,apply:e.apply.bind(e),applyTransaction:e.applyTransaction.bind(e),plugins:e.plugins,schema:e.schema,reconfigure:e.reconfigure.bind(e),toJSON:e.toJSON.bind(e),get storedMarks(){return s},get selection(){return r},get doc(){return i},get tr(){return r=t.selection,i=t.doc,s=t.storedMarks,t}}}var Yt=class fu{constructor(e){this.editor=e.editor,this.rawCommands=this.editor.extensionManager.commands,this.customState=e.state}get hasCustomState(){return!!this.customState}get state(){return this.customState||this.editor.state}get commands(){const{rawCommands:e,editor:t,state:r}=this,{view:i}=t,{tr:s}=r,o=this.buildProps(s);return Object.fromEntries(Object.entries(e).map(([l,a])=>[l,(...u)=>{const d=a(...u)(o);return!s.getMeta("preventDispatch")&&!this.hasCustomState&&i.dispatch(s),d}]))}get chain(){return()=>this.createChain()}get can(){return()=>this.createCan()}createChain(e,t=!0){const{rawCommands:r,editor:i,state:s}=this,{view:o}=i,l=[],a=!!e,c=e||s.tr,u=()=>(!a&&t&&!c.getMeta("preventDispatch")&&!this.hasCustomState&&o.dispatch(c),l.every(f=>f===!0)),d={...Object.fromEntries(Object.entries(r).map(([f,h])=>[f,(...m)=>{const g=this.buildProps(c,t),y=h(...m)(g);return l.push(y),d}])),run:u};return d}static createFakeChain(){const e=new Proxy({},{get:(t,r)=>{if(r!=="then")return r==="run"?()=>!1:()=>e}});return e}createCan(e){const{rawCommands:t,state:r}=this,i=!1,s=e||r.tr,o=this.buildProps(s,i);return{...Object.fromEntries(Object.entries(t).map(([l,a])=>[l,(...c)=>a(...c)({...o,dispatch:void 0})])),chain:()=>this.createChain(s,i)}}static createFallbackCan(){const e=fu.createFakeChain();return new Proxy({chain:()=>e},{get:(t,r)=>{if(r!=="then")return r==="chain"?t.chain:()=>!1}})}buildProps(e,t=!0){const{rawCommands:r,editor:i,state:s}=this,{view:o}=i,l={tr:e,editor:i,view:o,state:gi({state:s,transaction:e}),dispatch:t?()=>{}:void 0,chain:()=>this.createChain(e,t),can:()=>this.createCan(e),get commands(){return Object.fromEntries(Object.entries(r).map(([a,c])=>[a,(...u)=>c(...u)(l)]))}};return l}};const pm=()=>({editor:n,view:e})=>(requestAnimationFrame(()=>{if(!n.isDestroyed){var t;e.dom.blur(),(t=window)===null||t===void 0||(t=t.getSelection())===null||t===void 0||t.removeAllRanges()}}),!0),mm=(n=!0)=>({commands:e})=>e.setContent("",{emitUpdate:n}),gm=()=>({state:n,tr:e,dispatch:t})=>{const{selection:r}=e,{ranges:i}=r;return t&&i.forEach(({$from:s,$to:o})=>{n.doc.nodesBetween(s.pos,o.pos,(l,a)=>{if(l.type.isText)return;const{doc:c,mapping:u}=e,d=c.resolve(u.map(a)),f=c.resolve(u.map(a+l.nodeSize)),h=d.blockRange(f);if(!h)return;const p=on(h);if(l.type.isTextblock){const{defaultType:m}=d.parent.contentMatchAt(d.index());e.setNodeMarkup(h.start,m)}(p||p===0)&&e.lift(h,p)})}),!0},ym=n=>e=>n(e),bm=()=>({state:n,dispatch:e})=>wc(n,e),km=(n,e)=>({editor:t,tr:r})=>{const{state:i}=t,s=i.doc.slice(n.from,n.to);r.deleteRange(n.from,n.to);const o=r.mapping.map(e);return r.insert(o,s.content),r.setSelection(new v(r.doc.resolve(Math.max(o-1,0)))),!0},wm=()=>({tr:n,dispatch:e})=>{const{selection:t}=n,r=t.$anchor.node();if(r.content.size>0)return!1;const i=n.selection.$anchor;for(let s=i.depth;s>0;s-=1)if(i.node(s).type===r.type){if(e){const o=i.before(s),l=i.after(s);n.delete(o,l).scrollIntoView()}return!0}return!1};function X(n,e){if(typeof n=="string"){if(!e.nodes[n])throw Error(`There is no node type named '${n}'. Maybe you forgot to add the extension?`);return e.nodes[n]}return n}const Sm=n=>({tr:e,state:t,dispatch:r})=>{const i=X(n,t.schema),s=e.selection.$anchor;for(let o=s.depth;o>0;o-=1)if(s.node(o).type===i){if(r){const l=s.before(o),a=s.after(o);e.delete(l,a).scrollIntoView()}return!0}return!1},Cm=n=>({tr:e,dispatch:t})=>{const{from:r,to:i}=n;return t&&e.delete(r,i),!0},xm=n=>n.content?/^text(\*|\+)/.test(n.content):!1,Nl=(n,e,t)=>{if(!n.parent.isInline||t==="left"&&n.pos>n.start()||t==="right"&&n.pos({from:Nl(n,t,"left"),to:Nl(e,t,"right")}),Mm=()=>({state:n,dispatch:e})=>{if(n.selection.empty)return!1;if(e){const t=n.tr,{ranges:r}=n.selection,i=t.steps.length;r.forEach(s=>{const o=t.mapping.slice(i),l=t.doc.resolve(o.map(s.$from.pos)),a=t.doc.resolve(o.map(s.$to.pos)),{from:c,to:u}=vm(l,a,n.schema);t.deleteRange(c,u)}),t.selection.empty||t.setSelection(v.near(t.doc.resolve(t.selection.from))),t.scrollIntoView(),e(t)}return!0},Tm=()=>({commands:n})=>n.keyboardShortcut("Enter"),Em=()=>({state:n,dispatch:e})=>Qf(n,e);function ao(n){return Object.prototype.toString.call(n)==="[object RegExp]"}function Nr(n,e,t={strict:!0}){const r=Object.keys(e);return r.length?r.every(i=>t.strict?e[i]===n[i]:ao(e[i])?e[i].test(n[i]):e[i]===n[i]):!0}function hu(n,e,t={}){return n.find(r=>r.type===e&&Nr(Object.fromEntries(Object.keys(t).map(i=>[i,r.attrs[i]])),t))}function Ol(n,e,t={}){return!!hu(n,e,t)}function co(n,e,t){if(!n||!e)return;let r=n.parent.childAfter(n.parentOffset);if((!r.node||!r.node.marks.some(a=>a.type===e))&&(r=n.parent.childBefore(n.parentOffset)),!r.node||!r.node.marks.some(a=>a.type===e))return;if(!t){const a=r.node.marks.find(c=>c.type===e);a&&(t=a.attrs)}if(!hu([...r.node.marks],e,t))return;let i=r.index,s=n.start()+r.offset,o=i+1,l=s+r.node.nodeSize;for(;i>0&&Ol([...n.parent.child(i-1).marks],e,t);)i-=1,s-=n.parent.child(i).nodeSize;for(;o({tr:t,state:r,dispatch:i})=>{const s=Ye(n,r.schema),{doc:o,selection:l}=t,{$from:a,from:c,to:u}=l;if(i){const d=co(a,s,e);if(d&&d.from<=c&&d.to>=u){const f=v.create(o,d.from,d.to);t.setSelection(f)}}return!0},Nm=n=>e=>{const t=typeof n=="function"?n(e):n;for(let r=0;r({editor:t,view:r,tr:i,dispatch:s})=>{e={scrollIntoView:!0,...e};const o=()=>{(Or()||Rl())&&r.dom.focus(),Om()&&!Or()&&!Rl()&&r.dom.focus({preventScroll:!0}),requestAnimationFrame(()=>{t.isDestroyed||(r.focus(),e?.scrollIntoView&&t.commands.scrollIntoView())})};try{if(r.hasFocus()&&n===null||n===!1)return!0}catch{return!1}if(s&&n===null&&!pu(t.state.selection))return o(),!0;const l=ws(i.doc,n)||t.state.selection,a=t.state.selection.eq(l);return s&&(a||i.setSelection(l),a&&i.storedMarks&&i.setStoredMarks(i.storedMarks),o()),!0},Dm=(n,e)=>t=>n.every((r,i)=>e(r,{...t,index:i})),Im=(n,e)=>({tr:t,commands:r})=>r.insertContentAt({from:t.selection.from,to:t.selection.to},n,e),mu=n=>{const e=n.childNodes;for(let t=e.length-1;t>=0;t-=1){const r=e[t];r.nodeType===3&&r.nodeValue&&/^(\n\s\s|\n)$/.test(r.nodeValue)?n.removeChild(r):r.nodeType===1&&mu(r)}return n};function xt(n){if(typeof window>"u")throw new Error("[tiptap error]: there is no window object available, so this function cannot be used");const e=`${n}`,t=new window.DOMParser().parseFromString(e,"text/html").body;return mu(t)}function gu(n){return typeof n?.nodesBetween=="function"}function tn(n,e,t){if(gu(n))return n;const r=typeof n=="object"&&n!==null;t={slice:!0,parseOptions:{},...t};const i=typeof n=="string";if(r)try{if(Array.isArray(n)&&n.length>0)return b.fromArray(n.map(o=>e.nodeFromJSON(o)));const s=e.nodeFromJSON(n);return t.errorOnInvalidContent&&s.check(),s}catch(s){if(t.errorOnInvalidContent)throw new Error("[tiptap error]: Invalid JSON content",{cause:s});return console.warn("[tiptap warn]: Invalid content.","Passed value:",n,"Error:",s),tn("",e,t)}if(i){if(t.errorOnInvalidContent){let o=!1,l="";const a=new Ka({topNode:e.spec.topNode,marks:e.spec.marks,nodes:e.spec.nodes.append({__tiptap__private__unknown__catch__all__node:{content:"inline*",group:"block",parseDOM:[{tag:"*",getAttrs:c=>(o=!0,l=typeof c=="string"?c:c.outerHTML,null)}]}})});if(t.slice?Ke.fromSchema(a).parseSlice(xt(n),t.parseOptions):Ke.fromSchema(a).parse(xt(n),t.parseOptions),t.errorOnInvalidContent&&o)throw new Error("[tiptap error]: Invalid HTML content",{cause:new Error(`Invalid element found: ${l}`)})}const s=Ke.fromSchema(e);return t.slice?s.parseSlice(xt(n),t.parseOptions).content:s.parse(xt(n),t.parseOptions)}return tn("",e,t)}function yu(n){return!("type"in n)}function bu(n,e,t){const r=n.steps.length-1;if(r{o===0&&(o=u)}),n.setSelection(N.near(n.doc.resolve(o),t))}const Lm=(n,e,t)=>({tr:r,dispatch:i,editor:s})=>{if(i){t={parseOptions:s.options.parseOptions,updateSelection:!0,applyInputRules:!1,applyPasteRules:!1,...t};let l;const a=g=>{s.emit("contentError",{editor:s,error:g,disableCollaboration:()=>{"collaboration"in s.storage&&typeof s.storage.collaboration=="object"&&s.storage.collaboration&&(s.storage.collaboration.isDisabled=!0)}})},c={preserveWhitespace:"full",...t.parseOptions};if(!t.errorOnInvalidContent&&!s.options.enableContentCheck&&s.options.emitContentError)try{tn(e,s.schema,{parseOptions:c,errorOnInvalidContent:!0})}catch(g){a(g)}try{var o;l=tn(e,s.schema,{parseOptions:c,errorOnInvalidContent:(o=t.errorOnInvalidContent)!==null&&o!==void 0?o:s.options.enableContentCheck})}catch(g){return a(g),!1}let{from:u,to:d}=typeof n=="number"?{from:n,to:n}:{from:n.from,to:n.to},f=!0,h=!0;const p=yu(l)?l.content:[l];if(p.forEach(g=>{g.check(),f=f?g.isText&&g.marks.length===0:!1,h=h?g.isBlock:!1}),u===d&&h){const{parent:g}=r.doc.resolve(u);g.isTextblock&&!g.type.spec.code&&!g.childCount&&(u-=1,d+=1)}let m;if(f)Array.isArray(e)?m=e.map(g=>g.text||"").join(""):gu(e)?m=p.map(g=>{var y;return(y=g.text)!==null&&y!==void 0?y:""}).join(""):typeof e=="object"&&e&&e.text?m=e.text:m=e,r.insertText(m,u,d);else{m=b.from(p);const g=r.doc.resolve(u),y=g.node(),k=g.parentOffset===0,w=y.isText||y.isTextblock,C=y.content.size>0;k&&w&&C&&h&&(u=Math.max(0,u-1)),r.replaceWith(u,d,p)}t.updateSelection&&bu(r,r.steps.length-1,-1),t.applyInputRules&&r.setMeta("applyInputRules",{from:u,text:m}),t.applyPasteRules&&r.setMeta("applyPasteRules",{from:u,text:m})}return!0};function ku(n){for(let e=0;e({tr:e,dispatch:t,editor:r})=>{const{pos:i,attrs:s,content:o,updateSelection:l=!0}=n;let a;typeof i=="number"?a=e.doc.resolve(i):i?a=i:a=e.selection.$from;const c=ku(a.parent.contentMatchAt(a.index()));if(!c)return!1;const u=Object.keys(c.spec.attrs||{}),d=s?Object.fromEntries(Object.entries(s).filter(([h])=>u.includes(h))):{};let f;if(o){const h=tn(o,r.schema);f=c.createAndFill(d,h)}else f=c.createAndFill(d);return f?(t&&(e.insert(a.pos,f),l&&bu(e,e.steps.length-1,-1)),!0):!1},zm=()=>({state:n,dispatch:e})=>Gf(n,e),Bm=()=>({state:n,dispatch:e})=>Yf(n,e),$m=()=>({state:n,dispatch:e})=>hc(n,e),Hm=()=>({state:n,dispatch:e})=>yc(n,e),wu=(n,e)=>{const t=n.resolve(e),r=t.nodeBefore,i=t.nodeAfter;return!r||!i?!1:!r.type.spec.isolating&&!i.type.spec.isolating},Fm=()=>({state:n,dispatch:e,tr:t})=>{try{const r=ui(n.doc,n.selection.$from.pos,-1);return r==null||!wu(n.doc,r)?!1:(t.join(r,2),e&&e(t),!0)}catch{return!1}},Vm=()=>({state:n,dispatch:e,tr:t})=>{try{const r=ui(n.doc,n.selection.$from.pos,1);return r==null||!wu(n.doc,r)?!1:(t.join(r,2),e&&e(t),!0)}catch{return!1}},Wm=()=>({state:n,dispatch:e})=>qf(n,e),jm=()=>({state:n,dispatch:e})=>Jf(n,e);function Su(){return typeof navigator<"u"?/Mac/.test(navigator.platform):!1}function _m(n){const e=n.split(/-(?!$)/);let t=e[e.length-1];t==="Space"&&(t=" ");let r,i,s,o;for(let l=0;l({editor:e,view:t,tr:r,dispatch:i})=>{const s=_m(n).split(/-(?!$)/),o=s.find(c=>!["Alt","Ctrl","Meta","Shift"].includes(c)),l=new KeyboardEvent("keydown",{key:o==="Space"?" ":o,altKey:s.includes("Alt"),ctrlKey:s.includes("Ctrl"),metaKey:s.includes("Meta"),shiftKey:s.includes("Shift"),bubbles:!0,cancelable:!0}),a=e.captureTransaction(()=>{t.someProp("handleKeyDown",c=>c(t,l))});return a?.steps.forEach(c=>{const u=c.map(r.mapping);u&&i&&r.maybeStep(u)}),!0};function Ge(n,e,t={}){const{from:r,to:i,empty:s}=n.selection,o=e?X(e,n.schema):null,l=[];n.doc.nodesBetween(r,i,(u,d)=>{if(u.isText)return;const f=Math.max(r,d),h=Math.min(i,d+u.nodeSize);l.push({node:u,from:f,to:h})});const a=i-r,c=l.filter(u=>o?o.name===u.node.type.name:!0).filter(u=>Nr(u.node.attrs,t,{strict:!1}));return s?!!c.length:c.reduce((u,d)=>u+d.to-d.from,0)>=a}const Km=(n,e={})=>({state:t,dispatch:r})=>Ge(t,X(n,t.schema),e)?Xf(t,r):!1,qm=()=>({state:n,dispatch:e})=>Sc(n,e),Jm=n=>({state:e,dispatch:t})=>{const r=X(n,e.schema);return ch(r)(e,t)},Gm=()=>({state:n,dispatch:e})=>kc(n,e);function yi(n,e){return e.nodes[n]?"node":e.marks[n]?"mark":null}function Dl(n,e){const t=typeof e=="string"?[e]:e;return Object.keys(n).reduce((r,i)=>(t.includes(i)||(r[i]=n[i]),r),{})}const Ym=(n,e)=>({tr:t,state:r,dispatch:i})=>{let s=null,o=null;const l=yi(typeof n=="string"?n:n.name,r.schema);if(!l)return!1;l==="node"&&(s=X(n,r.schema)),l==="mark"&&(o=Ye(n,r.schema));let a=!1;return t.selection.ranges.forEach(c=>{r.doc.nodesBetween(c.$from.pos,c.$to.pos,(u,d)=>{s&&s===u.type&&(a=!0,i&&t.setNodeMarkup(d,void 0,Dl(u.attrs,e))),o&&u.marks.length&&u.marks.forEach(f=>{o===f.type&&(a=!0,i&&t.addMark(d,d+u.nodeSize,o.create(Dl(f.attrs,e))))})})}),a},Xm=()=>({tr:n,dispatch:e})=>(e&&n.scrollIntoView(),!0),Qm=()=>({tr:n,dispatch:e})=>{if(e){const t=new ye(n.doc);n.setSelection(t)}return!0},Zm=()=>({state:n,dispatch:e})=>mc(n,e),eg=()=>({state:n,dispatch:e})=>bc(n,e),tg=()=>({state:n,dispatch:e})=>th(n,e),ng=()=>({state:n,dispatch:e})=>ih(n,e),rg=()=>({state:n,dispatch:e})=>rh(n,e);function Ss(n,e,t={},r={}){return tn(n,e,{slice:!1,parseOptions:t,errorOnInvalidContent:r.errorOnInvalidContent})}const ig=(n,{errorOnInvalidContent:e,emitUpdate:t=!0,parseOptions:r={}}={})=>({editor:i,tr:s,dispatch:o,commands:l})=>{const{doc:a}=s;if(r.preserveWhitespace!=="full"){const c=Ss(n,i.schema,r,{errorOnInvalidContent:e??i.options.enableContentCheck});if(o){const u=yu(c)?c.content:[c];s.replaceWith(0,a.content.size,u).setMeta("preventUpdate",!t)}return!0}return o&&s.setMeta("preventUpdate",!t),l.insertContentAt({from:0,to:a.content.size},n,{parseOptions:r,errorOnInvalidContent:e??i.options.enableContentCheck})};function Cu(n,e){const t=Ye(e,n.schema),{from:r,to:i,empty:s}=n.selection,o=[];s?(n.storedMarks&&o.push(...n.storedMarks),o.push(...n.selection.$head.marks())):n.doc.nodesBetween(r,i,a=>{o.push(...a.marks)});const l=o.find(a=>a.type.name===t.name);return l?{...l.attrs}:{}}function xu(n,e){const t=new Ks(n);return e.forEach(r=>{r.steps.forEach(i=>{t.step(i)})}),t}function sg(n,e,t){const r=[];return n.nodesBetween(e.from,e.to,(i,s)=>{t(i)&&r.push({node:i,pos:s})}),r}function $n(n,e){for(let t=n.depth;t>0;t-=1){const r=n.node(t);if(e(r))return{pos:t>0?n.before(t):0,start:n.start(t),depth:t,node:r}}}function bi(n){return e=>$n(e.$from,n)}function M(n,e,t){return n.config[e]===void 0&&n.parent?M(n.parent,e,t):typeof n.config[e]=="function"?n.config[e].bind({...t,parent:n.parent?M(n.parent,e,t):null}):n.config[e]}function uo(n){return n.map(e=>{const t=M(e,"addExtensions",{name:e.name,options:e.options,storage:e.storage});return t?[e,...uo(t())]:e}).flat(10)}function fo(n,e){const t=ht.fromSchema(e).serializeFragment(n),r=document.implementation.createHTMLDocument().createElement("div");return r.appendChild(t),r.innerHTML}function Cs(n){return typeof n=="function"}function L(n,e=void 0,...t){return Cs(n)?e?n.bind(e)(...t):n(...t):n}function og(n={}){return Object.keys(n).length===0&&n.constructor===Object}function nn(n){return{baseExtensions:n.filter(e=>e.type==="extension"),nodeExtensions:n.filter(e=>e.type==="node"),markExtensions:n.filter(e=>e.type==="mark")}}function vu(n){const e=[],{nodeExtensions:t,markExtensions:r}=nn(n),i=[...t,...r],s={default:null,validate:void 0,rendered:!0,renderHTML:null,parseHTML:null,keepOnSplit:!0,isRequired:!1},o=t.filter(c=>c.name!=="text").map(c=>c.name),l=r.map(c=>c.name),a=[...o,...l];return n.forEach(c=>{const u=M(c,"addGlobalAttributes",{name:c.name,options:c.options,storage:c.storage,extensions:i});u&&u().forEach(d=>{let f;Array.isArray(d.types)?f=d.types:d.types==="*"?f=a:d.types==="nodes"?f=o:d.types==="marks"?f=l:f=[],f.forEach(h=>{Object.entries(d.attributes).forEach(([p,m])=>{e.push({type:h,name:p,attribute:{...s,...m}})})})})}),i.forEach(c=>{const u=M(c,"addAttributes",{name:c.name,options:c.options,storage:c.storage});if(!u)return;const d=u();Object.entries(d).forEach(([f,h])=>{const p={...s,...h};typeof p?.default=="function"&&(p.default=p.default()),p?.isRequired&&p?.default===void 0&&delete p.default,e.push({type:c.name,name:f,attribute:p})})}),e}function lg(n){const e=[];let t="",r=!1,i=!1,s=0;const o=n.length;for(let l=0;l0){s-=1,t+=a;continue}if(a===";"&&s===0){e.push(t),t="";continue}}t+=a}return t&&e.push(t),e}function Il(n){const e=[],t=lg(n||""),r=t.length;for(let i=0;i!!e).reduce((e,t)=>{const r={...e};return Object.entries(t).forEach(([i,s])=>{if(i==="__proto__"){Object.defineProperty(r,i,{configurable:!0,enumerable:!0,value:s,writable:!0});return}if(!r[i]){r[i]=s;return}if(i==="class"){const o=s?String(s).split(" "):[],l=r[i]?r[i].split(" "):[],a=o.filter(c=>!l.includes(c));r[i]=[...l,...a].join(" ")}else if(i==="style"){const o=new Map([...Il(r[i]),...Il(s)]);r[i]=Array.from(o.entries()).map(([l,a])=>`${l}: ${a}`).join("; ")}else r[i]=s}),r},{})}function rn(n,e){return e.filter(t=>t.type===n.type.name).filter(t=>t.attribute.rendered).map(t=>t.attribute.renderHTML?t.attribute.renderHTML(n.attrs)||{}:{[t.name]:n.attrs[t.name]}).reduce((t,r)=>H(t,r),{})}function ag(n){return typeof n!="string"?n:n.match(/^[+-]?(?:\d*\.)?\d+$/)?Number(n):n==="true"?!0:n==="false"?!1:n}function Ll(n,e){return"style"in n?n:{...n,getAttrs:t=>{const r=n.getAttrs?n.getAttrs(t):n.attrs;if(r===!1)return!1;const i=e.reduce((s,o)=>{const l=o.attribute.parseHTML?o.attribute.parseHTML(t):ag(t.getAttribute(o.name));return l==null?s:{...s,[o.name]:l}},{});return{...r,...i}}}}function Pl(n){return Object.fromEntries(Object.entries(n).filter(([e,t])=>e==="attrs"&&og(t)?!1:t!=null))}function zl(n){var e,t;const r={};return!(!(n==null||(e=n.attribute)===null||e===void 0)&&e.isRequired)&&"default"in(n?.attribute||{})&&(r.default=n.attribute.default),(n==null||(t=n.attribute)===null||t===void 0?void 0:t.validate)!==void 0&&(r.validate=n.attribute.validate),[n.name,r]}function cg(n,e){var t;const r=vu(n),{nodeExtensions:i,markExtensions:s}=nn(n),o=(t=i.find(c=>M(c,"topNode")))===null||t===void 0?void 0:t.name,l=Object.fromEntries(i.map(c=>{const u=r.filter(g=>g.type===c.name),d={name:c.name,options:c.options,storage:c.storage,editor:e},f=Pl({...n.reduce((g,y)=>{const k=M(y,"extendNodeSchema",d);return{...g,...k?k(c):{}}},{}),content:L(M(c,"content",d)),marks:L(M(c,"marks",d)),group:L(M(c,"group",d)),inline:L(M(c,"inline",d)),atom:L(M(c,"atom",d)),selectable:L(M(c,"selectable",d)),draggable:L(M(c,"draggable",d)),code:L(M(c,"code",d)),whitespace:L(M(c,"whitespace",d)),linebreakReplacement:L(M(c,"linebreakReplacement",d)),defining:L(M(c,"defining",d)),isolating:L(M(c,"isolating",d)),attrs:Object.fromEntries(u.map(zl))}),h=L(M(c,"parseHTML",d));h&&(f.parseDOM=h.map(g=>Ll(g,u)));const p=M(c,"renderHTML",d);p&&(f.toDOM=g=>p({node:g,HTMLAttributes:rn(g,u)}));const m=M(c,"renderText",d);return m&&(f.toText=m),[c.name,f]})),a=Object.fromEntries(s.map(c=>{const u=r.filter(m=>m.type===c.name),d={name:c.name,options:c.options,storage:c.storage,editor:e},f=Pl({...n.reduce((m,g)=>{const y=M(g,"extendMarkSchema",d);return{...m,...y?y(c):{}}},{}),inclusive:L(M(c,"inclusive",d)),excludes:L(M(c,"excludes",d)),group:L(M(c,"group",d)),spanning:L(M(c,"spanning",d)),code:L(M(c,"code",d)),attrs:Object.fromEntries(u.map(zl))}),h=L(M(c,"parseHTML",d));h&&(f.parseDOM=h.map(m=>Ll(m,u)));const p=M(c,"renderHTML",d);return p&&(f.toDOM=m=>p({mark:m,HTMLAttributes:rn(m,u)})),[c.name,f]}));return new Ka({topNode:o,nodes:l,marks:a})}function ug(n){const e=n.filter((t,r)=>n.indexOf(t)!==r);return Array.from(new Set(e))}function Sn(n){return n.sort((t,r)=>{const i=M(t,"priority")||100,s=M(r,"priority")||100;return i>s?-1:ir.name));return t.length&&console.warn(`[tiptap warn]: Duplicate extension names found: [${t.map(r=>`'${r}'`).join(", ")}]. This can lead to issues.`),e}function Tu(n,e,t){const{from:r,to:i}=e,{blockSeparator:s=` -`,textSerializers:o={}}=t||{};let l="";return n.nodesBetween(r,i,(a,c,u,d)=>{a.isBlock&&c>r&&(l+=s);const f=o?.[a.type.name];if(f)return u&&(l+=f({node:a,pos:c,parent:u,index:d,range:e})),!1;if(a.isText){var h;l+=a==null||(h=a.text)===null||h===void 0?void 0:h.slice(Math.max(r,c)-c,i-c)}}),l}function Ip(n,e){return xc(n,{from:0,to:n.content.size},e)}function wc(n){return Object.fromEntries(Object.entries(n.nodes).filter(([,e])=>e.spec.toText).map(([e,t])=>[e,t.spec.toText]))}function Rp(n,e){const t=q(e,n.schema),{from:r,to:i}=n.selection,s=[];n.doc.nodesBetween(r,i,l=>{s.push(l)});const o=s.reverse().find(l=>l.type.name===t.name);return o?{...o.attrs}:{}}function Cc(n,e){const t=qr(typeof e=="string"?e:e.name,n.schema);return t==="node"?Rp(n,e):t==="mark"?yc(n,e):{}}function Lp(n,e=JSON.stringify){const t={};return n.filter(r=>{const i=e(r);return Object.prototype.hasOwnProperty.call(t,i)?!1:t[i]=!0})}function Pp(n){const e=Lp(n);return e.length===1?e:e.filter((t,r)=>!e.filter((i,s)=>s!==r).some(i=>t.oldRange.from>=i.oldRange.from&&t.oldRange.to<=i.oldRange.to&&t.newRange.from>=i.newRange.from&&t.newRange.to<=i.newRange.to))}function Gr(n){const{mapping:e,steps:t}=n,r=[];return e.maps.forEach((i,s)=>{const o=[];if(i.ranges.length)i.forEach((l,a)=>{o.push({from:l,to:a})});else{const{from:l,to:a}=t[s];if(l===void 0||a===void 0)return;o.push({from:l,to:a})}o.forEach(({from:l,to:a})=>{const c=e.slice(s).map(l,-1),u=e.slice(s).map(a),d=e.invert().map(c,-1),f=e.invert().map(u);r.push({oldRange:{from:d,to:f},newRange:{from:c,to:u}})})}),Pp(r)}function Yr(n,e,t){const r=[];return n===e?t.resolve(n).marks().forEach(i=>{const s=Ms(t.resolve(n),i.type);s&&r.push({mark:i,...s})}):t.nodesBetween(n,e,(i,s)=>{!i||i?.nodeSize===void 0||r.push(...i.marks.map(o=>({from:s,to:s+i.nodeSize,mark:o})))}),r}const Bp=(n,e,t,r=20)=>{const i=n.doc.resolve(t);let s=r,o=null;for(;s>0&&o===null;){const l=i.node(s);l?.type.name===e?o=l:s-=1}return[o,s]},zp=n=>{const e=n.depth-1;if(e<0)return null;const t=n.index(e);return t===0?null:n.node(e).child(t-1)};function Nt(n,e){return e.nodes[n]||e.marks[n]||null}function Gn(n,e,t){return Object.fromEntries(Object.entries(t).filter(([r])=>{const i=n.find(s=>s.type===e&&s.name===r);return i?i.attribute.keepOnSplit:!1}))}const $p=(n,e=500)=>{let t="";const r=n.parentOffset;return n.parent.nodesBetween(Math.max(0,r-e),r,(i,s,o,l)=>{var a,c;const u=((a=(c=i.type.spec).toText)===null||a===void 0?void 0:a.call(c,{node:i,pos:s,parent:o,index:l}))||i.textContent||"%leaf%";t+=i.isAtom&&!i.isText?u:u.slice(0,Math.max(0,r-s))}),t};function qi(n,e,t={}){const{empty:r,ranges:i}=n.selection,s=e?je(e,n.schema):null;if(r)return!!(n.storedMarks||n.selection.$from.marks()).filter(u=>s?s.name===u.type.name:!0).find(u=>lr(u.attrs,t,{strict:!1}));let o=0;const l=[];if(i.forEach(({$from:u,$to:d})=>{const f=u.pos,h=d.pos;n.doc.nodesBetween(f,h,(p,m)=>{if(s&&p.inlineContent&&!p.type.allowsMarkType(s))return!1;if(!p.isText&&!p.marks.length)return;const g=Math.max(f,m),y=Math.min(h,m+p.nodeSize),S=y-g;o+=S,l.push(...p.marks.map(x=>({mark:x,from:g,to:y})))})}),o===0)return!1;const a=l.filter(u=>s?s.name===u.mark.type.name:!0).filter(u=>lr(u.mark.attrs,t,{strict:!1})).reduce((u,d)=>u+d.to-d.from,0),c=l.filter(u=>s?u.mark.type!==s&&u.mark.type.excludes(s):!0).reduce((u,d)=>u+d.to-d.from,0);return(a>0?a+c:a)>=o}function Fp(n,e,t={}){if(!e)return He(n,null,t)||qi(n,null,t);const r=qr(e,n.schema);return r==="node"?He(n,e,t):r==="mark"?qi(n,e,t):!1}const Vp=(n,e)=>{const{$from:t,$to:r,$anchor:i}=n.selection;if(e){const s=Jr(l=>l.type.name===e)(n.selection);if(!s)return!1;const o=n.doc.resolve(s.pos+1);return i.pos+1===o.end()}return!(r.parentOffset{const{$from:e,$to:t}=n.selection;return!(e.parentOffset>0||e.pos!==t.pos)};function Xo(n,e){return Array.isArray(e)?e.some(t=>(typeof t=="string"?t:t.name)===n.name):e}function gi(n,e){const{nodeExtensions:t}=Kt(e),r=t.find(s=>s.name===n);if(!r)return!1;const i=L(M(r,"group",{name:r.name,options:r.options,storage:r.storage}));return typeof i!="string"?!1:i.split(" ").includes("list")}function Dn(n,{checkChildren:e=!0,ignoreWhitespace:t=!1}={}){if(t){if(n.type.name==="hardBreak")return!0;if(n.isText){var r;return!/\S/.test((r=n.text)!==null&&r!==void 0?r:"")}}if(n.isText)return!n.text;if(n.isAtom||n.isLeaf)return!1;if(n.content.childCount===0)return!0;if(e){let i=!0;return n.content.forEach(s=>{i!==!1&&(Dn(s,{ignoreWhitespace:t,checkChildren:e})||(i=!1))}),i}return!1}function Mc(n){return n instanceof E}var vc=class Ec{constructor(e){this.position=e}static fromJSON(e){return new Ec(e.position)}toJSON(){return{position:this.position}}};function jp(n,e){const t=e.mapping.mapResult(n.position);return{position:new vc(t.pos),mapResult:t}}function Wp(n){return new vc(n)}function Kp(n,e,t){const{selection:r}=e;let i=null;if(cc(r)&&(i=r.$cursor),i){var s;const l=(s=n.storedMarks)!==null&&s!==void 0?s:i.marks();return i.parent.type.allowsMarkType(t)&&(!!t.isInSet(l)||!l.some(a=>a.type.excludes(t)))}const{ranges:o}=r;return o.some(({$from:l,$to:a})=>{let c=l.depth===0?n.doc.inlineContent&&n.doc.type.allowsMarkType(t):!1;return n.doc.nodesBetween(l.pos,a.pos,(u,d,f)=>{if(c)return!1;if(u.isInline){const h=!f||f.type.allowsMarkType(t),p=!!t.isInSet(u.marks)||!u.marks.some(m=>m.type.excludes(t));c=h&&p}return!c}),c})}const _p=(n,e={})=>({tr:t,state:r,dispatch:i})=>{const{selection:s}=t,{empty:o,ranges:l}=s,a=je(n,r.schema);if(i)if(o){const c=yc(r,a);t.addStoredMark(a.create({...c,...e}))}else l.forEach(c=>{const u=c.$from.pos,d=c.$to.pos;r.doc.nodesBetween(u,d,(f,h)=>{const p=Math.max(h,u),m=Math.min(h+f.nodeSize,d);f.marks.find(g=>g.type===a)?f.marks.forEach(g=>{a===g.type&&t.addMark(p,m,a.create({...g.attrs,...e}))}):t.addMark(p,m,a.create(e))})});return Kp(r,t,a)},Up=(n,e)=>({tr:t})=>(t.setMeta(n,e),!0),qp=(n,e={})=>({state:t,dispatch:r,chain:i})=>{const s=q(n,t.schema);let o;return t.selection.$anchor.sameParent(t.selection.$head)&&(o=t.selection.$anchor.parent.attrs),s.isTextblock?i().command(({commands:l})=>co(s,{...o,...e})(t)?!0:l.clearNodes()).command(({state:l})=>co(s,{...o,...e})(l,r)).run():(console.warn('[tiptap warn]: Currently "setNode()" only supports text block nodes.'),!1)},Jp=n=>({tr:e,dispatch:t})=>{if(t){const{doc:r}=e,i=ht(n,0,r.content.size),s=E.create(r,i);e.setSelection(s)}return!0},Gp=(n,e)=>({tr:t,state:r,dispatch:i})=>{const{selection:s}=r;let o,l;return typeof e=="number"?(o=e,l=e):e&&"from"in e&&"to"in e?(o=e.from,l=e.to):(o=s.from,l=s.to),i&&t.doc.nodesBetween(o,l,(a,c)=>{a.isText||t.setNodeMarkup(c,void 0,{...a.attrs,dir:n})}),!0},Yp=n=>({tr:e,dispatch:t})=>{if(t){const{doc:r}=e,{from:i,to:s}=typeof n=="number"?{from:n,to:n}:n,o=T.atStart(r).from,l=T.atEnd(r).to,a=ht(i,o,l),c=ht(s,o,l),u=T.create(r,a,c);e.setSelection(u)}return!0},Xp=n=>({state:e,dispatch:t})=>{const r=q(n,e.schema);return Dd(r)(e,t)};function Qo(n,e){const t=n.storedMarks||n.selection.$to.parentOffset&&n.selection.$from.marks();if(t){const r=t.filter(i=>e?.includes(i.type.name));n.tr.ensureMarks(r)}}const Qp=({keepMarks:n=!0}={})=>({tr:e,state:t,dispatch:r,editor:i})=>{const{selection:s,doc:o}=e,{$from:l,$to:a}=s,c=i.extensionManager.attributes,u=Gn(c,l.node().type.name,l.node().attrs);if(s instanceof E&&s.node.isBlock)return!l.parentOffset||!Fe(o,l.pos)?!1:(r&&(n&&Qo(t,i.extensionManager.splittableMarks),e.split(l.pos).scrollIntoView()),!0);if(!l.parent.isBlock)return!1;const d=a.parentOffset===a.parent.content.size,f=l.depth===0?void 0:pc(l.node(-1).contentMatchAt(l.indexAfter(-1)));let h=d&&f?[{type:f,attrs:u}]:void 0;const p=s instanceof T&&!s.empty?Be.create({doc:e.doc,selection:s}).tr.deleteSelection():null,m=p?p.doc:e.doc,g=p?p.mapping.map(l.pos):l.pos;let y=Fe(m,g,1,h);if(!h&&!y&&Fe(m,g,1,f?[{type:f}]:void 0)&&(y=!0,h=f?[{type:f,attrs:u}]:void 0),r){if(y){const S=e.steps.length;if(s instanceof T&&e.deleteSelection(),e.split(e.mapping.slice(S).map(l.pos),1,h),f&&!d&&!l.parentOffset&&l.parent.type!==f){const x=e.mapping.slice(S).map(l.before()),C=e.doc.resolve(x);l.node(-1).canReplaceWith(C.index(),C.index()+1,f)&&e.setNodeMarkup(e.mapping.slice(S).map(l.before()),f)}}n&&Qo(t,i.extensionManager.splittableMarks),e.scrollIntoView()}return y},Zp=(n,e={})=>({tr:t,state:r,dispatch:i,editor:s})=>{const o=q(n,r.schema),{$from:l,$to:a}=r.selection,c=r.selection.node;if(c&&c.isBlock||l.depth<2||!l.sameParent(a))return!1;const u=l.node(-1);if(u.type!==o)return!1;const d=s.extensionManager.attributes;if(l.parent.content.size===0&&l.node(-1).childCount===l.indexAfter(-1)){if(l.depth===2||l.node(-3).type!==o||l.index(-2)!==l.node(-2).childCount-1)return!1;if(i){var f;let C=b.empty;const I=l.index(-1)?1:l.index(-2)?2:3;for(let me=l.depth-I;me>=l.depth-3;me-=1)C=b.from(l.node(me).copy(C));const F=l.indexAfter(-1){if(X>-1)return!1;me.isTextblock&&me.content.size===0&&(X=at+1)}),X>-1&&t.setSelection(T.near(t.doc.resolve(X))),t.scrollIntoView()}return!0}const h=a.pos===l.end()?u.contentMatchAt(0).defaultType:null,p={...Gn(d,u.type.name,u.attrs),...e},m={...Gn(d,l.node().type.name,l.node().attrs),...e},g=l.parentOffset===0&&l.index(-1)===0,y=l.before(-1);t.delete(l.pos,a.pos);const S=g?u.attrs:p,x=h?[{type:o,attrs:S},{type:h,attrs:m}]:[{type:o,attrs:S}];if(!Fe(t.doc,l.pos,2))return!1;if(i){const{selection:C,storedMarks:I}=r,{splittableMarks:F}=s.extensionManager,A=I||C.$to.parentOffset&&C.$from.marks();if(t.split(l.pos,2,x).scrollIntoView(),g&&t.setNodeMarkup(y,void 0,p),!A||!i)return!0;const R=A.filter(P=>F.includes(P.type.name));t.ensureMarks(R)}return!0};function Zo(n){return!n||n==="1"?null:n}function Tc(n,e){return Zo(n)===Zo(e)}const yi=(n,e)=>{const t=Jr(s=>s.type===e)(n.selection);if(!t)return!0;const r=n.doc.resolve(Math.max(0,t.pos-1)).before(t.depth);if(r===void 0)return!0;const i=n.doc.nodeAt(r);return!(t.node.type===i?.type&&ot(n.doc,t.pos))||!Tc(t.node.attrs.type,i?.attrs.type)||n.join(t.pos),!0},bi=(n,e)=>{const t=Jr(s=>s.type===e)(n.selection);if(!t)return!0;const r=n.doc.resolve(t.start).after(t.depth);if(r===void 0)return!0;const i=n.doc.nodeAt(r);return!(t.node.type===i?.type&&ot(n.doc,r))||!Tc(t.node.attrs.type,i?.attrs.type)||n.join(r),!0};function em(n){const e=n.doc,t=e.firstChild;if(!t)return null;const r=e.resolve(1),i=e.resolve(t.nodeSize-1);return T.between(r,i)}const tm=(n,e,t,r={})=>({editor:i,tr:s,state:o,dispatch:l,chain:a,commands:c,can:u})=>{const{extensions:d,splittableMarks:f}=i.extensionManager,h=q(n,o.schema),p=q(e,o.schema),{selection:m,storedMarks:g}=o,{$from:y,$to:S}=m,x=y.blockRange(S),C=g||m.$to.parentOffset&&m.$from.marks();if(!x)return!1;const I=Jr(Se=>gi(Se.type.name,d))(m),F=m.from===0&&m.to===o.doc.content.size,A=o.doc.content.content,R=A.length===1?A[0]:null,P=F&&R&&gi(R.type.name,d)?{node:R,pos:0}:null,X=I??P,me=!!I&&x.depth>=1&&x.depth-I.depth<=1,at=!!P;if((me||at)&&X){if(X.node.type===h)return F&&at?a().command(({tr:Se,dispatch:Oe})=>{const xe=em(Se);return xe?(Se.setSelection(xe),Oe&&Oe(Se),!0):!1}).liftListItem(p).run():c.liftListItem(p);if(gi(X.node.type.name,d)&&h.validContent(X.node.content))return a().command(()=>(s.setNodeMarkup(X.pos,h),!0)).command(()=>yi(s,h)).command(()=>bi(s,h)).run()}return!t||!C||!l?a().command(()=>u().wrapInList(h,r)?!0:c.clearNodes()).wrapInList(h,r).command(()=>yi(s,h)).command(()=>bi(s,h)).run():a().command(()=>{const Se=u().wrapInList(h,r),Oe=C.filter(xe=>f.includes(xe.type.name));return s.ensureMarks(Oe),Se?!0:c.clearNodes()}).wrapInList(h,r).command(()=>yi(s,h)).command(()=>bi(s,h)).run()},nm=(n,e={},t={})=>({state:r,commands:i})=>{const{extendEmptyMarkRange:s=!1}=t,o=je(n,r.schema);return qi(r,o,e)?i.unsetMark(o,{extendEmptyMarkRange:s}):i.setMark(o,e)},rm=(n,e,t={})=>({state:r,commands:i})=>{const s=q(n,r.schema),o=q(e,r.schema),l=He(r,s,t);let a;return r.selection.$anchor.sameParent(r.selection.$head)&&(a=r.selection.$anchor.parent.attrs),l?i.setNode(o,a):i.setNode(s,{...a,...t})},im=(n,e={})=>({state:t,commands:r})=>{const i=q(n,t.schema);return He(t,i,e)?r.lift(i):r.wrapIn(i,e)},sm=()=>({state:n,dispatch:e})=>{const t=n.plugins;for(let r=0;r=0;a-=1)o.step(l.steps[a].invert(l.docs[a]));if(s.text){const a=o.doc.resolve(s.from).marks();o.replaceWith(s.from,s.to,n.schema.text(s.text,a))}else o.delete(s.from,s.to)}return!0}}return!1},om=(n={})=>({tr:e,dispatch:t,editor:r})=>{const{ignoreClearable:i=!1}=n,{selection:s}=e,{empty:o,ranges:l}=s;if(o)return!0;const{nonClearableMarks:a}=r.extensionManager;if(t){const c=Object.values(r.schema.marks).filter(u=>i||!a.includes(u.name));l.forEach(u=>{for(const d of c)e.removeMark(u.$from.pos,u.$to.pos,d)})}return!0},lm=(n,e={})=>({tr:t,state:r,dispatch:i})=>{const{extendEmptyMarkRange:s=!1}=e,{selection:o}=t,l=je(n,r.schema),{$from:a,empty:c,ranges:u}=o;if(!i)return!0;if(c&&s){var d;let{from:f,to:h}=o;const p=Ms(a,l,(d=a.marks().find(m=>m.type===l))===null||d===void 0?void 0:d.attrs);p&&(f=p.from,h=p.to),t.removeMark(f,h,l)}else u.forEach(f=>{t.removeMark(f.$from.pos,f.$to.pos,l)});return t.removeStoredMark(l),!0},am=n=>({tr:e,state:t,dispatch:r})=>{const{selection:i}=t;let s,o;return typeof n=="number"?(s=n,o=n):n&&"from"in n&&"to"in n?(s=n.from,o=n.to):(s=i.from,o=i.to),r&&e.doc.nodesBetween(s,o,(l,a)=>{if(l.isText)return;const c={...l.attrs};delete c.dir,e.setNodeMarkup(a,void 0,c)}),!0},cm=(n,e={})=>({tr:t,state:r,dispatch:i})=>{let s=null,o=null;const l=qr(typeof n=="string"?n:n.name,r.schema);if(!l)return!1;l==="node"&&(s=q(n,r.schema)),l==="mark"&&(o=je(n,r.schema));let a=!1;return t.selection.ranges.forEach(c=>{const u=c.$from.pos,d=c.$to.pos;let f,h,p,m;t.selection.empty?r.doc.nodesBetween(u,d,(g,y)=>{s&&s===g.type&&(a=!0,p=Math.max(y,u),m=Math.min(y+g.nodeSize,d),f=y,h=g)}):r.doc.nodesBetween(u,d,(g,y)=>{y=u&&y<=d&&(s&&s===g.type&&(a=!0,i&&t.setNodeMarkup(y,void 0,{...g.attrs,...e})),o&&g.marks.length&&g.marks.forEach(S=>{if(o===S.type&&(a=!0,i)){const x=Math.max(y,u),C=Math.min(y+g.nodeSize,d);t.addMark(x,C,o.create({...S.attrs,...e}))}}))}),h&&(f!==void 0&&i&&t.setNodeMarkup(f,void 0,{...h.attrs,...e}),o&&h.marks.length&&h.marks.forEach(g=>{o===g.type&&i&&t.addMark(p,m,o.create({...g.attrs,...e}))}))}),a},Lt=new _("__tiptap_decorations__"),um=n=>({tr:e,dispatch:t})=>(t&&e.setMeta(Lt,{type:"force",name:n}),!0),dm=(n,e={})=>({state:t,dispatch:r})=>{const i=q(n,t.schema);return Md(i,e)(t,r)},fm=(n,e={})=>({state:t,dispatch:r})=>{const i=q(n,t.schema);return vd(i,e)(t,r)};var hm=gu({blur:()=>Lh,clearContent:()=>Ph,clearNodes:()=>Bh,command:()=>zh,createParagraphNear:()=>$h,cut:()=>Fh,deleteCurrentNode:()=>Vh,deleteNode:()=>Hh,deleteRange:()=>jh,deleteSelection:()=>_h,enter:()=>Uh,exitCode:()=>qh,extendMarkRange:()=>Jh,first:()=>Gh,focus:()=>Xh,forEach:()=>Qh,insertContent:()=>Zh,insertContentAt:()=>ep,insertDefaultBlock:()=>tp,joinBackward:()=>ip,joinDown:()=>rp,joinForward:()=>sp,joinItemBackward:()=>op,joinItemForward:()=>lp,joinTextblockBackward:()=>ap,joinTextblockForward:()=>cp,joinUp:()=>np,keyboardShortcut:()=>dp,lift:()=>fp,liftEmptyBlock:()=>hp,liftListItem:()=>pp,newlineInCode:()=>mp,resetAttributes:()=>gp,scrollIntoView:()=>yp,selectAll:()=>bp,selectNodeBackward:()=>kp,selectNodeForward:()=>Sp,selectParentNode:()=>xp,selectTextblockEnd:()=>wp,selectTextblockStart:()=>Cp,setContent:()=>Mp,setMark:()=>_p,setMeta:()=>Up,setNode:()=>qp,setNodeSelection:()=>Jp,setTextDirection:()=>Gp,setTextSelection:()=>Yp,sinkListItem:()=>Xp,splitBlock:()=>Qp,splitListItem:()=>Zp,toggleList:()=>tm,toggleMark:()=>nm,toggleNode:()=>rm,toggleWrap:()=>im,undoInputRule:()=>sm,unsetAllMarks:()=>om,unsetMark:()=>lm,unsetTextDirection:()=>am,updateAttributes:()=>cm,updateDecorations:()=>um,wrapIn:()=>dm,wrapInList:()=>fm});const Gt=new WeakMap;function pm(n,e){var t;Gt.set(n,((t=Gt.get(n))!==null&&t!==void 0?t:0)+1);try{return e()}finally{var r;const i=((r=Gt.get(n))!==null&&r!==void 0?r:1)-1;i>0?Gt.set(n,i):Gt.delete(n)}}var mm=class{constructor(){this.callbacks={}}on(n,e){return this.callbacks[n]||(this.callbacks[n]=[]),this.callbacks[n].push(e),this}emit(n,...e){const t=this.callbacks[n];return t&&t.forEach(r=>r.apply(this,e)),this}off(n,e){const t=this.callbacks[n];return t&&(e?this.callbacks[n]=t.filter(r=>r!==e):delete this.callbacks[n]),this}once(n,e){const t=(...r)=>{this.off(n,t),e.apply(this,r)};return this.on(n,t)}removeAllListeners(){this.callbacks={}}};function gm(n){return n.kind==="widget"}function Ac(n,e){const t=[],r=new Set;for(const i of n)i.kind==="widget"&&gm(i)&&r.add(i.key),t.push(i.toPMDecoration(e));return{decorations:t,widgetKeys:r}}function ym(n,e,t){const{decorations:r,widgetKeys:i}=Ac(e,t);return{set:D.create(n,r),widgetKeys:i}}function Oc({position:n,from:e,to:t,docSize:r}){return nOc({position:o.anchor,from:e,to:t,docSize:r})?!0:(o.anchor===t||s.has(i)||(s.add(i),console.warn(`[tiptap warn]: Extension "${i}" returned a decoration outside the requested range [${e}, ${t}). It was ignored.`)),!1))}function km(n){var e;const t=(e=n.spec)===null||e===void 0?void 0:e.key;return typeof t=="string"?t:void 0}function Nc(n){return n.jsonID==="attr"}function Sm(n){let e=!1;if(n.getMap().forEach(()=>{e=!0}),e||Nc(n))return!0;const t=n;return typeof t.from=="number"&&typeof t.to=="number"}function xm(n,e){let t=null,r=0,i=0;for(let s=0;se.to);s+=1){const o=i+n.child(s).nodeSize;o>=e.from&&(t===null&&(t=i),r=o),i=o}return t===null?null:{from:t,to:r}}function wm(n,e){if(n.steps.some(s=>!Sm(s)))return{type:"full"};const t=Gr(n).map(({newRange:s})=>s);n.steps.forEach((s,o)=>{if(!Nc(s))return;const l=n.mapping.slice(o);t.push({from:l.map(s.pos,-1),to:l.map(s.pos+1)})});const r=[];for(const s of t){const o=xm(e,s);o&&r.push(o)}r.sort((s,o)=>s.from-o.from);const i=[];for(const s of r){const o=i[i.length-1];o&&s.from<=o.to?o.to=Math.max(o.to,s.to):i.push({...s})}return{type:"ranges",ranges:i}}function Dc(n,e,t,r){return n.map(e,t,{onRemove:i=>{const s=i?.key;typeof s=="string"&&r.delete(s)}})}function Cm(n,e,t){var r,i;const s=(r=e.decorationSetsByExtension[n])!==null&&r!==void 0?r:D.empty,o=new Set((i=e.widgetKeysByExtension[n])!==null&&i!==void 0?i:[]);return{set:Dc(s,t.mapping,t.doc,o),widgetKeys:o}}function el(n,e){const t=Object.values(e).flatMap(r=>r.find());return D.create(n,t)}function tl(n){const e=new Set;for(const t of Object.values(n))for(const r of t)e.add(r);return e}function Mm(n,e){var t;switch((t=e.update)!==null&&t!==void 0?t:"document"){case"document":if(e.createInRange)throw new Error(`[tiptap error]: Extension "${n}" provides createInRange() but does not use the "changedRanges" decoration update strategy.`);return;case"changedRanges":if(!e.createInRange)throw new Error(`[tiptap error]: Extension "${n}" uses the "changedRanges" decoration update strategy but does not provide createInRange().`);return;case"manual":if(e.createInRange)throw new Error(`[tiptap error]: Extension "${n}" uses the "manual" decoration update strategy, which is not compatible with createInRange(). createInRange() requires the "changedRanges" strategy.`);if(e.shouldUpdate)throw new Error(`[tiptap error]: Extension "${n}" cannot combine the "manual" decoration update strategy with shouldUpdate().`);return;default:throw new Error(`[tiptap error]: Extension "${n}" uses an unknown decoration update strategy. Expected "document", "changedRanges", or "manual".`)}}function vm(n,e,t){return t?!0:n.update==="manual"?!1:n.shouldUpdate?n.shouldUpdate(e):e.tr.docChanged}const Em=new Set;var Tm=class{constructor(n){this.warnedWidgetKeys=new Set,this.warnedOutOfRangeExtensions=new Set,this.handleBeforeTransaction=({nextState:e})=>{const t=Lt.getState(e);t&&this.warnDuplicateWidgetKeys(t)},this.editor=n.editor,this.entries=this.resolveEntries(n.entries),this.entries.forEach(({name:e,spec:t})=>Mm(e,t)),this.plugin=this.entries.length>0?this.createPlugin():null,this.editor.on("beforeTransaction",this.handleBeforeTransaction)}destroy(){this.editor.off("beforeTransaction",this.handleBeforeTransaction)}liveWidgetKeys(){var n,e;return(n=(e=Lt.getState(this.editor.state))===null||e===void 0?void 0:e.widgetKeys)!==null&&n!==void 0?n:Em}get mountedView(){return this.editor.isDestroyed?null:this.editor.view}resolveEntries(n){const e=[];for(const{name:t,addDecorations:r}of n){const i=r();i&&e.push({name:t,spec:i})}return e}createPlugin(){const{editor:n,entries:e}=this;return new $({key:Lt,state:{init:(t,r)=>{const i={},s={};for(const{name:l,spec:a}of e){const{set:c,widgetKeys:u}=this.buildFullSet(l,a,r);i[l]=c,s[l]=u}const o={decorationSetsByExtension:i,widgetKeysByExtension:s,mergedDecorationSet:this.buildMergedSet(r.doc,i),widgetKeys:tl(s)};return this.warnDuplicateWidgetKeys(o),o},apply:(t,r,i,s)=>{const o=t.getMeta(Lt),l=o?.type==="force"&&!o.name,a=o?.type==="force"?o.name:void 0,c={},u={},d=new Set;return pm(n,()=>{for(const{name:f,spec:h}of e){const p=l||a===f;if(vm(h,{editor:n,tr:t,oldState:i,newState:s},p))if(h.update==="changedRanges"&&t.docChanged&&!p){const m=this.applyChangedRangesRecompute(f,h,r,t,s);c[f]=m.set,u[f]=m.widgetKeys,d.add(f)}else{const{set:m,widgetKeys:g}=this.buildFullSet(f,h,s);c[f]=m,u[f]=g,d.add(f)}else{const m=Cm(f,r,t);c[f]=m.set,u[f]=m.widgetKeys}}}),d.size===0&&!t.docChanged?r:{decorationSetsByExtension:c,widgetKeysByExtension:u,mergedDecorationSet:this.mergeAfterApply({entries:e,previous:r,tr:t,decorationSetsByExtension:c,recomputedNames:d}),widgetKeys:tl(u)}}},props:{decorations(t){var r,i;return(r=(i=Lt.getState(t))===null||i===void 0?void 0:i.mergedDecorationSet)!==null&&r!==void 0?r:D.empty}}})}applyChangedRangesRecompute(n,e,t,r,i){const s=wm(r,i.doc);return s.type==="full"?this.buildFullSet(n,e,i):this.rebuildRanges(n,e,t,r,i,s.ranges)}rebuildRanges(n,e,t,r,i,s){var o,l;const a=(o=t.decorationSetsByExtension[n])!==null&&o!==void 0?o:D.empty,c=new Set((l=t.widgetKeysByExtension[n])!==null&&l!==void 0?l:[]);let u=Dc(a,r.mapping,r.doc,c);const d=i.doc.content.size;for(const{from:f,to:h}of s){const p=u.find(f,h).filter(y=>Oc({position:y.from,from:f,to:h,docSize:d}));for(const y of p){const S=km(y);S&&c.delete(S)}u=u.remove(p);const{decorations:m,widgetKeys:g}=Ac(bm({decorations:this.runCreate(n,"createInRange",()=>e.createInRange({editor:this.editor,state:i,view:this.mountedView,from:f,to:h})),from:f,to:h,docSize:d,extensionName:n,warnedExtensions:this.warnedOutOfRangeExtensions}),n);u=u.add(i.doc,m);for(const y of g)c.add(y)}return{set:u,widgetKeys:c}}buildFullSet(n,e,t){const r=this.runCreate(n,"create",()=>e.create({editor:this.editor,state:t,view:this.mountedView}));return ym(t.doc,r,n)}runCreate(n,e,t){try{return t()}catch(r){return console.error(`[tiptap error]: Extension "${n}" threw in \`addDecorations().${e}()\`. Its decorations were dropped for this update.`,r),[]}}warnDuplicateWidgetKeys(n){}buildMergedSet(n,e){const t=Object.keys(e);return t.length===1?e[t[0]]:el(n,e)}mergeAfterApply({entries:n,previous:e,tr:t,decorationSetsByExtension:r,recomputedNames:i}){return n.length===1?r[n[0].name]:i.size===0?e.mergedDecorationSet.map(t.mapping,t.doc):el(t.doc,r)}};function Am(n,e){const{selection:t}=n,{$from:r}=t;if(t instanceof E){const s=r.index();return r.parent.canReplaceWith(s,s+1,e)}let i=r.depth;for(;i>=0;){const s=r.index(i);if(r.node(i).contentMatchAt(s).matchType(e))return!0;i-=1}return!1}function Om(n,e,t){const r=document.querySelector("style[data-tiptap-style]");if(r!==null)return r;const i=document.createElement("style");return e&&i.setAttribute("nonce",e),i.setAttribute("data-tiptap-style",""),i.innerHTML=n,document.getElementsByTagName("head")[0].appendChild(i),i}function Nm(n){return typeof n=="number"}function Dm(n){return Object.prototype.toString.call(n).slice(8,-1)}function $n(n){return Dm(n)!=="Object"?!1:n.constructor===Object&&Object.getPrototypeOf(n)===Object.prototype}function nl(n,e,t){const r=n.split(` +`,textSerializers:o={}}=t||{};let l="";return n.nodesBetween(r,i,(a,c,u,d)=>{a.isBlock&&c>r&&(l+=s);const f=o?.[a.type.name];if(f)return u&&(l+=f({node:a,pos:c,parent:u,index:d,range:e})),!1;if(a.isText){var h;l+=a==null||(h=a.text)===null||h===void 0?void 0:h.slice(Math.max(r,c)-c,i-c)}}),l}function dg(n,e){return Tu(n,{from:0,to:n.content.size},e)}function Eu(n){return Object.fromEntries(Object.entries(n.nodes).filter(([,e])=>e.spec.toText).map(([e,t])=>[e,t.spec.toText]))}function fg(n,e){const t=X(e,n.schema),{from:r,to:i}=n.selection,s=[];n.doc.nodesBetween(r,i,l=>{s.push(l)});const o=s.reverse().find(l=>l.type.name===t.name);return o?{...o.attrs}:{}}function Au(n,e){const t=yi(typeof e=="string"?e:e.name,n.schema);return t==="node"?fg(n,e):t==="mark"?Cu(n,e):{}}function hg(n,e=JSON.stringify){const t={};return n.filter(r=>{const i=e(r);return Object.prototype.hasOwnProperty.call(t,i)?!1:t[i]=!0})}function pg(n){const e=hg(n);return e.length===1?e:e.filter((t,r)=>!e.filter((i,s)=>s!==r).some(i=>t.oldRange.from>=i.oldRange.from&&t.oldRange.to<=i.oldRange.to&&t.newRange.from>=i.newRange.from&&t.newRange.to<=i.newRange.to))}function ki(n){const{mapping:e,steps:t}=n,r=[];return e.maps.forEach((i,s)=>{const o=[];if(i.ranges.length)i.forEach((l,a)=>{o.push({from:l,to:a})});else{const{from:l,to:a}=t[s];if(l===void 0||a===void 0)return;o.push({from:l,to:a})}o.forEach(({from:l,to:a})=>{const c=e.slice(s).map(l,-1),u=e.slice(s).map(a),d=e.invert().map(c,-1),f=e.invert().map(u);r.push({oldRange:{from:d,to:f},newRange:{from:c,to:u}})})}),pg(r)}function wi(n,e,t){const r=[];return n===e?t.resolve(n).marks().forEach(i=>{const s=co(t.resolve(n),i.type);s&&r.push({mark:i,...s})}):t.nodesBetween(n,e,(i,s)=>{!i||i?.nodeSize===void 0||r.push(...i.marks.map(o=>({from:s,to:s+i.nodeSize,mark:o})))}),r}const mg=(n,e,t,r=20)=>{const i=n.doc.resolve(t);let s=r,o=null;for(;s>0&&o===null;){const l=i.node(s);l?.type.name===e?o=l:s-=1}return[o,s]},gg=n=>{const e=n.depth-1;if(e<0)return null;const t=n.index(e);return t===0?null:n.node(e).child(t-1)};function Wt(n,e){return e.nodes[n]||e.marks[n]||null}function mr(n,e,t){return Object.fromEntries(Object.entries(t).filter(([r])=>{const i=n.find(s=>s.type===e&&s.name===r);return i?i.attribute.keepOnSplit:!1}))}const yg=(n,e=500)=>{let t="";const r=n.parentOffset;return n.parent.nodesBetween(Math.max(0,r-e),r,(i,s,o,l)=>{var a,c;const u=((a=(c=i.type.spec).toText)===null||a===void 0?void 0:a.call(c,{node:i,pos:s,parent:o,index:l}))||i.textContent||"%leaf%";t+=i.isAtom&&!i.isText?u:u.slice(0,Math.max(0,r-s))}),t};function xs(n,e,t={}){const{empty:r,ranges:i}=n.selection,s=e?Ye(e,n.schema):null;if(r)return!!(n.storedMarks||n.selection.$from.marks()).filter(u=>s?s.name===u.type.name:!0).find(u=>Nr(u.attrs,t,{strict:!1}));let o=0;const l=[];if(i.forEach(({$from:u,$to:d})=>{const f=u.pos,h=d.pos;n.doc.nodesBetween(f,h,(p,m)=>{if(s&&p.inlineContent&&!p.type.allowsMarkType(s))return!1;if(!p.isText&&!p.marks.length)return;const g=Math.max(f,m),y=Math.min(h,m+p.nodeSize),k=y-g;o+=k,l.push(...p.marks.map(w=>({mark:w,from:g,to:y})))})}),o===0)return!1;const a=l.filter(u=>s?s.name===u.mark.type.name:!0).filter(u=>Nr(u.mark.attrs,t,{strict:!1})).reduce((u,d)=>u+d.to-d.from,0),c=l.filter(u=>s?u.mark.type!==s&&u.mark.type.excludes(s):!0).reduce((u,d)=>u+d.to-d.from,0);return(a>0?a+c:a)>=o}function bg(n,e,t={}){if(!e)return Ge(n,null,t)||xs(n,null,t);const r=yi(e,n.schema);return r==="node"?Ge(n,e,t):r==="mark"?xs(n,e,t):!1}const kg=(n,e)=>{const{$from:t,$to:r,$anchor:i}=n.selection;if(e){const s=bi(l=>l.type.name===e)(n.selection);if(!s)return!1;const o=n.doc.resolve(s.pos+1);return i.pos+1===o.end()}return!(r.parentOffset{const{$from:e,$to:t}=n.selection;return!(e.parentOffset>0||e.pos!==t.pos)};function Bl(n,e){return Array.isArray(e)?e.some(t=>(typeof t=="string"?t:t.name)===n.name):e}function Vi(n,e){const{nodeExtensions:t}=nn(e),r=t.find(s=>s.name===n);if(!r)return!1;const i=L(M(r,"group",{name:r.name,options:r.options,storage:r.storage}));return typeof i!="string"?!1:i.split(" ").includes("list")}function Jn(n,{checkChildren:e=!0,ignoreWhitespace:t=!1}={}){if(t){if(n.type.name==="hardBreak")return!0;if(n.isText){var r;return!/\S/.test((r=n.text)!==null&&r!==void 0?r:"")}}if(n.isText)return!n.text;if(n.isAtom||n.isLeaf)return!1;if(n.content.childCount===0)return!0;if(e){let i=!0;return n.content.forEach(s=>{i!==!1&&(Jn(s,{ignoreWhitespace:t,checkChildren:e})||(i=!1))}),i}return!1}function Nu(n){return n instanceof T}var Ou=class Ru{constructor(e){this.position=e}static fromJSON(e){return new Ru(e.position)}toJSON(){return{position:this.position}}};function Sg(n,e){const t=e.mapping.mapResult(n.position);return{position:new Ou(t.pos),mapResult:t}}function Cg(n){return new Ou(n)}function xg(n,e,t){const{selection:r}=e;let i=null;if(pu(r)&&(i=r.$cursor),i){var s;const l=(s=n.storedMarks)!==null&&s!==void 0?s:i.marks();return i.parent.type.allowsMarkType(t)&&(!!t.isInSet(l)||!l.some(a=>a.type.excludes(t)))}const{ranges:o}=r;return o.some(({$from:l,$to:a})=>{let c=l.depth===0?n.doc.inlineContent&&n.doc.type.allowsMarkType(t):!1;return n.doc.nodesBetween(l.pos,a.pos,(u,d,f)=>{if(c)return!1;if(u.isInline){const h=!f||f.type.allowsMarkType(t),p=!!t.isInSet(u.marks)||!u.marks.some(m=>m.type.excludes(t));c=h&&p}return!c}),c})}const vg=(n,e={})=>({tr:t,state:r,dispatch:i})=>{const{selection:s}=t,{empty:o,ranges:l}=s,a=Ye(n,r.schema);if(i)if(o){const c=Cu(r,a);t.addStoredMark(a.create({...c,...e}))}else l.forEach(c=>{const u=c.$from.pos,d=c.$to.pos;r.doc.nodesBetween(u,d,(f,h)=>{const p=Math.max(h,u),m=Math.min(h+f.nodeSize,d);f.marks.find(g=>g.type===a)?f.marks.forEach(g=>{a===g.type&&t.addMark(p,m,a.create({...g.attrs,...e}))}):t.addMark(p,m,a.create(e))})});return xg(r,t,a)},Mg=(n,e)=>({tr:t})=>(t.setMeta(n,e),!0),Tg=(n,e={})=>({state:t,dispatch:r,chain:i})=>{const s=X(n,t.schema);let o;return t.selection.$anchor.sameParent(t.selection.$head)&&(o=t.selection.$anchor.parent.attrs),s.isTextblock?i().command(({commands:l})=>Yo(s,{...o,...e})(t)?!0:l.clearNodes()).command(({state:l})=>Yo(s,{...o,...e})(l,r)).run():(console.warn('[tiptap warn]: Currently "setNode()" only supports text block nodes.'),!1)},Eg=n=>({tr:e,dispatch:t})=>{if(t){const{doc:r}=e,i=Ct(n,0,r.content.size),s=T.create(r,i);e.setSelection(s)}return!0},Ag=(n,e)=>({tr:t,state:r,dispatch:i})=>{const{selection:s}=r;let o,l;return typeof e=="number"?(o=e,l=e):e&&"from"in e&&"to"in e?(o=e.from,l=e.to):(o=s.from,l=s.to),i&&t.doc.nodesBetween(o,l,(a,c)=>{a.isText||t.setNodeMarkup(c,void 0,{...a.attrs,dir:n})}),!0},Ng=n=>({tr:e,dispatch:t})=>{if(t){const{doc:r}=e,{from:i,to:s}=typeof n=="number"?{from:n,to:n}:n,o=v.atStart(r).from,l=v.atEnd(r).to,a=Ct(i,o,l),c=Ct(s,o,l),u=v.create(r,a,c);e.setSelection(u)}return!0},Og=n=>({state:e,dispatch:t})=>{const r=X(n,e.schema);return fh(r)(e,t)};function $l(n,e){const t=n.storedMarks||n.selection.$to.parentOffset&&n.selection.$from.marks();if(t){const r=t.filter(i=>e?.includes(i.type.name));n.tr.ensureMarks(r)}}const Rg=({keepMarks:n=!0}={})=>({tr:e,state:t,dispatch:r,editor:i})=>{const{selection:s,doc:o}=e,{$from:l,$to:a}=s,c=i.extensionManager.attributes,u=mr(c,l.node().type.name,l.node().attrs);if(s instanceof T&&s.node.isBlock)return!l.parentOffset||!qe(o,l.pos)?!1:(r&&(n&&$l(t,i.extensionManager.splittableMarks),e.split(l.pos).scrollIntoView()),!0);if(!l.parent.isBlock)return!1;const d=a.parentOffset===a.parent.content.size,f=l.depth===0?void 0:ku(l.node(-1).contentMatchAt(l.indexAfter(-1)));let h=d&&f?[{type:f,attrs:u}]:void 0;const p=s instanceof v&&!s.empty?je.create({doc:e.doc,selection:s}).tr.deleteSelection():null,m=p?p.doc:e.doc,g=p?p.mapping.map(l.pos):l.pos;let y=qe(m,g,1,h);if(!h&&!y&&qe(m,g,1,f?[{type:f}]:void 0)&&(y=!0,h=f?[{type:f,attrs:u}]:void 0),r){if(y){const k=e.steps.length;if(s instanceof v&&e.deleteSelection(),e.split(e.mapping.slice(k).map(l.pos),1,h),f&&!d&&!l.parentOffset&&l.parent.type!==f){const w=e.mapping.slice(k).map(l.before()),C=e.doc.resolve(w);l.node(-1).canReplaceWith(C.index(),C.index()+1,f)&&e.setNodeMarkup(e.mapping.slice(k).map(l.before()),f)}}n&&$l(t,i.extensionManager.splittableMarks),e.scrollIntoView()}return y},Dg=(n,e={})=>({tr:t,state:r,dispatch:i,editor:s})=>{const o=X(n,r.schema),{$from:l,$to:a}=r.selection,c=r.selection.node;if(c&&c.isBlock||l.depth<2||!l.sameParent(a))return!1;const u=l.node(-1);if(u.type!==o)return!1;const d=s.extensionManager.attributes;if(l.parent.content.size===0&&l.node(-1).childCount===l.indexAfter(-1)){if(l.depth===2||l.node(-3).type!==o||l.index(-2)!==l.node(-2).childCount-1)return!1;if(i){var f;let C=b.empty;const O=l.index(-1)?1:l.index(-2)?2:3;for(let ke=l.depth-O;ke>=l.depth-3;ke-=1)C=b.from(l.node(ke).copy(C));const B=l.indexAfter(-1){if(te>-1)return!1;ke.isTextblock&&ke.content.size===0&&(te=yt+1)}),te>-1&&t.setSelection(v.near(t.doc.resolve(te))),t.scrollIntoView()}return!0}const h=a.pos===l.end()?u.contentMatchAt(0).defaultType:null,p={...mr(d,u.type.name,u.attrs),...e},m={...mr(d,l.node().type.name,l.node().attrs),...e},g=l.parentOffset===0&&l.index(-1)===0,y=l.before(-1);t.delete(l.pos,a.pos);const k=g?u.attrs:p,w=h?[{type:o,attrs:k},{type:h,attrs:m}]:[{type:o,attrs:k}];if(!qe(t.doc,l.pos,2))return!1;if(i){const{selection:C,storedMarks:O}=r,{splittableMarks:B}=s.extensionManager,E=O||C.$to.parentOffset&&C.$from.marks();if(t.split(l.pos,2,w).scrollIntoView(),g&&t.setNodeMarkup(y,void 0,p),!E||!i)return!0;const D=E.filter(P=>B.includes(P.type.name));t.ensureMarks(D)}return!0};function Hl(n){return!n||n==="1"?null:n}function Du(n,e){return Hl(n)===Hl(e)}const Wi=(n,e)=>{const t=bi(s=>s.type===e)(n.selection);if(!t)return!0;const r=n.doc.resolve(Math.max(0,t.pos-1)).before(t.depth);if(r===void 0)return!0;const i=n.doc.nodeAt(r);return!(t.node.type===i?.type&&pt(n.doc,t.pos))||!Du(t.node.attrs.type,i?.attrs.type)||n.join(t.pos),!0},ji=(n,e)=>{const t=bi(s=>s.type===e)(n.selection);if(!t)return!0;const r=n.doc.resolve(t.start).after(t.depth);if(r===void 0)return!0;const i=n.doc.nodeAt(r);return!(t.node.type===i?.type&&pt(n.doc,r))||!Du(t.node.attrs.type,i?.attrs.type)||n.join(r),!0};function Ig(n){const e=n.doc,t=e.firstChild;if(!t)return null;const r=e.resolve(1),i=e.resolve(t.nodeSize-1);return v.between(r,i)}const Lg=(n,e,t,r={})=>({editor:i,tr:s,state:o,dispatch:l,chain:a,commands:c,can:u})=>{const{extensions:d,splittableMarks:f}=i.extensionManager,h=X(n,o.schema),p=X(e,o.schema),{selection:m,storedMarks:g}=o,{$from:y,$to:k}=m,w=y.blockRange(k),C=g||m.$to.parentOffset&&m.$from.marks();if(!w)return!1;const O=bi(ve=>Vi(ve.type.name,d))(m),B=m.from===0&&m.to===o.doc.content.size,E=o.doc.content.content,D=E.length===1?E[0]:null,P=B&&D&&Vi(D.type.name,d)?{node:D,pos:0}:null,te=O??P,ke=!!O&&w.depth>=1&&w.depth-O.depth<=1,yt=!!P;if((ke||yt)&&te){if(te.node.type===h)return B&&yt?a().command(({tr:ve,dispatch:Pe})=>{const Me=Ig(ve);return Me?(ve.setSelection(Me),Pe&&Pe(ve),!0):!1}).liftListItem(p).run():c.liftListItem(p);if(Vi(te.node.type.name,d)&&h.validContent(te.node.content))return a().command(()=>(s.setNodeMarkup(te.pos,h),!0)).command(()=>Wi(s,h)).command(()=>ji(s,h)).run()}return!t||!C||!l?a().command(()=>u().wrapInList(h,r)?!0:c.clearNodes()).wrapInList(h,r).command(()=>Wi(s,h)).command(()=>ji(s,h)).run():a().command(()=>{const ve=u().wrapInList(h,r),Pe=C.filter(Me=>f.includes(Me.type.name));return s.ensureMarks(Pe),ve?!0:c.clearNodes()}).wrapInList(h,r).command(()=>Wi(s,h)).command(()=>ji(s,h)).run()},Pg=(n,e={},t={})=>({state:r,commands:i})=>{const{extendEmptyMarkRange:s=!1}=t,o=Ye(n,r.schema);return xs(r,o,e)?i.unsetMark(o,{extendEmptyMarkRange:s}):i.setMark(o,e)},zg=(n,e,t={})=>({state:r,commands:i})=>{const s=X(n,r.schema),o=X(e,r.schema),l=Ge(r,s,t);let a;return r.selection.$anchor.sameParent(r.selection.$head)&&(a=r.selection.$anchor.parent.attrs),l?i.setNode(o,a):i.setNode(s,{...a,...t})},Bg=(n,e={})=>({state:t,commands:r})=>{const i=X(n,t.schema);return Ge(t,i,e)?r.lift(i):r.wrapIn(i,e)},$g=()=>({state:n,dispatch:e})=>{const t=n.plugins;for(let r=0;r=0;a-=1)o.step(l.steps[a].invert(l.docs[a]));if(s.text){const a=o.doc.resolve(s.from).marks();o.replaceWith(s.from,s.to,n.schema.text(s.text,a))}else o.delete(s.from,s.to)}return!0}}return!1},Hg=(n={})=>({tr:e,dispatch:t,editor:r})=>{const{ignoreClearable:i=!1}=n,{selection:s}=e,{empty:o,ranges:l}=s;if(o)return!0;const{nonClearableMarks:a}=r.extensionManager;if(t){const c=Object.values(r.schema.marks).filter(u=>i||!a.includes(u.name));l.forEach(u=>{for(const d of c)e.removeMark(u.$from.pos,u.$to.pos,d)})}return!0},Fg=(n,e={})=>({tr:t,state:r,dispatch:i})=>{const{extendEmptyMarkRange:s=!1}=e,{selection:o}=t,l=Ye(n,r.schema),{$from:a,empty:c,ranges:u}=o;if(!i)return!0;if(c&&s){var d;let{from:f,to:h}=o;const p=co(a,l,(d=a.marks().find(m=>m.type===l))===null||d===void 0?void 0:d.attrs);p&&(f=p.from,h=p.to),t.removeMark(f,h,l)}else u.forEach(f=>{t.removeMark(f.$from.pos,f.$to.pos,l)});return t.removeStoredMark(l),!0},Vg=n=>({tr:e,state:t,dispatch:r})=>{const{selection:i}=t;let s,o;return typeof n=="number"?(s=n,o=n):n&&"from"in n&&"to"in n?(s=n.from,o=n.to):(s=i.from,o=i.to),r&&e.doc.nodesBetween(s,o,(l,a)=>{if(l.isText)return;const c={...l.attrs};delete c.dir,e.setNodeMarkup(a,void 0,c)}),!0},Wg=(n,e={})=>({tr:t,state:r,dispatch:i})=>{let s=null,o=null;const l=yi(typeof n=="string"?n:n.name,r.schema);if(!l)return!1;l==="node"&&(s=X(n,r.schema)),l==="mark"&&(o=Ye(n,r.schema));let a=!1;return t.selection.ranges.forEach(c=>{const u=c.$from.pos,d=c.$to.pos;let f,h,p,m;t.selection.empty?r.doc.nodesBetween(u,d,(g,y)=>{s&&s===g.type&&(a=!0,p=Math.max(y,u),m=Math.min(y+g.nodeSize,d),f=y,h=g)}):r.doc.nodesBetween(u,d,(g,y)=>{y=u&&y<=d&&(s&&s===g.type&&(a=!0,i&&t.setNodeMarkup(y,void 0,{...g.attrs,...e})),o&&g.marks.length&&g.marks.forEach(k=>{if(o===k.type&&(a=!0,i)){const w=Math.max(y,u),C=Math.min(y+g.nodeSize,d);t.addMark(w,C,o.create({...k.attrs,...e}))}}))}),h&&(f!==void 0&&i&&t.setNodeMarkup(f,void 0,{...h.attrs,...e}),o&&h.marks.length&&h.marks.forEach(g=>{o===g.type&&i&&t.addMark(p,m,o.create({...g.attrs,...e}))}))}),a},Kt=new W("__tiptap_decorations__"),jg=n=>({tr:e,dispatch:t})=>(t&&e.setMeta(Kt,{type:"force",name:n}),!0),_g=(n,e={})=>({state:t,dispatch:r})=>{const i=X(n,t.schema);return sh(i,e)(t,r)},Ug=(n,e={})=>({state:t,dispatch:r})=>{const i=X(n,t.schema);return oh(i,e)(t,r)};var Kg=Xd({blur:()=>pm,clearContent:()=>mm,clearNodes:()=>gm,command:()=>ym,createParagraphNear:()=>bm,cut:()=>km,deleteCurrentNode:()=>wm,deleteNode:()=>Sm,deleteRange:()=>Cm,deleteSelection:()=>Mm,enter:()=>Tm,exitCode:()=>Em,extendMarkRange:()=>Am,first:()=>Nm,focus:()=>Rm,forEach:()=>Dm,insertContent:()=>Im,insertContentAt:()=>Lm,insertDefaultBlock:()=>Pm,joinBackward:()=>$m,joinDown:()=>Bm,joinForward:()=>Hm,joinItemBackward:()=>Fm,joinItemForward:()=>Vm,joinTextblockBackward:()=>Wm,joinTextblockForward:()=>jm,joinUp:()=>zm,keyboardShortcut:()=>Um,lift:()=>Km,liftEmptyBlock:()=>qm,liftListItem:()=>Jm,newlineInCode:()=>Gm,resetAttributes:()=>Ym,scrollIntoView:()=>Xm,selectAll:()=>Qm,selectNodeBackward:()=>Zm,selectNodeForward:()=>eg,selectParentNode:()=>tg,selectTextblockEnd:()=>ng,selectTextblockStart:()=>rg,setContent:()=>ig,setMark:()=>vg,setMeta:()=>Mg,setNode:()=>Tg,setNodeSelection:()=>Eg,setTextDirection:()=>Ag,setTextSelection:()=>Ng,sinkListItem:()=>Og,splitBlock:()=>Rg,splitListItem:()=>Dg,toggleList:()=>Lg,toggleMark:()=>Pg,toggleNode:()=>zg,toggleWrap:()=>Bg,undoInputRule:()=>$g,unsetAllMarks:()=>Hg,unsetMark:()=>Fg,unsetTextDirection:()=>Vg,updateAttributes:()=>Wg,updateDecorations:()=>jg,wrapIn:()=>_g,wrapInList:()=>Ug});const cn=new WeakMap;function qg(n,e){var t;cn.set(n,((t=cn.get(n))!==null&&t!==void 0?t:0)+1);try{return e()}finally{var r;const i=((r=cn.get(n))!==null&&r!==void 0?r:1)-1;i>0?cn.set(n,i):cn.delete(n)}}var Jg=class{constructor(){this.callbacks={}}on(n,e){return this.callbacks[n]||(this.callbacks[n]=[]),this.callbacks[n].push(e),this}emit(n,...e){const t=this.callbacks[n];return t&&t.forEach(r=>r.apply(this,e)),this}off(n,e){const t=this.callbacks[n];return t&&(e?this.callbacks[n]=t.filter(r=>r!==e):delete this.callbacks[n]),this}once(n,e){const t=(...r)=>{this.off(n,t),e.apply(this,r)};return this.on(n,t)}removeAllListeners(){this.callbacks={}}};function Gg(n){return n.kind==="widget"}function Iu(n,e){const t=[],r=new Set;for(const i of n)i.kind==="widget"&&Gg(i)&&r.add(i.key),t.push(i.toPMDecoration(e));return{decorations:t,widgetKeys:r}}function Yg(n,e,t){const{decorations:r,widgetKeys:i}=Iu(e,t);return{set:I.create(n,r),widgetKeys:i}}function Lu({position:n,from:e,to:t,docSize:r}){return nLu({position:o.anchor,from:e,to:t,docSize:r})?!0:(o.anchor===t||s.has(i)||(s.add(i),console.warn(`[tiptap warn]: Extension "${i}" returned a decoration outside the requested range [${e}, ${t}). It was ignored.`)),!1))}function Qg(n){var e;const t=(e=n.spec)===null||e===void 0?void 0:e.key;return typeof t=="string"?t:void 0}function Pu(n){return n.jsonID==="attr"}function Zg(n){let e=!1;if(n.getMap().forEach(()=>{e=!0}),e||Pu(n))return!0;const t=n;return typeof t.from=="number"&&typeof t.to=="number"}function ey(n,e){let t=null,r=0,i=0;for(let s=0;se.to);s+=1){const o=i+n.child(s).nodeSize;o>=e.from&&(t===null&&(t=i),r=o),i=o}return t===null?null:{from:t,to:r}}function ty(n,e){if(n.steps.some(s=>!Zg(s)))return{type:"full"};const t=ki(n).map(({newRange:s})=>s);n.steps.forEach((s,o)=>{if(!Pu(s))return;const l=n.mapping.slice(o);t.push({from:l.map(s.pos,-1),to:l.map(s.pos+1)})});const r=[];for(const s of t){const o=ey(e,s);o&&r.push(o)}r.sort((s,o)=>s.from-o.from);const i=[];for(const s of r){const o=i[i.length-1];o&&s.from<=o.to?o.to=Math.max(o.to,s.to):i.push({...s})}return{type:"ranges",ranges:i}}function zu(n,e,t,r){return n.map(e,t,{onRemove:i=>{const s=i?.key;typeof s=="string"&&r.delete(s)}})}function ny(n,e,t){var r,i;const s=(r=e.decorationSetsByExtension[n])!==null&&r!==void 0?r:I.empty,o=new Set((i=e.widgetKeysByExtension[n])!==null&&i!==void 0?i:[]);return{set:zu(s,t.mapping,t.doc,o),widgetKeys:o}}function Fl(n,e){const t=Object.values(e).flatMap(r=>r.find());return I.create(n,t)}function Vl(n){const e=new Set;for(const t of Object.values(n))for(const r of t)e.add(r);return e}function ry(n,e){var t;switch((t=e.update)!==null&&t!==void 0?t:"document"){case"document":if(e.createInRange)throw new Error(`[tiptap error]: Extension "${n}" provides createInRange() but does not use the "changedRanges" decoration update strategy.`);return;case"changedRanges":if(!e.createInRange)throw new Error(`[tiptap error]: Extension "${n}" uses the "changedRanges" decoration update strategy but does not provide createInRange().`);return;case"manual":if(e.createInRange)throw new Error(`[tiptap error]: Extension "${n}" uses the "manual" decoration update strategy, which is not compatible with createInRange(). createInRange() requires the "changedRanges" strategy.`);if(e.shouldUpdate)throw new Error(`[tiptap error]: Extension "${n}" cannot combine the "manual" decoration update strategy with shouldUpdate().`);return;default:throw new Error(`[tiptap error]: Extension "${n}" uses an unknown decoration update strategy. Expected "document", "changedRanges", or "manual".`)}}function iy(n,e,t){return t?!0:n.update==="manual"?!1:n.shouldUpdate?n.shouldUpdate(e):e.tr.docChanged}const sy=new Set;var oy=class{constructor(n){this.warnedWidgetKeys=new Set,this.warnedOutOfRangeExtensions=new Set,this.handleBeforeTransaction=({nextState:e})=>{const t=Kt.getState(e);t&&this.warnDuplicateWidgetKeys(t)},this.editor=n.editor,this.entries=this.resolveEntries(n.entries),this.entries.forEach(({name:e,spec:t})=>ry(e,t)),this.plugin=this.entries.length>0?this.createPlugin():null,this.editor.on("beforeTransaction",this.handleBeforeTransaction)}destroy(){this.editor.off("beforeTransaction",this.handleBeforeTransaction)}liveWidgetKeys(){var n,e;return(n=(e=Kt.getState(this.editor.state))===null||e===void 0?void 0:e.widgetKeys)!==null&&n!==void 0?n:sy}get mountedView(){return this.editor.isDestroyed?null:this.editor.view}resolveEntries(n){const e=[];for(const{name:t,addDecorations:r}of n){const i=r();i&&e.push({name:t,spec:i})}return e}createPlugin(){const{editor:n,entries:e}=this;return new z({key:Kt,state:{init:(t,r)=>{const i={},s={};for(const{name:l,spec:a}of e){const{set:c,widgetKeys:u}=this.buildFullSet(l,a,r);i[l]=c,s[l]=u}const o={decorationSetsByExtension:i,widgetKeysByExtension:s,mergedDecorationSet:this.buildMergedSet(r.doc,i),widgetKeys:Vl(s)};return this.warnDuplicateWidgetKeys(o),o},apply:(t,r,i,s)=>{const o=t.getMeta(Kt),l=o?.type==="force"&&!o.name,a=o?.type==="force"?o.name:void 0,c={},u={},d=new Set;return qg(n,()=>{for(const{name:f,spec:h}of e){const p=l||a===f;if(iy(h,{editor:n,tr:t,oldState:i,newState:s},p))if(h.update==="changedRanges"&&t.docChanged&&!p){const m=this.applyChangedRangesRecompute(f,h,r,t,s);c[f]=m.set,u[f]=m.widgetKeys,d.add(f)}else{const{set:m,widgetKeys:g}=this.buildFullSet(f,h,s);c[f]=m,u[f]=g,d.add(f)}else{const m=ny(f,r,t);c[f]=m.set,u[f]=m.widgetKeys}}}),d.size===0&&!t.docChanged?r:{decorationSetsByExtension:c,widgetKeysByExtension:u,mergedDecorationSet:this.mergeAfterApply({entries:e,previous:r,tr:t,decorationSetsByExtension:c,recomputedNames:d}),widgetKeys:Vl(u)}}},props:{decorations(t){var r,i;return(r=(i=Kt.getState(t))===null||i===void 0?void 0:i.mergedDecorationSet)!==null&&r!==void 0?r:I.empty}}})}applyChangedRangesRecompute(n,e,t,r,i){const s=ty(r,i.doc);return s.type==="full"?this.buildFullSet(n,e,i):this.rebuildRanges(n,e,t,r,i,s.ranges)}rebuildRanges(n,e,t,r,i,s){var o,l;const a=(o=t.decorationSetsByExtension[n])!==null&&o!==void 0?o:I.empty,c=new Set((l=t.widgetKeysByExtension[n])!==null&&l!==void 0?l:[]);let u=zu(a,r.mapping,r.doc,c);const d=i.doc.content.size;for(const{from:f,to:h}of s){const p=u.find(f,h).filter(y=>Lu({position:y.from,from:f,to:h,docSize:d}));for(const y of p){const k=Qg(y);k&&c.delete(k)}u=u.remove(p);const{decorations:m,widgetKeys:g}=Iu(Xg({decorations:this.runCreate(n,"createInRange",()=>e.createInRange({editor:this.editor,state:i,view:this.mountedView,from:f,to:h})),from:f,to:h,docSize:d,extensionName:n,warnedExtensions:this.warnedOutOfRangeExtensions}),n);u=u.add(i.doc,m);for(const y of g)c.add(y)}return{set:u,widgetKeys:c}}buildFullSet(n,e,t){const r=this.runCreate(n,"create",()=>e.create({editor:this.editor,state:t,view:this.mountedView}));return Yg(t.doc,r,n)}runCreate(n,e,t){try{return t()}catch(r){return console.error(`[tiptap error]: Extension "${n}" threw in \`addDecorations().${e}()\`. Its decorations were dropped for this update.`,r),[]}}warnDuplicateWidgetKeys(n){}buildMergedSet(n,e){const t=Object.keys(e);return t.length===1?e[t[0]]:Fl(n,e)}mergeAfterApply({entries:n,previous:e,tr:t,decorationSetsByExtension:r,recomputedNames:i}){return n.length===1?r[n[0].name]:i.size===0?e.mergedDecorationSet.map(t.mapping,t.doc):Fl(t.doc,r)}};function ly(n,e){const{selection:t}=n,{$from:r}=t;if(t instanceof T){const s=r.index();return r.parent.canReplaceWith(s,s+1,e)}let i=r.depth;for(;i>=0;){const s=r.index(i);if(r.node(i).contentMatchAt(s).matchType(e))return!0;i-=1}return!1}function ay(n,e,t){const r=document.querySelector("style[data-tiptap-style]");if(r!==null)return r;const i=document.createElement("style");return e&&i.setAttribute("nonce",e),i.setAttribute("data-tiptap-style",""),i.innerHTML=n,document.getElementsByTagName("head")[0].appendChild(i),i}function cy(n){return typeof n=="number"}function uy(n){return Object.prototype.toString.call(n).slice(8,-1)}function er(n){return uy(n)!=="Object"?!1:n.constructor===Object&&Object.getPrototypeOf(n)===Object.prototype}function dy(n){return typeof n=="string"&&n.trim().length>0&&!/[;{}]/.test(n)}function Wl(n,e,t){const r=n.split(` `),i=[];let s="",o=0;const l=e.baseIndentSize||2;for(;o0)break;if(u.trim()===""){o+=1,s=`${s}${u} `;continue}else return}const f=e.extractItemData(d),{indentLevel:h,mainContent:p}=f;s=`${s}${u} -`;const m=[p];for(o+=1;oI.trim()!=="");if(C===-1)break;if((((c=r[o+1+C].match(/^(\s*)/))===null||c===void 0||(c=c[1])===null||c===void 0?void 0:c.length)||0)>h){m.push(x),s=`${s}${x} -`,o+=1;continue}else break}if((((a=x.match(/^(\s*)/))===null||a===void 0||(a=a[1])===null||a===void 0?void 0:a.length)||0)>h)m.push(x),s=`${s}${x} -`,o+=1;else break}let g;const y=m.slice(1);if(y.length>0){const x=y.map(C=>C.slice(h+l)).join(` -`);x.trim()&&(e.customNestedParser?g=e.customNestedParser(x):g=t.blockTokens(x))}const S=e.createToken(f,g);i.push(S)}if(i.length!==0)return{items:i,raw:s}}const rl=4;function il(n){let e=0;for(const t of n)e=t===" "?e+rl-e%rl:e+1;return e}function Ic(n,e,t,r,i){if(!n||!Array.isArray(n.content))return"";const s=typeof t=="function"?t(r):t,[o,...l]=n.content;let a=`${s}${e.renderChildren([o])}`;return l&&l.length>0&&l.forEach((c,u)=>{var d,f;const h=(d=(f=e.renderChild)===null||f===void 0?void 0:f.call(e,c,u+1))!==null&&d!==void 0?d:e.renderChildren([c]);if(h!=null){const p=g=>{if(!i?.alignNestedToPrefix)return e.indent(g);const y=e.indent(""),S=il(s);return(il(y)>=S?y:" ".repeat(S))+g},m=h.split(` +`;const m=[p];for(o+=1;oO.trim()!=="");if(C===-1)break;if((((c=r[o+1+C].match(/^(\s*)/))===null||c===void 0||(c=c[1])===null||c===void 0?void 0:c.length)||0)>h){m.push(w),s=`${s}${w} +`,o+=1;continue}else break}if((((a=w.match(/^(\s*)/))===null||a===void 0||(a=a[1])===null||a===void 0?void 0:a.length)||0)>h)m.push(w),s=`${s}${w} +`,o+=1;else break}let g;const y=m.slice(1);if(y.length>0){const w=y.map(C=>C.slice(h+l)).join(` +`);w.trim()&&(e.customNestedParser?g=e.customNestedParser(w):g=t.blockTokens(w))}const k=e.createToken(f,g);i.push(k)}if(i.length!==0)return{items:i,raw:s}}const jl=4;function _l(n){let e=0;for(const t of n)e=t===" "?e+jl-e%jl:e+1;return e}function Bu(n,e,t,r,i){if(!n||!Array.isArray(n.content))return"";const s=typeof t=="function"?t(r):t,[o,...l]=n.content;let a=`${s}${e.renderChildren([o])}`;return l&&l.length>0&&l.forEach((c,u)=>{var d,f;const h=(d=(f=e.renderChild)===null||f===void 0?void 0:f.call(e,c,u+1))!==null&&d!==void 0?d:e.renderChildren([c]);if(h!=null){const p=g=>{if(!i?.alignNestedToPrefix)return e.indent(g);const y=e.indent(""),k=_l(s);return(_l(y)>=k?y:" ".repeat(k))+g},m=h.split(` `).map(g=>p(g||"")).join(` `);a+=c.type==="paragraph"?` ${m}`:` -${m}`}}),a}function Rc(n,e){const t={...n};return $n(n)&&$n(e)&&Object.keys(e).forEach(r=>{$n(e[r])&&$n(n[r])?t[r]=Rc(n[r],e[r]):t[r]=e[r]}),t}function Im(n,e,t={}){const{state:r}=e,{doc:i,tr:s}=r,o=n;i.descendants((l,a)=>{const c=s.mapping.map(a),u=s.mapping.map(a)+l.nodeSize;let d=null;if(l.marks.forEach(h=>{if(h!==o)return!1;d=h}),!d)return;let f=!1;if(Object.keys(t).forEach(h=>{t[h]!==d.attrs[h]&&(f=!0)}),f){const h=n.type.create({...n.attrs,...t});s.removeMark(c,u,n.type),s.addMark(c,u,h)}}),s.docChanged&&e.view.dispatch(s)}var In=class{constructor(n){var e;this.find=n.find,this.handler=n.handler,this.undoable=(e=n.undoable)!==null&&e!==void 0?e:!0}};const Rm=(n,e)=>{if(Cs(e))return e.exec(n);const t=e(n);if(!t)return null;const r=[t.text];return r.index=t.index,r.input=n,r.data=t.data,t.replaceWith&&(t.text.includes(t.replaceWith)||console.warn('[tiptap warn]: "inputRuleMatch.replaceWith" must be part of "inputRuleMatch.text".'),r.push(t.replaceWith)),r};function Lm(n){const{editor:e,from:t,to:r,text:i,insertText:s}=n;if(!s)return{inputTransaction:null,tr:e.view.state.tr};const o=e.view.state.tr.insertText(i,t,r);return{inputTransaction:o,tr:Be.create({doc:o.doc,selection:o.selection,storedMarks:o.storedMarks}).tr}}function Pm(n){const{editor:e,from:t,to:r,text:i,rule:s,match:o,plugin:l,insertText:a}=n,{view:c}=e,{inputTransaction:u,tr:d}=Lm({editor:e,from:t,to:r,text:i,insertText:a}),f=u?t+i.length:r,h=Ur({state:c.state,transaction:d}),p={from:t-(o[0].length-i.length),to:f},{commands:m,chain:g,can:y}=new $t({editor:e,state:h});return s.handler({state:h,range:p,match:o,commands:m,chain:g,can:y})===null||!d.steps.length?!1:(u&&(c.dispatch(u),!c.state.doc.eq(u.doc))||(Dh(d),d.setMeta("inputRule",!0),s.undoable&&d.setMeta(l,{transform:d,from:t,to:f,text:i}),c.dispatch(d)),!0)}function Bm(n,e,t){const r=e[0].length-t.length;if(r<=0)return!0;const i=n.parentOffset-r;return i>=0&&n.parent.textBetween(i,n.parentOffset)===e[0].slice(0,r)}function Fn(n){var e;const{editor:t,from:r,to:i,text:s,rules:o,plugin:l,insertText:a}=n,{view:c}=t;if(c.composing)return!1;const u=c.state.doc.resolve(r);if(u.parent.type.spec.code||!((e=u.nodeBefore||u.nodeAfter)===null||e===void 0)&&e.marks.find(f=>f.type.spec.code))return!1;const d=$p(u)+s;for(const f of o){const h=Rm(d,f.find);if(!(!h||!Bm(u,h,s))&&Pm({editor:t,from:r,to:i,text:s,rule:f,match:h,plugin:l,insertText:a}))return!0}return!1}function zm(n){const{editor:e,rules:t}=n,r=new $({state:{init(){return null},apply(i,s,o){const l=i.getMeta(r);if(l)return l;const a=i.getMeta("applyInputRules");return a&&setTimeout(()=>{let{text:c}=a;typeof c=="string"?c=c:c=Es(b.from(c),o.schema);const{from:u}=a,d=u+c.length;Fn({editor:e,from:u,to:d,text:c,rules:t,plugin:r})}),i.selectionSet||i.docChanged?null:s}},props:{handleTextInput(i,s,o,l){return Fn({editor:e,from:s,to:o,text:l,rules:t,plugin:r,insertText:!0})},handleDOMEvents:{compositionend:i=>(setTimeout(()=>{const{$cursor:s}=i.state.selection;s&&Fn({editor:e,from:s.pos,to:s.pos,text:"",rules:t,plugin:r})}),!1)},handleKeyDown(i,s){if(s.key!=="Enter")return!1;const{$cursor:o}=i.state.selection;return o?Fn({editor:e,from:o.pos,to:o.pos,text:` -`,rules:t,plugin:r}):!1}},isInputRules:!0});return r}var Ts=class{constructor(n={}){this.type="extendable",this.parent=null,this.child=null,this.name="",this.config={name:this.name},this.config={...this.config,...n},this.name=this.config.name}get options(){return{...L(M(this,"addOptions",{name:this.name}))}}get storage(){return{...L(M(this,"addStorage",{name:this.name,options:this.options}))}}configure(n={}){const e=this.extend({...this.config,addOptions:()=>Rc(this.options,n)});return e.name=this.name,e.parent=this.parent,this.child=null,e}extend(n={}){const e=new this.constructor({...this.config,...n});return e.parent=this,this.child=e,e.name="name"in n?n.name:e.parent.name,e}},Et=class Lc extends Ts{constructor(...e){super(...e),this.type="mark"}static create(e={}){const t=typeof e=="function"?e():e;return new Lc(t)}static handleExit({editor:e,mark:t}){const{tr:r}=e.state,i=e.state.selection.$from;if(i.pos===i.end()){const s=i.marks();if(!s.find(l=>l?.type.name===t.name))return!1;const o=s.find(l=>l?.type.name===t.name);return o&&r.removeStoredMark(o),r.insertText(" ",i.pos),e.view.dispatch(r),!0}return!1}configure(e){return super.configure(e)}extend(e){const t=typeof e=="function"?e():e;return super.extend(t)}},Pc=class{constructor(n){this.find=n.find,this.handler=n.handler}};const $m=(n,e,t)=>{if(Cs(e))return[...n.matchAll(e)];const r=e(n,t);return r?r.map(i=>{const s=[i.text];return s.index=i.index,s.input=n,s.data=i.data,i.replaceWith&&(i.text.includes(i.replaceWith)||console.warn('[tiptap warn]: "pasteRuleMatch.replaceWith" must be part of "pasteRuleMatch.text".'),s.push(i.replaceWith)),s}):[]};function Fm(n){const{editor:e,state:t,from:r,to:i,rule:s,pasteEvent:o,dropEvent:l}=n,{commands:a,chain:c,can:u}=new $t({editor:e,state:t}),d=[];return t.doc.nodesBetween(r,i,(f,h)=>{var p,m,g,y;if(!((p=f.type)===null||p===void 0||(p=p.spec)===null||p===void 0)&&p.code||!(f.isText||f.isTextblock||f.isInline))return;const S=(m=(g=(y=f.content)===null||y===void 0?void 0:y.size)!==null&&g!==void 0?g:f.nodeSize)!==null&&m!==void 0?m:0,x=Math.max(r,h),C=Math.min(i,h+S);if(x>=C)return;const I=f.isText?f.text||"":f.textBetween(x-h,C-h,void 0,"");$m(I,s.find,o).forEach(F=>{if(F.index===void 0)return;const A=x+F.index+1,R=A+F[0].length,P={from:t.tr.mapping.map(A),to:t.tr.mapping.map(R)},X=s.handler({state:t,range:P,match:F,commands:a,chain:c,can:u,pasteEvent:o,dropEvent:l});d.push(X)})}),d.every(f=>f!==null)}let Dt=null;const Vm=n=>{var e;const t=new ClipboardEvent("paste",{clipboardData:new DataTransfer});return(e=t.clipboardData)===null||e===void 0||e.setData("text/html",n),t};function Hm(n){const{editor:e,rules:t}=n;let r=null,i=!1,s=!1,o=typeof ClipboardEvent<"u"?new ClipboardEvent("paste"):null,l;try{l=typeof DragEvent<"u"?new DragEvent("drop"):null}catch{l=null}const a=({state:c,from:u,to:d,rule:f,pasteEvt:h})=>{const p=c.tr,m=Ur({state:c,transaction:p});if(!(!Fm({editor:e,state:m,from:Math.max(u-1,0),to:d.b-1,rule:f,pasteEvent:h,dropEvent:l})||!p.steps.length)){try{l=typeof DragEvent<"u"?new DragEvent("drop"):null}catch{l=null}return o=typeof ClipboardEvent<"u"?new ClipboardEvent("paste"):null,p}};return e.on("destroy",()=>{Dt===e&&(Dt=null)}),t.map(c=>new $({view(u){const d=h=>{var p;r=!((p=u.dom.parentElement)===null||p===void 0)&&p.contains(h.target)?u.dom.parentElement:null,r&&(Dt=e)},f=()=>{Dt&&(Dt=null)};return window.addEventListener("dragstart",d),window.addEventListener("dragend",f),{destroy(){window.removeEventListener("dragstart",d),window.removeEventListener("dragend",f)}}},props:{handleDOMEvents:{drop:(u,d)=>{if(s=r===u.dom.parentElement,l=d,!s){const f=Dt;f?.isEditable&&setTimeout(()=>{if(f.isDestroyed)return;const h=f.state.selection;h&&f.commands.deleteRange({from:h.from,to:h.to})},10)}return!1},paste:(u,d)=>{var f;const h=(f=d.clipboardData)===null||f===void 0?void 0:f.getData("text/html");return o=d,i=!!h?.includes("data-pm-slice"),!1}}},appendTransaction:(u,d,f)=>{const h=u[0],p=h.getMeta("uiEvent")==="paste"&&!i,m=h.getMeta("uiEvent")==="drop"&&!s,g=h.getMeta("applyPasteRules"),y=!!g;if(!p&&!m&&!y)return;if(y){let{text:C}=g;typeof C=="string"?C=C:C=Es(b.from(C),f.schema);const{from:I}=g,F=I+C.length,A=Vm(C);return a({rule:c,state:f,from:I,to:{b:F},pasteEvt:A})}const S=d.doc.content.findDiffStart(f.doc.content),x=d.doc.content.findDiffEnd(f.doc.content);if(!(!Nm(S)||!x||S===x.b))return a({rule:c,state:f,from:S,to:x,pasteEvt:o})}}))}var Xr=class{constructor(n,e){this.splittableMarks=[],this.nonClearableMarks=[],this.decorationManager=null,this.editor=e,this.baseExtensions=n,this.extensions=Sc(n),this.schema=Np(this.extensions,e),this.setupExtensions()}get commands(){return this.extensions.reduce((n,e)=>{const t=M(e,"addCommands",{name:e.name,options:e.options,storage:this.editor.extensionStorage[e.name],editor:this.editor,type:Nt(e.name,this.schema)});return t?{...n,...t()}:n},{})}get plugins(){const{editor:n}=this,e=ln([...this.extensions].reverse()).flatMap(r=>{const i={name:r.name,options:r.options,storage:this.editor.extensionStorage[r.name],editor:n,type:Nt(r.name,this.schema)},s=[],o=M(r,"addKeyboardShortcuts",i);let l={};if(r.type==="mark"&&M(r,"exitable",i)&&(l.ArrowRight=()=>Et.handleExit({editor:n,mark:r})),o){const f=Object.fromEntries(Object.entries(o()).map(([h,p])=>[h,()=>p({editor:n})]));l={...l,...f}}const a=Ch(l);s.push(a);const c=M(r,"addInputRules",i);if(Xo(r,n.options.enableInputRules)&&c){const f=c();if(f&&f.length){const h=zm({editor:n,rules:f}),p=Array.isArray(h)?h:[h];s.push(...p)}}const u=M(r,"addPasteRules",i);if(Xo(r,n.options.enablePasteRules)&&u){const f=u();if(f&&f.length){const h=Hm({editor:n,rules:f});s.push(...h)}}const d=M(r,"addProseMirrorPlugins",i);if(d){const f=d();s.push(...f)}return s}),t=this.createDecorationPlugin();return t&&e.push(t),e}createDecorationPlugin(){var n;const{editor:e}=this;(n=this.decorationManager)===null||n===void 0||n.destroy();const t=[];return this.extensions.forEach(r=>{const i=M(r,"addDecorations",{name:r.name,options:r.options,storage:this.editor.extensionStorage[r.name],editor:e,type:Nt(r.name,this.schema)});i&&t.push({name:r.name,addDecorations:i})}),this.decorationManager=new Tm({editor:e,entries:t}),this.decorationManager.plugin}get attributes(){return kc(this.extensions)}get nodeViews(){const{editor:n}=this,{nodeExtensions:e}=Kt(this.extensions);return Object.fromEntries(e.filter(t=>!!M(t,"addNodeView")).map(t=>{const r=this.attributes.filter(l=>l.type===t.name),i=M(t,"addNodeView",{name:t.name,options:t.options,storage:this.editor.extensionStorage[t.name],editor:n,type:q(t.name,this.schema)});if(!i)return[];const s=i();if(!s)return[];const o=(l,a,c,u,d)=>{const f=Mn(l,r);return s({node:l,view:a,getPos:c,decorations:u,innerDecorations:d,editor:n,extension:t,HTMLAttributes:f})};return[t.name,o]}))}dispatchTransaction(n){const{editor:e}=this;return ln([...this.extensions].reverse()).reduceRight((t,r)=>{const i={name:r.name,options:r.options,storage:this.editor.extensionStorage[r.name],editor:e,type:Nt(r.name,this.schema)},s=M(r,"dispatchTransaction",i);return s?o=>{s.call(i,{transaction:o,next:t})}:t},n)}transformPastedHTML(n){const{editor:e}=this;return ln([...this.extensions]).reduce((t,r)=>{const i={name:r.name,options:r.options,storage:this.editor.extensionStorage[r.name],editor:e,type:Nt(r.name,this.schema)},s=M(r,"transformPastedHTML",i);return s?(o,l)=>{const a=t(o,l);return s.call(i,a)}:t},n||(t=>t))}get markViews(){const{editor:n}=this,{markExtensions:e}=Kt(this.extensions);return Object.fromEntries(e.filter(t=>!!M(t,"addMarkView")).map(t=>{const r=this.attributes.filter(o=>o.type===t.name),i=M(t,"addMarkView",{name:t.name,options:t.options,storage:this.editor.extensionStorage[t.name],editor:n,type:je(t.name,this.schema)});if(!i)return[];const s=(o,l,a)=>{const c=Mn(o,r);return i()({mark:o,view:l,inline:a,editor:n,extension:t,HTMLAttributes:c,updateAttributes:u=>{Im(o,n,u)}})};return[t.name,s]}))}destroy(){var n;(n=this.decorationManager)===null||n===void 0||n.destroy(),this.extensions.forEach(e=>{let t=e;for(;t.parent;){const r=t.parent;r.child===t&&(r.child=null),t=r}}),this.extensions=[],this.baseExtensions=[],this.decorationManager=null,this.schema=null,this.editor=null}setupExtensions(){const n=this.extensions;this.editor.extensionStorage=Object.fromEntries(n.map(e=>[e.name,e.storage])),n.forEach(e=>{const t={name:e.name,options:e.options,storage:this.editor.extensionStorage[e.name],editor:this.editor,type:Nt(e.name,this.schema)};if(e.type==="mark"){var r,i;(!((r=L(M(e,"keepOnSplit",t)))!==null&&r!==void 0)||r)&&this.splittableMarks.push(e.name),!((i=L(M(e,"clearable",t)))!==null&&i!==void 0)||i||this.nonClearableMarks.push(e.name)}const s=M(e,"onBeforeCreate",t),o=M(e,"onCreate",t),l=M(e,"onUpdate",t),a=M(e,"onSelectionUpdate",t),c=M(e,"onTransaction",t),u=M(e,"onFocus",t),d=M(e,"onBlur",t),f=M(e,"onDestroy",t);s&&this.editor.on("beforeCreate",s),o&&this.editor.on("create",o),l&&this.editor.on("update",l),a&&this.editor.on("selectionUpdate",a),c&&this.editor.on("transaction",c),u&&this.editor.on("focus",u),d&&this.editor.on("blur",d),f&&this.editor.on("destroy",f)})}};Xr.resolve=Sc;Xr.sort=ln;Xr.flatten=vs;var W=class Bc extends Ts{constructor(...e){super(...e),this.type="extension"}static create(e={}){const t=typeof e=="function"?e():e;return new Bc(t)}configure(e){return super.configure(e)}extend(e){const t=typeof e=="function"?e():e;return super.extend(t)}};const jm=W.create({name:"clipboardTextSerializer",addOptions(){return{blockSeparator:void 0}},addProseMirrorPlugins(){return[new $({key:new _("clipboardTextSerializer"),props:{clipboardTextSerializer:()=>{const{editor:n}=this,{state:e,schema:t}=n,{doc:r,selection:i}=e,s=wc(t),{blockSeparator:o}=this.options,l={...o!==void 0?{blockSeparator:o}:{},textSerializers:s};return[...i.ranges].sort((a,c)=>a.$from.pos-c.$from.pos).map(({$from:a,$to:c})=>xc(r,{from:a.pos,to:c.pos},l)).join(o??` +${m}`}}),a}function $u(n,e){const t={...n};return er(n)&&er(e)&&Object.keys(e).forEach(r=>{er(e[r])&&er(n[r])?t[r]=$u(n[r],e[r]):t[r]=e[r]}),t}function fy(n,e,t={}){const{state:r}=e,{doc:i,tr:s}=r,o=n;i.descendants((l,a)=>{const c=s.mapping.map(a),u=s.mapping.map(a)+l.nodeSize;let d=null;if(l.marks.forEach(h=>{if(h!==o)return!1;d=h}),!d)return;let f=!1;if(Object.keys(t).forEach(h=>{t[h]!==d.attrs[h]&&(f=!0)}),f){const h=n.type.create({...n.attrs,...t});s.removeMark(c,u,n.type),s.addMark(c,u,h)}}),s.docChanged&&e.view.dispatch(s)}var Gn=class{constructor(n){var e;this.find=n.find,this.handler=n.handler,this.undoable=(e=n.undoable)!==null&&e!==void 0?e:!0}};const hy=(n,e)=>{if(ao(e))return e.exec(n);const t=e(n);if(!t)return null;const r=[t.text];return r.index=t.index,r.input=n,r.data=t.data,t.replaceWith&&(t.text.includes(t.replaceWith)||console.warn('[tiptap warn]: "inputRuleMatch.replaceWith" must be part of "inputRuleMatch.text".'),r.push(t.replaceWith)),r};function py(n){const{editor:e,from:t,to:r,text:i,insertText:s}=n;if(!s)return{inputTransaction:null,tr:e.view.state.tr};const o=e.view.state.tr.insertText(i,t,r);return{inputTransaction:o,tr:je.create({doc:o.doc,selection:o.selection,storedMarks:o.storedMarks}).tr}}function my(n){const{editor:e,from:t,to:r,text:i,rule:s,match:o,plugin:l,insertText:a}=n,{view:c}=e,{inputTransaction:u,tr:d}=py({editor:e,from:t,to:r,text:i,insertText:a}),f=u?t+i.length:r,h=gi({state:c.state,transaction:d}),p={from:t-(o[0].length-i.length),to:f},{commands:m,chain:g,can:y}=new Yt({editor:e,state:h});return s.handler({state:h,range:p,match:o,commands:m,chain:g,can:y})===null||!d.steps.length?!1:(u&&(c.dispatch(u),!c.state.doc.eq(u.doc))||(dm(d),d.setMeta("inputRule",!0),s.undoable&&d.setMeta(l,{transform:d,from:t,to:f,text:i}),c.dispatch(d)),!0)}function gy(n,e,t){const r=e[0].length-t.length;if(r<=0)return!0;const i=n.parentOffset-r;return i>=0&&n.parent.textBetween(i,n.parentOffset)===e[0].slice(0,r)}function tr(n){var e;const{editor:t,from:r,to:i,text:s,rules:o,plugin:l,insertText:a}=n,{view:c}=t;if(c.composing)return!1;const u=c.state.doc.resolve(r);if(u.parent.type.spec.code||!((e=u.nodeBefore||u.nodeAfter)===null||e===void 0)&&e.marks.find(f=>f.type.spec.code))return!1;const d=yg(u)+s;for(const f of o){const h=hy(d,f.find);if(!(!h||!gy(u,h,s))&&my({editor:t,from:r,to:i,text:s,rule:f,match:h,plugin:l,insertText:a}))return!0}return!1}function yy(n){const{editor:e,rules:t}=n,r=new z({state:{init(){return null},apply(i,s,o){const l=i.getMeta(r);if(l)return l;const a=i.getMeta("applyInputRules");return a&&setTimeout(()=>{let{text:c}=a;typeof c=="string"?c=c:c=fo(b.from(c),o.schema);const{from:u}=a,d=u+c.length;tr({editor:e,from:u,to:d,text:c,rules:t,plugin:r})}),i.selectionSet||i.docChanged?null:s}},props:{handleTextInput(i,s,o,l){return tr({editor:e,from:s,to:o,text:l,rules:t,plugin:r,insertText:!0})},handleDOMEvents:{compositionend:i=>(setTimeout(()=>{const{$cursor:s}=i.state.selection;s&&tr({editor:e,from:s.pos,to:s.pos,text:"",rules:t,plugin:r})}),!1)},handleKeyDown(i,s){if(s.key!=="Enter")return!1;const{$cursor:o}=i.state.selection;return o?tr({editor:e,from:o.pos,to:o.pos,text:` +`,rules:t,plugin:r}):!1}},isInputRules:!0});return r}var ho=class{constructor(n={}){this.type="extendable",this.parent=null,this.child=null,this.name="",this.config={name:this.name},this.config={...this.config,...n},this.name=this.config.name}get options(){return{...L(M(this,"addOptions",{name:this.name}))}}get storage(){return{...L(M(this,"addStorage",{name:this.name,options:this.options}))}}configure(n={}){const e=this.extend({...this.config,addOptions:()=>$u(this.options,n)});return e.name=this.name,e.parent=this.parent,this.child=null,e}extend(n={}){const e=new this.constructor({...this.config,...n});return e.parent=this,this.child=e,e.name="name"in n?n.name:e.parent.name,e}},gt=class Hu extends ho{constructor(...e){super(...e),this.type="mark"}static create(e={}){const t=typeof e=="function"?e():e;return new Hu(t)}static handleExit({editor:e,mark:t}){const{tr:r}=e.state,i=e.state.selection.$from;if(i.pos===i.end()){const s=i.marks();if(!s.find(l=>l?.type.name===t.name))return!1;const o=s.find(l=>l?.type.name===t.name);return o&&r.removeStoredMark(o),r.insertText(" ",i.pos),e.view.dispatch(r),!0}return!1}configure(e){return super.configure(e)}extend(e){const t=typeof e=="function"?e():e;return super.extend(t)}},Fu=class{constructor(n){this.find=n.find,this.handler=n.handler}};const by=(n,e,t)=>{if(ao(e))return[...n.matchAll(e)];const r=e(n,t);return r?r.map(i=>{const s=[i.text];return s.index=i.index,s.input=n,s.data=i.data,i.replaceWith&&(i.text.includes(i.replaceWith)||console.warn('[tiptap warn]: "pasteRuleMatch.replaceWith" must be part of "pasteRuleMatch.text".'),s.push(i.replaceWith)),s}):[]};function ky(n){const{editor:e,state:t,from:r,to:i,rule:s,pasteEvent:o,dropEvent:l}=n,{commands:a,chain:c,can:u}=new Yt({editor:e,state:t}),d=[];return t.doc.nodesBetween(r,i,(f,h)=>{var p,m,g,y;if(!((p=f.type)===null||p===void 0||(p=p.spec)===null||p===void 0)&&p.code||!(f.isText||f.isTextblock||f.isInline))return;const k=(m=(g=(y=f.content)===null||y===void 0?void 0:y.size)!==null&&g!==void 0?g:f.nodeSize)!==null&&m!==void 0?m:0,w=Math.max(r,h),C=Math.min(i,h+k);if(w>=C)return;const O=f.isText?f.text||"":f.textBetween(w-h,C-h,void 0,"");by(O,s.find,o).forEach(B=>{if(B.index===void 0)return;const E=w+B.index+1,D=E+B[0].length,P={from:t.tr.mapping.map(E),to:t.tr.mapping.map(D)},te=s.handler({state:t,range:P,match:B,commands:a,chain:c,can:u,pasteEvent:o,dropEvent:l});d.push(te)})}),d.every(f=>f!==null)}let jt=null;const wy=n=>{var e;const t=new ClipboardEvent("paste",{clipboardData:new DataTransfer});return(e=t.clipboardData)===null||e===void 0||e.setData("text/html",n),t};function Sy(n){const{editor:e,rules:t}=n;let r=null,i=!1,s=!1,o=typeof ClipboardEvent<"u"?new ClipboardEvent("paste"):null,l;try{l=typeof DragEvent<"u"?new DragEvent("drop"):null}catch{l=null}const a=({state:c,from:u,to:d,rule:f,pasteEvt:h})=>{const p=c.tr,m=gi({state:c,transaction:p});if(!(!ky({editor:e,state:m,from:Math.max(u-1,0),to:d.b-1,rule:f,pasteEvent:h,dropEvent:l})||!p.steps.length)){try{l=typeof DragEvent<"u"?new DragEvent("drop"):null}catch{l=null}return o=typeof ClipboardEvent<"u"?new ClipboardEvent("paste"):null,p}};return e.on("destroy",()=>{jt===e&&(jt=null)}),t.map(c=>new z({view(u){const d=h=>{var p;r=!((p=u.dom.parentElement)===null||p===void 0)&&p.contains(h.target)?u.dom.parentElement:null,r&&(jt=e)},f=()=>{jt&&(jt=null)};return window.addEventListener("dragstart",d),window.addEventListener("dragend",f),{destroy(){window.removeEventListener("dragstart",d),window.removeEventListener("dragend",f)}}},props:{handleDOMEvents:{drop:(u,d)=>{if(s=r===u.dom.parentElement,l=d,!s){const f=jt;f?.isEditable&&setTimeout(()=>{if(f.isDestroyed)return;const h=f.state.selection;h&&f.commands.deleteRange({from:h.from,to:h.to})},10)}return!1},paste:(u,d)=>{var f;const h=(f=d.clipboardData)===null||f===void 0?void 0:f.getData("text/html");return o=d,i=!!h?.includes("data-pm-slice"),!1}}},appendTransaction:(u,d,f)=>{const h=u[0],p=h.getMeta("uiEvent")==="paste"&&!i,m=h.getMeta("uiEvent")==="drop"&&!s,g=h.getMeta("applyPasteRules"),y=!!g;if(!p&&!m&&!y)return;if(y){let{text:C}=g;typeof C=="string"?C=C:C=fo(b.from(C),f.schema);const{from:O}=g,B=O+C.length,E=wy(C);return a({rule:c,state:f,from:O,to:{b:B},pasteEvt:E})}const k=d.doc.content.findDiffStart(f.doc.content),w=d.doc.content.findDiffEnd(f.doc.content);if(!(!cy(k)||!w||k===w.b))return a({rule:c,state:f,from:k,to:w,pasteEvt:o})}}))}var Si=class{constructor(n,e){this.splittableMarks=[],this.nonClearableMarks=[],this.decorationManager=null,this.editor=e,this.baseExtensions=n,this.extensions=Mu(n),this.schema=cg(this.extensions,e),this.setupExtensions()}get commands(){return this.extensions.reduce((n,e)=>{const t=M(e,"addCommands",{name:e.name,options:e.options,storage:this.editor.extensionStorage[e.name],editor:this.editor,type:Wt(e.name,this.schema)});return t?{...n,...t()}:n},{})}get plugins(){const{editor:n}=this,e=Sn([...this.extensions].reverse()).flatMap(r=>{const i={name:r.name,options:r.options,storage:this.editor.extensionStorage[r.name],editor:n,type:Wt(r.name,this.schema)},s=[],o=M(r,"addKeyboardShortcuts",i);let l={};if(r.type==="mark"&&M(r,"exitable",i)&&(l.ArrowRight=()=>gt.handleExit({editor:n,mark:r})),o){const f=Object.fromEntries(Object.entries(o()).map(([h,p])=>[h,()=>p({editor:n})]));l={...l,...f}}const a=rm(l);s.push(a);const c=M(r,"addInputRules",i);if(Bl(r,n.options.enableInputRules)&&c){const f=c();if(f&&f.length){const h=yy({editor:n,rules:f}),p=Array.isArray(h)?h:[h];s.push(...p)}}const u=M(r,"addPasteRules",i);if(Bl(r,n.options.enablePasteRules)&&u){const f=u();if(f&&f.length){const h=Sy({editor:n,rules:f});s.push(...h)}}const d=M(r,"addProseMirrorPlugins",i);if(d){const f=d();s.push(...f)}return s}),t=this.createDecorationPlugin();return t&&e.push(t),e}createDecorationPlugin(){var n;const{editor:e}=this;(n=this.decorationManager)===null||n===void 0||n.destroy();const t=[];return this.extensions.forEach(r=>{const i=M(r,"addDecorations",{name:r.name,options:r.options,storage:this.editor.extensionStorage[r.name],editor:e,type:Wt(r.name,this.schema)});i&&t.push({name:r.name,addDecorations:i})}),this.decorationManager=new oy({editor:e,entries:t}),this.decorationManager.plugin}get attributes(){return vu(this.extensions)}get nodeViews(){const{editor:n}=this,{nodeExtensions:e}=nn(this.extensions);return Object.fromEntries(e.filter(t=>!!M(t,"addNodeView")).map(t=>{const r=this.attributes.filter(l=>l.type===t.name),i=M(t,"addNodeView",{name:t.name,options:t.options,storage:this.editor.extensionStorage[t.name],editor:n,type:X(t.name,this.schema)});if(!i)return[];const s=i();if(!s)return[];const o=(l,a,c,u,d)=>{const f=rn(l,r);return s({node:l,view:a,getPos:c,decorations:u,innerDecorations:d,editor:n,extension:t,HTMLAttributes:f})};return[t.name,o]}))}dispatchTransaction(n){const{editor:e}=this;return Sn([...this.extensions].reverse()).reduceRight((t,r)=>{const i={name:r.name,options:r.options,storage:this.editor.extensionStorage[r.name],editor:e,type:Wt(r.name,this.schema)},s=M(r,"dispatchTransaction",i);return s?o=>{s.call(i,{transaction:o,next:t})}:t},n)}transformPastedHTML(n){const{editor:e}=this;return Sn([...this.extensions]).reduce((t,r)=>{const i={name:r.name,options:r.options,storage:this.editor.extensionStorage[r.name],editor:e,type:Wt(r.name,this.schema)},s=M(r,"transformPastedHTML",i);return s?(o,l)=>{const a=t(o,l);return s.call(i,a)}:t},n||(t=>t))}get markViews(){const{editor:n}=this,{markExtensions:e}=nn(this.extensions);return Object.fromEntries(e.filter(t=>!!M(t,"addMarkView")).map(t=>{const r=this.attributes.filter(o=>o.type===t.name),i=M(t,"addMarkView",{name:t.name,options:t.options,storage:this.editor.extensionStorage[t.name],editor:n,type:Ye(t.name,this.schema)});if(!i)return[];const s=(o,l,a)=>{const c=rn(o,r);return i()({mark:o,view:l,inline:a,editor:n,extension:t,HTMLAttributes:c,updateAttributes:u=>{fy(o,n,u)}})};return[t.name,s]}))}destroy(){var n;(n=this.decorationManager)===null||n===void 0||n.destroy(),this.extensions.forEach(e=>{let t=e;for(;t.parent;){const r=t.parent;r.child===t&&(r.child=null),t=r}}),this.extensions=[],this.baseExtensions=[],this.decorationManager=null,this.schema=null,this.editor=null}setupExtensions(){const n=this.extensions;this.editor.extensionStorage=Object.fromEntries(n.map(e=>[e.name,e.storage])),n.forEach(e=>{const t={name:e.name,options:e.options,storage:this.editor.extensionStorage[e.name],editor:this.editor,type:Wt(e.name,this.schema)};if(e.type==="mark"){var r,i;(!((r=L(M(e,"keepOnSplit",t)))!==null&&r!==void 0)||r)&&this.splittableMarks.push(e.name),!((i=L(M(e,"clearable",t)))!==null&&i!==void 0)||i||this.nonClearableMarks.push(e.name)}const s=M(e,"onBeforeCreate",t),o=M(e,"onCreate",t),l=M(e,"onUpdate",t),a=M(e,"onSelectionUpdate",t),c=M(e,"onTransaction",t),u=M(e,"onFocus",t),d=M(e,"onBlur",t),f=M(e,"onDestroy",t);s&&this.editor.on("beforeCreate",s),o&&this.editor.on("create",o),l&&this.editor.on("update",l),a&&this.editor.on("selectionUpdate",a),c&&this.editor.on("transaction",c),u&&this.editor.on("focus",u),d&&this.editor.on("blur",d),f&&this.editor.on("destroy",f)})}};Si.resolve=Mu;Si.sort=Sn;Si.flatten=uo;var j=class Vu extends ho{constructor(...e){super(...e),this.type="extension"}static create(e={}){const t=typeof e=="function"?e():e;return new Vu(t)}configure(e){return super.configure(e)}extend(e){const t=typeof e=="function"?e():e;return super.extend(t)}};const Cy=j.create({name:"clipboardTextSerializer",addOptions(){return{blockSeparator:void 0}},addProseMirrorPlugins(){return[new z({key:new W("clipboardTextSerializer"),props:{clipboardTextSerializer:()=>{const{editor:n}=this,{state:e,schema:t}=n,{doc:r,selection:i}=e,s=Eu(t),{blockSeparator:o}=this.options,l={...o!==void 0?{blockSeparator:o}:{},textSerializers:s};return[...i.ranges].sort((a,c)=>a.$from.pos-c.$from.pos).map(({$from:a,$to:c})=>Tu(r,{from:a.pos,to:c.pos},l)).join(o??` -`)}}})]}}),Wm=W.create({name:"commands",addCommands(){return{...hm}}}),Km=W.create({name:"delete",onUpdate({transaction:n,appendedTransactions:e}){var t,r;const i=()=>{var s,o,l;if((s=(o=this.editor.options.coreExtensionOptions)===null||o===void 0||(o=o.delete)===null||o===void 0||(l=o.filterTransaction)===null||l===void 0?void 0:l.call(o,n))!==null&&s!==void 0?s:n.getMeta("y-sync$"))return;const a=bc(n.before,[n,...e]);Gr(a).forEach(u=>{a.mapping.mapResult(u.oldRange.from).deletedAfter&&a.mapping.mapResult(u.oldRange.to).deletedBefore&&a.before.nodesBetween(u.oldRange.from,u.oldRange.to,(d,f)=>{const h=f+d.nodeSize-2,p=u.oldRange.from<=f&&h<=u.oldRange.to;this.editor.emit("delete",{type:"node",node:d,from:f,to:h,newFrom:a.mapping.map(f),newTo:a.mapping.map(h),deletedRange:u.oldRange,newRange:u.newRange,partial:!p,editor:this.editor,transaction:n,combinedTransform:a})})});const c=a.mapping;a.steps.forEach((u,d)=>{if(u instanceof Ce){var f,h;const p=c.slice(d).map(u.from,-1),m=c.slice(d).map(u.to),g=c.invert().map(p,-1),y=c.invert().map(m),S=p>0?(f=a.doc.nodeAt(p-1))===null||f===void 0?void 0:f.marks.some(C=>C.eq(u.mark)):!1,x=(h=a.doc.nodeAt(m))===null||h===void 0?void 0:h.marks.some(C=>C.eq(u.mark));this.editor.emit("delete",{type:"mark",mark:u.mark,from:u.from,to:u.to,deletedRange:{from:g,to:y},newRange:{from:p,to:m},partial:!!(x||S),editor:this.editor,transaction:n,combinedTransform:a})}})};!((t=(r=this.editor.options.coreExtensionOptions)===null||r===void 0||(r=r.delete)===null||r===void 0?void 0:r.async)!==null&&t!==void 0)||t?setTimeout(i,0):i()}}),_m=W.create({name:"drop",addProseMirrorPlugins(){return[new $({key:new _("tiptapDrop"),props:{handleDrop:(n,e,t,r)=>{this.editor.emit("drop",{editor:this.editor,event:e,slice:t,moved:r})}}})]}}),Um=W.create({name:"editable",addProseMirrorPlugins(){return[new $({key:new _("editable"),props:{editable:()=>this.editor.options.editable}})]}}),qm=new _("focusEvents"),Jm=W.create({name:"focusEvents",addProseMirrorPlugins(){const{editor:n}=this;return[new $({key:qm,props:{handleDOMEvents:{focus:(e,t)=>{n.isFocused=!0;const r=n.state.tr.setMeta("focus",{event:t}).setMeta("addToHistory",!1);return e.dispatch(r),!1},blur:(e,t)=>{n.isFocused=!1;const r=n.state.tr.setMeta("blur",{event:t}).setMeta("addToHistory",!1);return e.dispatch(r),!1}}}})]}}),Gm=W.create({name:"keymap",addKeyboardShortcuts(){const n=()=>this.editor.commands.first(({commands:o})=>[()=>o.undoInputRule(),()=>o.command(({tr:l})=>{const{selection:a,doc:c}=l,{empty:u,$anchor:d}=a,{pos:f,parent:h}=d,p=d.parent.isTextblock&&f>0?l.doc.resolve(f-1):d,m=p.parent.type.spec.isolating,g=d.pos-d.parentOffset,y=m&&p.parent.childCount===1?g===d.pos:O.atStart(c).from===f;return!u||!h.type.isTextblock||h.textContent.length||!y||y&&d.parent.type.name==="paragraph"?!1:o.clearNodes()}),()=>o.deleteSelection(),()=>o.joinBackward(),()=>o.selectNodeBackward()]),e=()=>this.editor.commands.first(({commands:o})=>[()=>o.deleteSelection(),()=>o.deleteCurrentNode(),()=>o.joinForward(),()=>o.selectNodeForward()]),r={Enter:()=>this.editor.commands.first(({commands:o})=>[()=>o.newlineInCode(),()=>o.createParagraphNear(),()=>o.liftEmptyBlock(),()=>o.splitBlock()]),"Mod-Enter":()=>this.editor.commands.exitCode(),Backspace:n,"Mod-Backspace":n,"Shift-Backspace":n,Delete:e,"Mod-Delete":e,"Mod-a":()=>this.editor.commands.selectAll()},i={...r},s={...r,"Ctrl-h":n,"Alt-Backspace":n,"Ctrl-d":e,"Ctrl-Alt-Backspace":e,"Alt-Delete":e,"Alt-d":e,"Ctrl-a":()=>this.editor.commands.selectTextblockStart(),"Ctrl-e":()=>this.editor.commands.selectTextblockEnd()};return ar()||gc()?s:i},addProseMirrorPlugins(){return[new $({key:new _("clearDocument"),appendTransaction:(n,e,t)=>{if(n.some(h=>h.getMeta("composition")))return;const r=n.some(h=>h.docChanged)&&!e.doc.eq(t.doc),i=n.some(h=>h.getMeta("preventClearDocument"));if(!r||i)return;const{empty:s,from:o,to:l}=e.selection,a=O.atStart(e.doc).from,c=O.atEnd(e.doc).to;if(s||!(o===a&&l===c)||!Dn(t.doc))return;const u=t.tr,d=Ur({state:t,transaction:u}),{commands:f}=new $t({editor:this.editor,state:d});if(f.clearNodes(),!!u.steps.length)return u}})]}}),Ym=W.create({name:"paste",addProseMirrorPlugins(){return[new $({key:new _("tiptapPaste"),props:{handlePaste:(n,e,t)=>{this.editor.emit("paste",{editor:this.editor,event:e,slice:t})}}})]}}),Xm=W.create({name:"tabindex",addOptions(){return{value:void 0}},addProseMirrorPlugins(){return[new $({key:new _("tabindex"),props:{attributes:()=>{var n;return!this.editor.isEditable&&this.options.value===void 0?{}:{tabindex:(n=this.options.value)!==null&&n!==void 0?n:"0"}}}})]}}),Qm=W.create({name:"textDirection",addOptions(){return{direction:void 0}},addGlobalAttributes(){if(!this.options.direction)return[];const{nodeExtensions:n}=Kt(this.extensions);return[{types:n.filter(e=>e.name!=="text").map(e=>e.name),attributes:{dir:{default:this.options.direction,parseHTML:e=>{const t=e.getAttribute("dir");return t&&(t==="ltr"||t==="rtl"||t==="auto")?t:this.options.direction},renderHTML:e=>e.dir?{dir:e.dir}:{}}}}]},addProseMirrorPlugins(){return[new $({key:new _("textDirection"),props:{attributes:()=>{const n=this.options.direction;return n?{dir:n}:{}}}})]}});let sl=!1;function Zm(n){if(sl)return;sl=!0;let e;try{e=H.fromJSON(n,{from:0,to:0}).slice.content}catch{return}e instanceof b||console.warn("[tiptap warn]: prosemirror-model is loaded more than once. Wrapping and splitting nodes will fail. Deduplicate it in your lock file, or alias it to a single copy in your bundler.")}var eg=class en{get name(){return this.node.type.name}constructor(e,t,r=!1,i=null){this.currentNode=null,this.actualDepth=null,this.isBlock=r,this.resolvedPos=e,this.editor=t,this.currentNode=i}get node(){return this.currentNode||this.resolvedPos.node()}get element(){return this.editor.view.domAtPos(this.pos).node}get depth(){var e;return(e=this.actualDepth)!==null&&e!==void 0?e:this.resolvedPos.depth}get pos(){return this.resolvedPos.pos}get content(){return this.node.content}set content(e){let t=this.from,r=this.to;if(this.isBlock){if(this.content.size===0){console.error(`You can’t set content on a block node. Tried to set content on ${this.name} at ${this.pos}`);return}t=this.from+1,r=this.to-1}this.editor.commands.insertContentAt({from:t,to:r},e)}get attributes(){return this.node.attrs}get textContent(){return this.node.textContent}get size(){return this.node.nodeSize}get from(){return this.isBlock?this.pos:this.resolvedPos.start(this.resolvedPos.depth)}get range(){return{from:this.from,to:this.to}}get to(){return this.isBlock?this.pos+this.size:this.resolvedPos.end(this.resolvedPos.depth)+(this.node.isText?0:1)}get parent(){if(this.depth===0)return null;const e=this.resolvedPos.start(this.resolvedPos.depth-1),t=this.resolvedPos.doc.resolve(e);return new en(t,this.editor)}get before(){let e=this.resolvedPos.doc.resolve(this.from-(this.isBlock?1:2));return e.depth!==this.depth&&(e=this.resolvedPos.doc.resolve(this.from-3)),new en(e,this.editor)}get after(){let e=this.resolvedPos.doc.resolve(this.to+(this.isBlock?2:1));return e.depth!==this.depth&&(e=this.resolvedPos.doc.resolve(this.to+3)),new en(e,this.editor)}get children(){const e=[];return this.node.content.forEach((t,r)=>{const i=t.isBlock&&!t.isTextblock,s=t.isAtom&&!t.isText,o=t.isInline,l=this.pos+r+(s?0:1);if(l<0||l>this.resolvedPos.doc.nodeSize-2)return;const a=this.resolvedPos.doc.resolve(l);if(!i&&!o&&a.depth<=this.depth)return;const c=new en(a,this.editor,i,i||o?t:null);i&&(c.actualDepth=this.depth+1),e.push(c)}),e}get firstChild(){return this.children[0]||null}get lastChild(){const e=this.children;return e[e.length-1]||null}closest(e,t={}){let r=null,i=this.parent;for(;i&&!r;){if(i.node.type.name===e)if(Object.keys(t).length>0){const s=i.node.attrs,o=Object.keys(t);for(let l=0;l{r&&i.length>0||(o.node.type.name===e&&s.every(l=>t[l]===o.node.attrs[l])&&i.push(o),!(r&&i.length>0)&&(i=i.concat(o.querySelectorAll(e,t,r))))}),i}setAttribute(e){const{tr:t}=this.editor.state;t.setNodeMarkup(this.from,void 0,{...this.node.attrs,...e}),this.editor.view.dispatch(t)}};const tg=`.ProseMirror { +`)}}})]}}),xy=j.create({name:"commands",addCommands(){return{...Kg}}}),vy=j.create({name:"delete",onUpdate({transaction:n,appendedTransactions:e}){var t,r;const i=()=>{var s,o,l;if((s=(o=this.editor.options.coreExtensionOptions)===null||o===void 0||(o=o.delete)===null||o===void 0||(l=o.filterTransaction)===null||l===void 0?void 0:l.call(o,n))!==null&&s!==void 0?s:n.getMeta("y-sync$"))return;const a=xu(n.before,[n,...e]);ki(a).forEach(u=>{a.mapping.mapResult(u.oldRange.from).deletedAfter&&a.mapping.mapResult(u.oldRange.to).deletedBefore&&a.before.nodesBetween(u.oldRange.from,u.oldRange.to,(d,f)=>{const h=f+d.nodeSize-2,p=u.oldRange.from<=f&&h<=u.oldRange.to;this.editor.emit("delete",{type:"node",node:d,from:f,to:h,newFrom:a.mapping.map(f),newTo:a.mapping.map(h),deletedRange:u.oldRange,newRange:u.newRange,partial:!p,editor:this.editor,transaction:n,combinedTransform:a})})});const c=a.mapping;a.steps.forEach((u,d)=>{if(u instanceof Ee){var f,h;const p=c.slice(d).map(u.from,-1),m=c.slice(d).map(u.to),g=c.invert().map(p,-1),y=c.invert().map(m),k=p>0?(f=a.doc.nodeAt(p-1))===null||f===void 0?void 0:f.marks.some(C=>C.eq(u.mark)):!1,w=(h=a.doc.nodeAt(m))===null||h===void 0?void 0:h.marks.some(C=>C.eq(u.mark));this.editor.emit("delete",{type:"mark",mark:u.mark,from:u.from,to:u.to,deletedRange:{from:g,to:y},newRange:{from:p,to:m},partial:!!(w||k),editor:this.editor,transaction:n,combinedTransform:a})}})};!((t=(r=this.editor.options.coreExtensionOptions)===null||r===void 0||(r=r.delete)===null||r===void 0?void 0:r.async)!==null&&t!==void 0)||t?setTimeout(i,0):i()}}),My=j.create({name:"drop",addProseMirrorPlugins(){return[new z({key:new W("tiptapDrop"),props:{handleDrop:(n,e,t,r)=>{this.editor.emit("drop",{editor:this.editor,event:e,slice:t,moved:r})}}})]}}),Ty=j.create({name:"editable",addProseMirrorPlugins(){return[new z({key:new W("editable"),props:{editable:()=>this.editor.options.editable}})]}}),Ey=new W("focusEvents"),Ay=j.create({name:"focusEvents",addProseMirrorPlugins(){const{editor:n}=this;return[new z({key:Ey,props:{handleDOMEvents:{focus:(e,t)=>{n.isFocused=!0;const r=n.state.tr.setMeta("focus",{event:t}).setMeta("addToHistory",!1);return e.dispatch(r),!1},blur:(e,t)=>{n.isFocused=!1;const r=n.state.tr.setMeta("blur",{event:t}).setMeta("addToHistory",!1);return e.dispatch(r),!1}}}})]}}),Ny=j.create({name:"keymap",addKeyboardShortcuts(){const n=()=>this.editor.commands.first(({commands:o})=>[()=>o.undoInputRule(),()=>o.command(({tr:l})=>{const{selection:a,doc:c}=l,{empty:u,$anchor:d}=a,{pos:f,parent:h}=d,p=d.parent.isTextblock&&f>0?l.doc.resolve(f-1):d,m=p.parent.type.spec.isolating,g=d.pos-d.parentOffset,y=m&&p.parent.childCount===1?g===d.pos:N.atStart(c).from===f;return!u||!h.type.isTextblock||h.textContent.length||!y||y&&d.parent.type.name==="paragraph"?!1:o.clearNodes()}),()=>o.deleteSelection(),()=>o.joinBackward(),()=>o.selectNodeBackward()]),e=()=>this.editor.commands.first(({commands:o})=>[()=>o.deleteSelection(),()=>o.deleteCurrentNode(),()=>o.joinForward(),()=>o.selectNodeForward()]),r={Enter:()=>this.editor.commands.first(({commands:o})=>[()=>o.newlineInCode(),()=>o.createParagraphNear(),()=>o.liftEmptyBlock(),()=>o.splitBlock()]),"Mod-Enter":()=>this.editor.commands.exitCode(),Backspace:n,"Mod-Backspace":n,"Shift-Backspace":n,Delete:e,"Mod-Delete":e,"Mod-a":()=>this.editor.commands.selectAll()},i={...r},s={...r,"Ctrl-h":n,"Alt-Backspace":n,"Ctrl-d":e,"Ctrl-Alt-Backspace":e,"Alt-Delete":e,"Alt-d":e,"Ctrl-a":()=>this.editor.commands.selectTextblockStart(),"Ctrl-e":()=>this.editor.commands.selectTextblockEnd()};return Or()||Su()?s:i},addProseMirrorPlugins(){return[new z({key:new W("clearDocument"),appendTransaction:(n,e,t)=>{if(n.some(h=>h.getMeta("composition")))return;const r=n.some(h=>h.docChanged)&&!e.doc.eq(t.doc),i=n.some(h=>h.getMeta("preventClearDocument"));if(!r||i)return;const{empty:s,from:o,to:l}=e.selection,a=N.atStart(e.doc).from,c=N.atEnd(e.doc).to;if(s||!(o===a&&l===c)||!Jn(t.doc))return;const u=t.tr,d=gi({state:t,transaction:u}),{commands:f}=new Yt({editor:this.editor,state:d});if(f.clearNodes(),!!u.steps.length)return u}})]}}),Oy=j.create({name:"paste",addProseMirrorPlugins(){return[new z({key:new W("tiptapPaste"),props:{handlePaste:(n,e,t)=>{this.editor.emit("paste",{editor:this.editor,event:e,slice:t})}}})]}}),Ry=j.create({name:"tabindex",addOptions(){return{value:void 0}},addProseMirrorPlugins(){return[new z({key:new W("tabindex"),props:{attributes:()=>{var n;return!this.editor.isEditable&&this.options.value===void 0?{}:{tabindex:(n=this.options.value)!==null&&n!==void 0?n:"0"}}}})]}}),Dy=j.create({name:"textDirection",addOptions(){return{direction:void 0}},addGlobalAttributes(){if(!this.options.direction)return[];const{nodeExtensions:n}=nn(this.extensions);return[{types:n.filter(e=>e.name!=="text").map(e=>e.name),attributes:{dir:{default:this.options.direction,parseHTML:e=>{const t=e.getAttribute("dir");return t&&(t==="ltr"||t==="rtl"||t==="auto")?t:this.options.direction},renderHTML:e=>e.dir?{dir:e.dir}:{}}}}]},addProseMirrorPlugins(){return[new z({key:new W("textDirection"),props:{attributes:()=>{const n=this.options.direction;return n?{dir:n}:{}}}})]}});let Ul=!1;function Iy(n){if(Ul)return;Ul=!0;let e;try{e=K.fromJSON(n,{from:0,to:0}).slice.content}catch{return}e instanceof b||console.warn("[tiptap warn]: prosemirror-model is loaded more than once. Wrapping and splitting nodes will fail. Deduplicate it in your lock file, or alias it to a single copy in your bundler.")}var Ly=class mn{get name(){return this.node.type.name}constructor(e,t,r=!1,i=null){this.currentNode=null,this.actualDepth=null,this.isBlock=r,this.resolvedPos=e,this.editor=t,this.currentNode=i}get node(){return this.currentNode||this.resolvedPos.node()}get element(){return this.editor.view.domAtPos(this.pos).node}get depth(){var e;return(e=this.actualDepth)!==null&&e!==void 0?e:this.resolvedPos.depth}get pos(){return this.resolvedPos.pos}get content(){return this.node.content}set content(e){let t=this.from,r=this.to;if(this.isBlock){if(this.content.size===0){console.error(`You can’t set content on a block node. Tried to set content on ${this.name} at ${this.pos}`);return}t=this.from+1,r=this.to-1}this.editor.commands.insertContentAt({from:t,to:r},e)}get attributes(){return this.node.attrs}get textContent(){return this.node.textContent}get size(){return this.node.nodeSize}get from(){return this.isBlock?this.pos:this.resolvedPos.start(this.resolvedPos.depth)}get range(){return{from:this.from,to:this.to}}get to(){return this.isBlock?this.pos+this.size:this.resolvedPos.end(this.resolvedPos.depth)+(this.node.isText?0:1)}get parent(){if(this.depth===0)return null;const e=this.resolvedPos.start(this.resolvedPos.depth-1),t=this.resolvedPos.doc.resolve(e);return new mn(t,this.editor)}get before(){let e=this.resolvedPos.doc.resolve(this.from-(this.isBlock?1:2));return e.depth!==this.depth&&(e=this.resolvedPos.doc.resolve(this.from-3)),new mn(e,this.editor)}get after(){let e=this.resolvedPos.doc.resolve(this.to+(this.isBlock?2:1));return e.depth!==this.depth&&(e=this.resolvedPos.doc.resolve(this.to+3)),new mn(e,this.editor)}get children(){const e=[];return this.node.content.forEach((t,r)=>{const i=t.isBlock&&!t.isTextblock,s=t.isAtom&&!t.isText,o=t.isInline,l=this.pos+r+(s?0:1);if(l<0||l>this.resolvedPos.doc.nodeSize-2)return;const a=this.resolvedPos.doc.resolve(l);if(!i&&!o&&a.depth<=this.depth)return;const c=new mn(a,this.editor,i,i||o?t:null);i&&(c.actualDepth=this.depth+1),e.push(c)}),e}get firstChild(){return this.children[0]||null}get lastChild(){const e=this.children;return e[e.length-1]||null}closest(e,t={}){let r=null,i=this.parent;for(;i&&!r;){if(i.node.type.name===e)if(Object.keys(t).length>0){const s=i.node.attrs,o=Object.keys(t);for(let l=0;l{r&&i.length>0||(o.node.type.name===e&&s.every(l=>t[l]===o.node.attrs[l])&&i.push(o),!(r&&i.length>0)&&(i=i.concat(o.querySelectorAll(e,t,r))))}),i}setAttribute(e){const{tr:t}=this.editor.state;t.setNodeMarkup(this.from,void 0,{...this.node.attrs,...e}),this.editor.view.dispatch(t)}};const Py=`.ProseMirror { position: relative; } @@ -93,47 +93,62 @@ img.ProseMirror-separator { .ProseMirror-focused .ProseMirror-gapcursor { display: block; -}`;var ng=class extends mm{constructor(n={}){super(),this.css=null,this.className="tiptap",this.editorView=null,this.isFocused=!1,this.destroyed=!1,this.isInitialized=!1,this.extensionStorage={},this.instanceId=Math.random().toString(36).slice(2,9),this.hasWarnedStaleDecorationRead=!1,this.options={element:typeof document<"u"?document.createElement("div"):null,content:"",injectCSS:!0,injectNonce:void 0,extensions:[],autofocus:!1,editable:!0,textDirection:void 0,editorProps:{},parseOptions:{},coreExtensionOptions:{},enableInputRules:!0,enablePasteRules:!0,enableCoreExtensions:!0,enableContentCheck:!1,emitContentError:!1,onBeforeCreate:()=>null,onCreate:()=>null,onMount:()=>null,onUnmount:()=>null,onUpdate:()=>null,onSelectionUpdate:()=>null,onTransaction:()=>null,onFocus:()=>null,onBlur:()=>null,onDestroy:()=>null,onContentError:({error:t})=>{throw t},onPaste:()=>null,onDrop:()=>null,onDelete:()=>null,enableExtensionDispatchTransaction:!0},this.isCapturingTransaction=!1,this.capturedTransaction=null,this.utils={getUpdatedPosition:jp,createMappablePosition:Wp},this.setOptions(n),this.createExtensionManager(),this.createCommandManager(),this.createSchema(),this.on("beforeCreate",this.options.onBeforeCreate),this.emit("beforeCreate",{editor:this}),this.on("mount",this.options.onMount),this.on("unmount",this.options.onUnmount),this.on("contentError",this.options.onContentError),this.on("create",this.options.onCreate),this.on("update",this.options.onUpdate),this.on("selectionUpdate",this.options.onSelectionUpdate),this.on("transaction",this.options.onTransaction),this.on("focus",this.options.onFocus),this.on("blur",this.options.onBlur),this.on("destroy",this.options.onDestroy),this.on("drop",({event:t,slice:r,moved:i})=>this.options.onDrop(t,r,i)),this.on("paste",({event:t,slice:r})=>this.options.onPaste(t,r)),this.on("delete",this.options.onDelete);const e=this.createDoc();if(!this.editorState){const t=Ki(e,this.options.autofocus);this.editorState=Be.create({doc:e,schema:this.schema,selection:t||void 0})}Zm(this.schema),this.options.element&&this.mount(this.options.element)}mount(n){if(typeof document>"u")throw new Error("[tiptap error]: The editor cannot be mounted because there is no 'document' defined in this environment.");this.createView(n),this.emit("mount",{editor:this}),this.css&&!document.head.contains(this.css)&&document.head.appendChild(this.css),window.setTimeout(()=>{this.isDestroyed||(this.options.autofocus!==!1&&this.options.autofocus!==null&&this.commands.focus(this.options.autofocus),this.emit("create",{editor:this}),this.isInitialized=!0)},0)}unmount(){if(this.editorView){this.editorState=this.editorView.state;const n=this.editorView.dom;n?.editor&&delete n.editor,this.editorView.destroy()}if(this.editorView=null,this.isInitialized=!1,this.css&&!document.querySelectorAll(`.${this.className}`).length)try{typeof this.css.remove=="function"?this.css.remove():this.css.parentNode&&this.css.parentNode.removeChild(this.css)}catch(n){console.warn("Failed to remove CSS element:",n)}this.css=null,this.emit("unmount",{editor:this})}get storage(){return this.extensionStorage}get commands(){return this.commandManager.commands}chain(){return this.commandManager?this.commandManager.chain():$t.createFakeChain()}can(){return this.commandManager?this.commandManager.can():$t.createFallbackCan()}injectCSS(){this.options.injectCSS&&typeof document<"u"&&(this.css=Om(tg,this.options.injectNonce))}setOptions(n={}){this.options={...this.options,...n},!(!this.editorView||!this.state||this.isDestroyed)&&(this.options.editorProps&&this.view.setProps({...this.options.editorProps,attributes:this.getEditorViewAttributes()}),this.view.updateState(this.state))}setEditable(n,e=!0){this.setOptions({editable:n}),e&&this.emit("update",{editor:this,transaction:this.state.tr,appendedTransactions:[]})}get isEditable(){return this.options.editable&&this.view&&this.view.editable}get view(){return this.editorView?this.editorView:new Proxy({state:this.editorState,updateState:n=>{this.editorState=n},dispatch:n=>{this.dispatchTransaction(n)},composing:!1,dragging:null,editable:!0,isDestroyed:!1},{get:(n,e)=>{if(this.editorView)return this.editorView[e];if(e==="state")return this.editorState;if(e in n)return Reflect.get(n,e);throw new Error(`[tiptap error]: The editor view is not available. Cannot access view['${e}']. The editor may not be mounted yet.`)}})}get state(){return this.editorView&&(this.editorState=this.view.state),this.editorState}registerPlugin(n,e){const t=Ui(e)?e(n,[...this.state.plugins]):[...this.state.plugins,n],r=this.state.reconfigure({plugins:t});return this.view.updateState(r),r}unregisterPlugin(n){if(this.isDestroyed)return;const e=this.state.plugins;let t=e;if([].concat(n).forEach(i=>{const s=typeof i=="string"?`${i}$`:i.key;t=t.filter(o=>!o.key.startsWith(s))}),e.length===t.length)return;const r=this.state.reconfigure({plugins:t});return this.view.updateState(r),r}createExtensionManager(){var n,e;const t=[...this.options.enableCoreExtensions?[Um,jm.configure({blockSeparator:(n=this.options.coreExtensionOptions)===null||n===void 0||(n=n.clipboardTextSerializer)===null||n===void 0?void 0:n.blockSeparator}),Wm,Jm,Gm,Xm.configure({value:(e=this.options.coreExtensionOptions)===null||e===void 0||(e=e.tabindex)===null||e===void 0?void 0:e.value}),_m,Ym,Km,Qm.configure({direction:this.options.textDirection})].filter(r=>typeof this.options.enableCoreExtensions=="object"?this.options.enableCoreExtensions[r.name]!==!1:!0):[],...this.options.extensions].filter(r=>["extension","node","mark"].includes(r?.type));this.extensionManager=new Xr(t,this)}createCommandManager(){this.commandManager=new $t({editor:this})}createSchema(){this.schema=this.extensionManager.schema}createDoc(){let n;try{n=_i(this.options.content,this.schema,this.options.parseOptions,{errorOnInvalidContent:this.options.enableContentCheck})}catch(e){if(!(e instanceof Error)||!["[tiptap error]: Invalid JSON content","[tiptap error]: Invalid HTML content"].includes(e.message))throw e;const t=_i(this.options.content,this.schema,this.options.parseOptions,{errorOnInvalidContent:!1});return this.editorState=Be.create({doc:t,schema:this.schema,selection:Ki(t,this.options.autofocus)||void 0}),this.emit("contentError",{editor:this,error:e,disableCollaboration:()=>{"collaboration"in this.storage&&typeof this.storage.collaboration=="object"&&this.storage.collaboration&&(this.storage.collaboration.isDisabled=!0),this.options.extensions=this.options.extensions.filter(r=>r.name!=="collaboration"),this.createExtensionManager()}}),this.editorState.doc}return n}getEditorViewAttributes(){var n;const e=(n=this.options.editorProps)===null||n===void 0?void 0:n.attributes;return Ui(e)?t=>({role:"textbox",...e(t)}):{role:"textbox",...e}}createView(n){const{editorProps:e,enableExtensionDispatchTransaction:t}=this.options,r=e.dispatchTransaction||this.dispatchTransaction.bind(this),i=t?this.extensionManager.dispatchTransaction(r):r,s=e.transformPastedHTML,o=this.extensionManager.transformPastedHTML(s);this.editorView=new ec(n,{...e,attributes:this.getEditorViewAttributes(),dispatchTransaction:i,transformPastedHTML:o,state:this.editorState,markViews:this.extensionManager.markViews,nodeViews:this.extensionManager.nodeViews});const l=this.state.reconfigure({plugins:this.extensionManager.plugins});this.view.updateState(l),this.prependClass(),this.injectCSS();const a=this.view.dom;a.editor=this}createNodeViews(){this.view.isDestroyed||this.view.setProps({markViews:this.extensionManager.markViews,nodeViews:this.extensionManager.nodeViews})}prependClass(){this.view.dom.className=`${this.className} ${this.view.dom.className}`}captureTransaction(n){this.isCapturingTransaction=!0,n(),this.isCapturingTransaction=!1;const e=this.capturedTransaction;return this.capturedTransaction=null,e}dispatchTransaction(n){if(this.view.isDestroyed)return;if(this.isCapturingTransaction){if(!this.capturedTransaction){this.capturedTransaction=n;return}n.steps.forEach(c=>{var u;return(u=this.capturedTransaction)===null||u===void 0?void 0:u.step(c)});return}const{state:e,transactions:t}=this.state.applyTransaction(n),r=!this.state.selection.eq(e.selection),i=t.includes(n),s=this.state;if(this.emit("beforeTransaction",{editor:this,transaction:n,nextState:e}),!i)return;this.view.updateState(e),this.emit("transaction",{editor:this,transaction:n,appendedTransactions:t.slice(1)}),r&&this.emit("selectionUpdate",{editor:this,transaction:n});const o=t.findLast(c=>c.getMeta("focus")||c.getMeta("blur")),l=o?.getMeta("focus"),a=o?.getMeta("blur");l&&this.emit("focus",{editor:this,event:l.event,transaction:o}),a&&this.emit("blur",{editor:this,event:a.event,transaction:o}),!(n.getMeta("preventUpdate")||!t.some(c=>c.docChanged)||s.doc.eq(e.doc))&&this.emit("update",{editor:this,transaction:n,appendedTransactions:t.slice(1)})}getAttributes(n){return Cc(this.state,n)}isActive(n,e){const t=typeof n=="string"?n:null,r=typeof n=="string"?e:n;return Fp(this.state,t,r)}getJSON(){return this.state.doc.toJSON()}getHTML(){return Es(this.state.doc.content,this.schema)}getText(n){const{blockSeparator:e=` +}`;var zy=class extends Jg{constructor(n={}){super(),this.css=null,this.className="tiptap",this.editorView=null,this.isFocused=!1,this.destroyed=!1,this.isInitialized=!1,this.extensionStorage={},this.instanceId=Math.random().toString(36).slice(2,9),this.hasWarnedStaleDecorationRead=!1,this.options={element:typeof document<"u"?document.createElement("div"):null,content:"",injectCSS:!0,injectNonce:void 0,extensions:[],autofocus:!1,editable:!0,textDirection:void 0,editorProps:{},parseOptions:{},coreExtensionOptions:{},enableInputRules:!0,enablePasteRules:!0,enableCoreExtensions:!0,enableContentCheck:!1,emitContentError:!1,onBeforeCreate:()=>null,onCreate:()=>null,onMount:()=>null,onUnmount:()=>null,onUpdate:()=>null,onSelectionUpdate:()=>null,onTransaction:()=>null,onFocus:()=>null,onBlur:()=>null,onDestroy:()=>null,onContentError:({error:t})=>{throw t},onPaste:()=>null,onDrop:()=>null,onDelete:()=>null,enableExtensionDispatchTransaction:!0},this.isCapturingTransaction=!1,this.capturedTransaction=null,this.utils={getUpdatedPosition:Sg,createMappablePosition:Cg},this.setOptions(n),this.createExtensionManager(),this.createCommandManager(),this.createSchema(),this.on("beforeCreate",this.options.onBeforeCreate),this.emit("beforeCreate",{editor:this}),this.on("mount",this.options.onMount),this.on("unmount",this.options.onUnmount),this.on("contentError",this.options.onContentError),this.on("create",this.options.onCreate),this.on("update",this.options.onUpdate),this.on("selectionUpdate",this.options.onSelectionUpdate),this.on("transaction",this.options.onTransaction),this.on("focus",this.options.onFocus),this.on("blur",this.options.onBlur),this.on("destroy",this.options.onDestroy),this.on("drop",({event:t,slice:r,moved:i})=>this.options.onDrop(t,r,i)),this.on("paste",({event:t,slice:r})=>this.options.onPaste(t,r)),this.on("delete",this.options.onDelete);const e=this.createDoc();if(!this.editorState){const t=ws(e,this.options.autofocus);this.editorState=je.create({doc:e,schema:this.schema,selection:t||void 0})}Iy(this.schema),this.options.element&&this.mount(this.options.element)}mount(n){if(typeof document>"u")throw new Error("[tiptap error]: The editor cannot be mounted because there is no 'document' defined in this environment.");this.createView(n),this.emit("mount",{editor:this}),this.css&&!document.head.contains(this.css)&&document.head.appendChild(this.css),window.setTimeout(()=>{this.isDestroyed||(this.options.autofocus!==!1&&this.options.autofocus!==null&&this.commands.focus(this.options.autofocus),this.emit("create",{editor:this}),this.isInitialized=!0)},0)}unmount(){if(this.editorView){this.editorState=this.editorView.state;const n=this.editorView.dom;n?.editor&&delete n.editor,this.editorView.destroy()}if(this.editorView=null,this.isInitialized=!1,this.css&&!document.querySelectorAll(`.${this.className}`).length)try{typeof this.css.remove=="function"?this.css.remove():this.css.parentNode&&this.css.parentNode.removeChild(this.css)}catch(n){console.warn("Failed to remove CSS element:",n)}this.css=null,this.emit("unmount",{editor:this})}get storage(){return this.extensionStorage}get commands(){return this.commandManager.commands}chain(){return this.commandManager?this.commandManager.chain():Yt.createFakeChain()}can(){return this.commandManager?this.commandManager.can():Yt.createFallbackCan()}injectCSS(){this.options.injectCSS&&typeof document<"u"&&(this.css=ay(Py,this.options.injectNonce))}setOptions(n={}){this.options={...this.options,...n},!(!this.editorView||!this.state||this.isDestroyed)&&(this.options.editorProps&&this.view.setProps({...this.options.editorProps,attributes:this.getEditorViewAttributes()}),this.view.updateState(this.state))}setEditable(n,e=!0){this.setOptions({editable:n}),e&&this.emit("update",{editor:this,transaction:this.state.tr,appendedTransactions:[]})}get isEditable(){return this.options.editable&&this.view&&this.view.editable}get view(){return this.editorView?this.editorView:new Proxy({state:this.editorState,updateState:n=>{this.editorState=n},dispatch:n=>{this.dispatchTransaction(n)},composing:!1,dragging:null,editable:!0,isDestroyed:!1},{get:(n,e)=>{if(this.editorView)return this.editorView[e];if(e==="state")return this.editorState;if(e in n)return Reflect.get(n,e);throw new Error(`[tiptap error]: The editor view is not available. Cannot access view['${e}']. The editor may not be mounted yet.`)}})}get state(){return this.editorView&&(this.editorState=this.view.state),this.editorState}registerPlugin(n,e){const t=Cs(e)?e(n,[...this.state.plugins]):[...this.state.plugins,n],r=this.state.reconfigure({plugins:t});return this.view.updateState(r),r}unregisterPlugin(n){if(this.isDestroyed)return;const e=this.state.plugins;let t=e;if([].concat(n).forEach(i=>{const s=typeof i=="string"?`${i}$`:i.key;t=t.filter(o=>!o.key.startsWith(s))}),e.length===t.length)return;const r=this.state.reconfigure({plugins:t});return this.view.updateState(r),r}createExtensionManager(){var n,e;const t=[...this.options.enableCoreExtensions?[Ty,Cy.configure({blockSeparator:(n=this.options.coreExtensionOptions)===null||n===void 0||(n=n.clipboardTextSerializer)===null||n===void 0?void 0:n.blockSeparator}),xy,Ay,Ny,Ry.configure({value:(e=this.options.coreExtensionOptions)===null||e===void 0||(e=e.tabindex)===null||e===void 0?void 0:e.value}),My,Oy,vy,Dy.configure({direction:this.options.textDirection})].filter(r=>typeof this.options.enableCoreExtensions=="object"?this.options.enableCoreExtensions[r.name]!==!1:!0):[],...this.options.extensions].filter(r=>["extension","node","mark"].includes(r?.type));this.extensionManager=new Si(t,this)}createCommandManager(){this.commandManager=new Yt({editor:this})}createSchema(){this.schema=this.extensionManager.schema}createDoc(){let n;try{n=Ss(this.options.content,this.schema,this.options.parseOptions,{errorOnInvalidContent:this.options.enableContentCheck})}catch(e){if(!(e instanceof Error)||!["[tiptap error]: Invalid JSON content","[tiptap error]: Invalid HTML content"].includes(e.message))throw e;const t=Ss(this.options.content,this.schema,this.options.parseOptions,{errorOnInvalidContent:!1});return this.editorState=je.create({doc:t,schema:this.schema,selection:ws(t,this.options.autofocus)||void 0}),this.emit("contentError",{editor:this,error:e,disableCollaboration:()=>{"collaboration"in this.storage&&typeof this.storage.collaboration=="object"&&this.storage.collaboration&&(this.storage.collaboration.isDisabled=!0),this.options.extensions=this.options.extensions.filter(r=>r.name!=="collaboration"),this.createExtensionManager()}}),this.editorState.doc}return n}getEditorViewAttributes(){var n;const e=(n=this.options.editorProps)===null||n===void 0?void 0:n.attributes;return Cs(e)?t=>({role:"textbox",...e(t)}):{role:"textbox",...e}}createView(n){const{editorProps:e,enableExtensionDispatchTransaction:t}=this.options,r=e.dispatchTransaction||this.dispatchTransaction.bind(this),i=t?this.extensionManager.dispatchTransaction(r):r,s=e.transformPastedHTML,o=this.extensionManager.transformPastedHTML(s);this.editorView=new ou(n,{...e,attributes:this.getEditorViewAttributes(),dispatchTransaction:i,transformPastedHTML:o,state:this.editorState,markViews:this.extensionManager.markViews,nodeViews:this.extensionManager.nodeViews});const l=this.state.reconfigure({plugins:this.extensionManager.plugins});this.view.updateState(l),this.prependClass(),this.injectCSS();const a=this.view.dom;a.editor=this}createNodeViews(){this.view.isDestroyed||this.view.setProps({markViews:this.extensionManager.markViews,nodeViews:this.extensionManager.nodeViews})}prependClass(){this.view.dom.className=`${this.className} ${this.view.dom.className}`}captureTransaction(n){this.isCapturingTransaction=!0,n(),this.isCapturingTransaction=!1;const e=this.capturedTransaction;return this.capturedTransaction=null,e}dispatchTransaction(n){if(this.view.isDestroyed)return;if(this.isCapturingTransaction){if(!this.capturedTransaction){this.capturedTransaction=n;return}n.steps.forEach(c=>{var u;return(u=this.capturedTransaction)===null||u===void 0?void 0:u.step(c)});return}const{state:e,transactions:t}=this.state.applyTransaction(n),r=!this.state.selection.eq(e.selection),i=t.includes(n),s=this.state;if(this.emit("beforeTransaction",{editor:this,transaction:n,nextState:e}),!i)return;this.view.updateState(e),this.emit("transaction",{editor:this,transaction:n,appendedTransactions:t.slice(1)}),r&&this.emit("selectionUpdate",{editor:this,transaction:n});const o=t.findLast(c=>c.getMeta("focus")||c.getMeta("blur")),l=o?.getMeta("focus"),a=o?.getMeta("blur");l&&this.emit("focus",{editor:this,event:l.event,transaction:o}),a&&this.emit("blur",{editor:this,event:a.event,transaction:o}),!(n.getMeta("preventUpdate")||!t.some(c=>c.docChanged)||s.doc.eq(e.doc))&&this.emit("update",{editor:this,transaction:n,appendedTransactions:t.slice(1)})}getAttributes(n){return Au(this.state,n)}isActive(n,e){const t=typeof n=="string"?n:null,r=typeof n=="string"?e:n;return bg(this.state,t,r)}getJSON(){return this.state.doc.toJSON()}getHTML(){return fo(this.state.doc.content,this.schema)}getText(n){const{blockSeparator:e=` -`,textSerializers:t={}}=n||{};return Ip(this.state.doc,{blockSeparator:e,textSerializers:{...wc(this.schema),...t}})}get isEmpty(){return Dn(this.state.doc)}destroy(){this.destroyed||(this.destroyed=!0,this.emit("destroy"),this.unmount(),this.removeAllListeners(),this.extensionManager.destroy(),this.extensionManager=null,this.schema=null,this.commandManager=null,this.extensionStorage={})}get isDestroyed(){var n,e;return(n=(e=this.editorView)===null||e===void 0?void 0:e.isDestroyed)!==null&&n!==void 0?n:!0}$node(n,e){var t;return((t=this.$doc)===null||t===void 0?void 0:t.querySelector(n,e))||null}$nodes(n,e){var t;return((t=this.$doc)===null||t===void 0?void 0:t.querySelectorAll(n,e))||null}$pos(n){const e=this.state.doc.resolve(n),t=n>0&&e.nodeAfter&&!e.nodeAfter.isText&&e.nodeAfter.isAtom?e.nodeAfter:null;return new eg(e,this,!1,t)}get $doc(){return this.$pos(0)}};function vt(n){return new In({find:n.find,handler:({state:e,range:t,match:r})=>{const i=L(n.getAttributes,void 0,r);if(i===!1||i===null)return null;const{tr:s}=e,o=r[r.length-1],l=r[0];if(o){const a=l.search(/\S/),c=t.from+l.indexOf(o),u=c+o.length;if(Yr(t.from,t.to,e.doc).filter(f=>f.mark.type.excluded.find(h=>h===n.type&&h!==f.mark.type)).filter(f=>f.to>c).length)return null;ut.from&&s.delete(t.from+a,c);const d=t.from+a+o.length;s.addMark(t.from+a,d,n.type.create(i||{})),s.removeStoredMark(n.type)}},undoable:n.undoable})}function rg(n){return new In({find:n.find,handler:({state:e,range:t,match:r})=>{const i=L(n.getAttributes,void 0,r)||{},{tr:s}=e,o=t.from;let l=t.to;const a=n.type.create(i);if(r[1]){let c=o+r[0].lastIndexOf(r[1]);c>l?c=l:l=c+r[1].length;const u=r[0][r[0].length-1];s.insertText(u,o+r[0].length-1),s.replaceWith(c,l,a)}else if(r[0]){const c=n.type.isInline?o:o-1;s.insert(c,n.type.create(i)).delete(s.mapping.map(o),s.mapping.map(l))}s.scrollIntoView()},undoable:n.undoable})}function Ji(n){return new In({find:n.find,handler:({state:e,range:t,match:r})=>{const i=e.doc.resolve(t.from),s=L(n.getAttributes,void 0,r)||{};if(!i.node(-1).canReplaceWith(i.index(-1),i.indexAfter(-1),n.type))return null;e.tr.delete(t.from,t.to).setBlockType(t.from,t.from,n.type,s)},undoable:n.undoable})}function _t(n){return new In({find:n.find,handler:({state:e,range:t,match:r,chain:i})=>{const s=L(n.getAttributes,void 0,r)||{},o=e.tr.delete(t.from,t.to),l=o.doc.resolve(t.from).blockRange(),a=l&&as(l,n.type,s);if(!a)return null;if(o.wrap(l,a),n.keepMarks&&n.editor){const{selection:u,storedMarks:d}=e,{splittableMarks:f}=n.editor.extensionManager,h=d||u.$to.parentOffset&&u.$from.marks();if(h){const p=h.filter(m=>f.includes(m.type.name));o.ensureMarks(p)}}if(n.keepAttributes){const u=n.type.name==="bulletList"||n.type.name==="orderedList"?"listItem":"taskList";i().updateAttributes(u,s).run()}const c=o.doc.resolve(t.from-1).nodeBefore;c&&c.type===n.type&&ot(o.doc,t.from-1)&&(!n.joinPredicate||n.joinPredicate(r,c))&&o.join(t.from-1)},undoable:n.undoable})}var pe=class zc extends Ts{constructor(...e){super(...e),this.type="node"}static create(e={}){const t=typeof e=="function"?e():e;return new zc(t)}configure(e){return super.configure(e)}extend(e){const t=typeof e=="function"?e():e;return super.extend(t)}};function it(n){return new Pc({find:n.find,handler:({state:e,range:t,match:r,pasteEvent:i})=>{const s=L(n.getAttributes,void 0,r,i);if(s===!1||s===null)return null;const{tr:o}=e,l=r[r.length-1],a=r[0];let c=t.to;if(l){const u=a.search(/\S/),d=t.from+a.indexOf(l),f=d+l.length;if(Yr(t.from,t.to,e.doc).filter(h=>h.mark.type.excluded.find(p=>p===n.type&&p!==h.mark.type)).filter(h=>h.to>d).length)return null;ft.from&&o.delete(t.from+u,d),c=t.from+u+l.length,o.addMark(t.from+u,c,n.type.create(s||{})),r.index!==void 0&&r.input!==void 0&&r.index+r[0].length>=r.input.length||o.removeStoredMark(n.type)}}})}const $c=new WeakSet,Fc=new WeakSet;function ct(n){const e=n;return $c.add(e),e}function Gi(n){return Array.isArray(n)&&$c.has(n)}function Vc(n){return n.flatMap(e=>e==null?[]:Array.isArray(e)&&Fc.has(e)&&!Gi(e)?Vc(e):[e])}function ig(n,e){if(n==="slot")return 0;if(n instanceof Function){const i=n(e);return Array.isArray(i)&&!Gi(i)&&!Fc.has(i)?ct(i):i}const{children:t,...r}=e??{};if(n==="svg")throw new Error("SVG elements are not supported in the JSX syntax, use the array syntax instead");if(Array.isArray(t)){if(Gi(t))return ct([n,r,t]);if(t.length===0)return ct([n,r]);const i=Vc(t);return i.length===0?ct([n,r]):ct([n,r,...i])}return t!=null?ct([n,r,t]):ct([n,r])}const cr=(n,e)=>ig(n,e),sg=(n,e)=>{var t;const{state:r}=n,{selection:i}=r;if(!i.empty)return!1;const{$from:s}=i;if(s.parentOffset!==0)return!1;const o=s.depth-1;if(o<0)return!1;const l=s.node(o),a=s.index(o);if(a===0)return!1;if(l.type===e)return n.commands.lift(e.name);const c=l.child(a-1);if(c.type!==e||!(!((t=c.lastChild)===null||t===void 0)&&t.isTextblock))return!1;const u=s.before()-1-1;return n.commands.command(({tr:d,dispatch:f})=>{if(!f)return!0;const h=s.parent.content,p=new w(h,0,0);return d.replace(u,s.after(),p),d.setSelection(T.create(d.doc,u+h.size)),d.scrollIntoView(),f(d),!0})},og=/^\s*>\s$/,lg=pe.create({name:"blockquote",addOptions(){return{HTMLAttributes:{}}},content:"block+",group:"block",defining:!0,parseHTML(){return[{tag:"blockquote"}]},renderHTML({HTMLAttributes:n}){return cr("blockquote",{...J(this.options.HTMLAttributes,n),children:cr("slot",{})})},parseMarkdown:(n,e)=>{var t;const r=(t=e.parseBlockChildren)!==null&&t!==void 0?t:e.parseChildren;return e.createNode("blockquote",void 0,r(n.tokens||[]))},renderMarkdown:(n,e)=>{if(!n.content)return"";const t=">",r=[];return n.content.forEach((i,s)=>{var o,l;const a=((o=(l=e.renderChild)===null||l===void 0?void 0:l.call(e,i,s))!==null&&o!==void 0?o:e.renderChildren([i])).split(` +`,textSerializers:t={}}=n||{};return dg(this.state.doc,{blockSeparator:e,textSerializers:{...Eu(this.schema),...t}})}get isEmpty(){return Jn(this.state.doc)}destroy(){this.destroyed||(this.destroyed=!0,this.emit("destroy"),this.unmount(),this.removeAllListeners(),this.extensionManager.destroy(),this.extensionManager=null,this.schema=null,this.commandManager=null,this.extensionStorage={})}get isDestroyed(){var n,e;return(n=(e=this.editorView)===null||e===void 0?void 0:e.isDestroyed)!==null&&n!==void 0?n:!0}$node(n,e){var t;return((t=this.$doc)===null||t===void 0?void 0:t.querySelector(n,e))||null}$nodes(n,e){var t;return((t=this.$doc)===null||t===void 0?void 0:t.querySelectorAll(n,e))||null}$pos(n){const e=this.state.doc.resolve(n),t=n>0&&e.nodeAfter&&!e.nodeAfter.isText&&e.nodeAfter.isAtom?e.nodeAfter:null;return new Ly(e,this,!1,t)}get $doc(){return this.$pos(0)}};function zt(n){return new Gn({find:n.find,handler:({state:e,range:t,match:r})=>{const i=L(n.getAttributes,void 0,r);if(i===!1||i===null)return null;const{tr:s}=e,o=r[r.length-1],l=r[0];if(o){const a=l.search(/\S/),c=t.from+l.indexOf(o),u=c+o.length;if(wi(t.from,t.to,e.doc).filter(f=>f.mark.type.excluded.find(h=>h===n.type&&h!==f.mark.type)).filter(f=>f.to>c).length)return null;ut.from&&s.delete(t.from+a,c);const d=t.from+a+o.length;s.addMark(t.from+a,d,n.type.create(i||{})),s.removeStoredMark(n.type)}},undoable:n.undoable})}function Wu(n){return new Gn({find:n.find,handler:({state:e,range:t,match:r})=>{const i=L(n.getAttributes,void 0,r)||{},{tr:s}=e,o=t.from;let l=t.to;const a=n.type.create(i);if(r[1]){let c=o+r[0].lastIndexOf(r[1]);c>l?c=l:l=c+r[1].length;const u=r[0][r[0].length-1];s.insertText(u,o+r[0].length-1),s.replaceWith(c,l,a)}else if(r[0]){const c=n.type.isInline?o:o-1;s.insert(c,n.type.create(i)).delete(s.mapping.map(o),s.mapping.map(l))}s.scrollIntoView()},undoable:n.undoable})}function vs(n){return new Gn({find:n.find,handler:({state:e,range:t,match:r})=>{const i=e.doc.resolve(t.from),s=L(n.getAttributes,void 0,r)||{};if(!i.node(-1).canReplaceWith(i.index(-1),i.indexAfter(-1),n.type))return null;e.tr.delete(t.from,t.to).setBlockType(t.from,t.from,n.type,s)},undoable:n.undoable})}function sn(n){return new Gn({find:n.find,handler:({state:e,range:t,match:r,chain:i})=>{const s=L(n.getAttributes,void 0,r)||{},o=e.tr.delete(t.from,t.to),l=o.doc.resolve(t.from).blockRange(),a=l&&Us(l,n.type,s);if(!a)return null;if(o.wrap(l,a),n.keepMarks&&n.editor){const{selection:u,storedMarks:d}=e,{splittableMarks:f}=n.editor.extensionManager,h=d||u.$to.parentOffset&&u.$from.marks();if(h){const p=h.filter(m=>f.includes(m.type.name));o.ensureMarks(p)}}if(n.keepAttributes){const u=n.type.name==="bulletList"||n.type.name==="orderedList"?"listItem":"taskList";i().updateAttributes(u,s).run()}const c=o.doc.resolve(t.from-1).nodeBefore;c&&c.type===n.type&&pt(o.doc,t.from-1)&&(!n.joinPredicate||n.joinPredicate(r,c))&&o.join(t.from-1)},undoable:n.undoable})}const By=n=>"touches"in n;var $y=class{constructor(n){var e,t,r,i,s,o;this.directions=["bottom-left","bottom-right","top-left","top-right"],this.minSize={height:8,width:8},this.preserveAspectRatio=!1,this.classNames={container:"",wrapper:"",handle:"",resizing:""},this.initialWidth=0,this.initialHeight=0,this.aspectRatio=1,this.isResizing=!1,this.activeHandle=null,this.startX=0,this.startY=0,this.startWidth=0,this.startHeight=0,this.isShiftKeyPressed=!1,this.lastEditableState=void 0,this.handleMap=new Map,this.handleMouseMove=l=>{if(!this.isResizing||!this.activeHandle)return;const a=l.clientX-this.startX,c=l.clientY-this.startY;this.handleResize(a,c)},this.handleTouchMove=l=>{if(!this.isResizing||!this.activeHandle)return;const a=l.touches[0];if(!a)return;const c=a.clientX-this.startX,u=a.clientY-this.startY;this.handleResize(c,u)},this.handleMouseUp=()=>{if(!this.isResizing)return;const l=this.element.offsetWidth,a=this.element.offsetHeight;this.onCommit(l,a),this.isResizing=!1,this.activeHandle=null,this.container.dataset.resizeState="false",this.classNames.resizing&&this.container.classList.remove(this.classNames.resizing),document.removeEventListener("mousemove",this.handleMouseMove),document.removeEventListener("mouseup",this.handleMouseUp),document.removeEventListener("keydown",this.handleKeyDown),document.removeEventListener("keyup",this.handleKeyUp)},this.handleKeyDown=l=>{l.key==="Shift"&&(this.isShiftKeyPressed=!0)},this.handleKeyUp=l=>{l.key==="Shift"&&(this.isShiftKeyPressed=!1)},this.node=n.node,this.editor=n.editor,this.element=n.element,this.element.draggable=!1,this.contentElement=n.contentElement,this.getPos=n.getPos,this.onResize=n.onResize,this.onCommit=n.onCommit,this.onUpdate=n.onUpdate,!((e=n.options)===null||e===void 0)&&e.min&&(this.minSize={...this.minSize,...n.options.min}),!((t=n.options)===null||t===void 0)&&t.max&&(this.maxSize=n.options.max),!(n==null||(r=n.options)===null||r===void 0)&&r.directions&&(this.directions=n.options.directions),!((i=n.options)===null||i===void 0)&&i.preserveAspectRatio&&(this.preserveAspectRatio=n.options.preserveAspectRatio),!((s=n.options)===null||s===void 0)&&s.className&&(this.classNames={container:n.options.className.container||"",wrapper:n.options.className.wrapper||"",handle:n.options.className.handle||"",resizing:n.options.className.resizing||""}),!((o=n.options)===null||o===void 0)&&o.createCustomHandle&&(this.createCustomHandle=n.options.createCustomHandle),this.wrapper=this.createWrapper(),this.container=this.createContainer(),this.applyInitialSize(),this.attachHandles(),this.editor.on("update",this.handleEditorUpdate.bind(this))}get dom(){return this.container}get contentDOM(){var n;return(n=this.contentElement)!==null&&n!==void 0?n:null}handleEditorUpdate(){const n=this.editor.isEditable;n!==this.lastEditableState&&(this.lastEditableState=n,n?n&&this.handleMap.size===0&&this.attachHandles():this.removeHandles())}update(n,e,t){return n.type!==this.node.type?!1:(this.node=n,this.onUpdate?this.onUpdate(n,e,t):!0)}destroy(){this.isResizing&&(this.container.dataset.resizeState="false",this.classNames.resizing&&this.container.classList.remove(this.classNames.resizing),document.removeEventListener("mousemove",this.handleMouseMove),document.removeEventListener("mouseup",this.handleMouseUp),document.removeEventListener("keydown",this.handleKeyDown),document.removeEventListener("keyup",this.handleKeyUp),this.isResizing=!1,this.activeHandle=null),this.editor.off("update",this.handleEditorUpdate.bind(this)),this.container.remove()}createContainer(){const n=document.createElement("div");return n.dataset.resizeContainer="",n.dataset.node=this.node.type.name,n.style.display=this.node.type.isInline?"inline-flex":"flex",this.classNames.container&&(n.className=this.classNames.container),n.appendChild(this.wrapper),n}createWrapper(){const n=document.createElement("div");return n.style.position="relative",n.style.display="block",n.dataset.resizeWrapper="",this.classNames.wrapper&&(n.className=this.classNames.wrapper),n.appendChild(this.element),n}createHandle(n){const e=document.createElement("div");return e.dataset.resizeHandle=n,e.style.position="absolute",this.classNames.handle&&(e.className=this.classNames.handle),e}positionHandle(n,e){const t=e.includes("top"),r=e.includes("bottom"),i=e.includes("left"),s=e.includes("right");t&&(n.style.top="0"),r&&(n.style.bottom="0"),i&&(n.style.left="0"),s&&(n.style.right="0"),(e==="top"||e==="bottom")&&(n.style.left="0",n.style.right="0"),(e==="left"||e==="right")&&(n.style.top="0",n.style.bottom="0")}attachHandles(){this.directions.forEach(n=>{let e;this.createCustomHandle?e=this.createCustomHandle(n):e=this.createHandle(n),e instanceof HTMLElement||(console.warn(`[ResizableNodeView] createCustomHandle("${n}") did not return an HTMLElement. Falling back to default handle.`),e=this.createHandle(n)),this.createCustomHandle||this.positionHandle(e,n),e.addEventListener("mousedown",t=>this.handleResizeStart(t,n)),e.addEventListener("touchstart",t=>this.handleResizeStart(t,n)),this.handleMap.set(n,e),this.wrapper.appendChild(e)})}removeHandles(){this.handleMap.forEach(n=>n.remove()),this.handleMap.clear()}applyInitialSize(){const n=this.node.attrs.width,e=this.node.attrs.height;n?(this.element.style.width=`${n}px`,this.initialWidth=n):this.initialWidth=this.element.offsetWidth,e?(this.element.style.height=`${e}px`,this.initialHeight=e):this.initialHeight=this.element.offsetHeight,this.initialWidth>0&&this.initialHeight>0&&(this.aspectRatio=this.initialWidth/this.initialHeight)}handleResizeStart(n,e){n.preventDefault(),n.stopPropagation(),this.isResizing=!0,this.activeHandle=e,By(n)?(this.startX=n.touches[0].clientX,this.startY=n.touches[0].clientY):(this.startX=n.clientX,this.startY=n.clientY),this.startWidth=this.element.offsetWidth,this.startHeight=this.element.offsetHeight,this.startWidth>0&&this.startHeight>0&&(this.aspectRatio=this.startWidth/this.startHeight),this.getPos(),this.container.dataset.resizeState="true",this.classNames.resizing&&this.container.classList.add(this.classNames.resizing),document.addEventListener("mousemove",this.handleMouseMove),document.addEventListener("touchmove",this.handleTouchMove),document.addEventListener("mouseup",this.handleMouseUp),document.addEventListener("keydown",this.handleKeyDown),document.addEventListener("keyup",this.handleKeyUp)}handleResize(n,e){if(!this.activeHandle)return;const t=this.preserveAspectRatio||this.isShiftKeyPressed,{width:r,height:i}=this.calculateNewDimensions(this.activeHandle,n,e),s=this.applyConstraints(r,i,t);this.element.style.width=`${s.width}px`,this.element.style.height=`${s.height}px`,this.onResize&&this.onResize(s.width,s.height)}calculateNewDimensions(n,e,t){let r=this.startWidth,i=this.startHeight;const s=n.includes("right"),o=n.includes("left"),l=n.includes("bottom"),a=n.includes("top");return s?r=this.startWidth+e:o&&(r=this.startWidth-e),l?i=this.startHeight+t:a&&(i=this.startHeight-t),(n==="right"||n==="left")&&(r=this.startWidth+(s?e:-e)),(n==="top"||n==="bottom")&&(i=this.startHeight+(l?t:-t)),this.preserveAspectRatio||this.isShiftKeyPressed?this.applyAspectRatio(r,i,n):{width:r,height:i}}applyConstraints(n,e,t){var r,i;if(!t){var s,o;let c=Math.max(this.minSize.width,n),u=Math.max(this.minSize.height,e);return!((s=this.maxSize)===null||s===void 0)&&s.width&&(c=Math.min(this.maxSize.width,c)),!((o=this.maxSize)===null||o===void 0)&&o.height&&(u=Math.min(this.maxSize.height,u)),{width:c,height:u}}let l=n,a=e;return lthis.maxSize.width&&(l=this.maxSize.width,a=l/this.aspectRatio),!((i=this.maxSize)===null||i===void 0)&&i.height&&a>this.maxSize.height&&(a=this.maxSize.height,l=a*this.aspectRatio),{width:l,height:a}}applyAspectRatio(n,e,t){const r=t==="left"||t==="right",i=t==="top"||t==="bottom";return r?{width:n,height:n/this.aspectRatio}:i?{width:e*this.aspectRatio,height:e}:{width:n,height:n/this.aspectRatio}}},_=class ju extends ho{constructor(...e){super(...e),this.type="node"}static create(e={}){const t=typeof e=="function"?e():e;return new ju(t)}configure(e){return super.configure(e)}extend(e){const t=typeof e=="function"?e():e;return super.extend(t)}};function ft(n){return new Fu({find:n.find,handler:({state:e,range:t,match:r,pasteEvent:i})=>{const s=L(n.getAttributes,void 0,r,i);if(s===!1||s===null)return null;const{tr:o}=e,l=r[r.length-1],a=r[0];let c=t.to;if(l){const u=a.search(/\S/),d=t.from+a.indexOf(l),f=d+l.length;if(wi(t.from,t.to,e.doc).filter(h=>h.mark.type.excluded.find(p=>p===n.type&&p!==h.mark.type)).filter(h=>h.to>d).length)return null;ft.from&&o.delete(t.from+u,d),c=t.from+u+l.length,o.addMark(t.from+u,c,n.type.create(s||{})),r.index!==void 0&&r.input!==void 0&&r.index+r[0].length>=r.input.length||o.removeStoredMark(n.type)}}})}const Hy=new Set(["youtube.com","www.youtube.com","m.youtube.com","music.youtube.com","youtube-nocookie.com","www.youtube-nocookie.com"]),Rt={youtube:{name:"YouTube",idPattern:/^[A-Za-z0-9_-]{11}$/,idFromUrl(n){const e=n.hostname.toLowerCase();if(e==="youtu.be")return n.pathname.split("/")[1]??null;if(!Hy.has(e))return null;if(n.pathname==="/watch")return n.searchParams.get("v");const t=/^\/(?:shorts|embed)\/([^/]+)\/?$/.exec(n.pathname);return t?t[1]:null}}};function _i(n){return Object.prototype.hasOwnProperty.call(Rt,n)}function Fy(n){let e;try{e=new URL(n.trim())}catch{return null}if(e.protocol!=="https:"&&e.protocol!=="http:")return null;for(const t of Object.keys(Rt)){const r=Rt[t].idFromUrl(e);if(r&&Rt[t].idPattern.test(r))return{provider:t,id:r}}return null}const Vy=/(?:^|\s)(!\[(.+|:?)]\((\S+)(?:(?:\s+)["'](\S+)["'])?\))$/,Wy=_.create({name:"image",addOptions(){return{inline:!1,allowBase64:!1,HTMLAttributes:{},resize:!1}},inline(){return this.options.inline},group(){return this.options.inline?"inline":"block"},draggable:!0,addAttributes(){return{src:{default:null},alt:{default:null},title:{default:null},width:{default:null},height:{default:null}}},parseHTML(){return[{tag:this.options.allowBase64?"img[src]":'img[src]:not([src^="data:"])'}]},renderHTML({HTMLAttributes:n}){return["img",H(this.options.HTMLAttributes,n)]},parseMarkdown:(n,e)=>e.createNode("image",{src:n.href,title:n.title,alt:n.text}),renderMarkdown:n=>{var e,t,r,i,s,o;const l=(e=(t=n.attrs)===null||t===void 0?void 0:t.src)!==null&&e!==void 0?e:"",a=(r=(i=n.attrs)===null||i===void 0?void 0:i.alt)!==null&&r!==void 0?r:"",c=(s=(o=n.attrs)===null||o===void 0?void 0:o.title)!==null&&s!==void 0?s:"";return c?`![${a}](${l} "${c}")`:`![${a}](${l})`},addNodeView(){if(!this.options.resize||!this.options.resize.enabled||typeof document>"u")return null;const{directions:n,minWidth:e,minHeight:t,alwaysPreserveAspectRatio:r}=this.options.resize,i=new Set(["src","width","height"]);return({node:s,getPos:o,HTMLAttributes:l,editor:a})=>{const c=document.createElement("img");c.draggable=!1;const u=H(this.options.HTMLAttributes,l);Object.entries(u).forEach(([y,k])=>{if(k!=null)switch(y){case"src":case"width":case"height":break;default:c.setAttribute(y,k)}}),u.src!==null&&(c.src=u.src);let d={...l};const f=y=>{if(typeof y=="string"&&y!==""){c.getAttribute("src")!==y&&(c.src=y);return}c.hasAttribute("src")&&c.removeAttribute("src"),c.src!==""&&(c.src="")};f(l.src);const h=y=>{if(y.type!==s.type)return!1;const k=a.extensionManager.attributes.filter(C=>C.type===y.type.name),w=rn(y,k);return Object.keys(d).forEach(C=>{!i.has(C)&&!(C in w)&&c.removeAttribute(C)}),Object.entries(w).forEach(([C,O])=>{i.has(C)||(O!=null?c.setAttribute(C,O):c.removeAttribute(C))}),f(w.src),d=w,!0},p=new $y({element:c,editor:a,node:s,getPos:o,onResize:(y,k)=>{c.style.width=`${y}px`,c.style.height=`${k}px`},onCommit:(y,k)=>{const w=o();w!==void 0&&this.editor.chain().setNodeSelection(w).updateAttributes(this.name,{width:y,height:k}).run()},onUpdate:h,options:{directions:n,min:{width:e,height:t},preserveAspectRatio:r===!0}}),m=p.dom,g=()=>{m.style.visibility="",m.style.pointerEvents=""};return m.style.visibility="hidden",m.style.pointerEvents="none",c.complete&&c.naturalWidth>0?g():(c.onload=g,c.onerror=g),p}},addCommands(){return{setImage:n=>({commands:e})=>e.insertContent({type:this.name,attrs:n})}},addInputRules(){return[Wu({find:Vy,type:this.type,getAttributes:n=>{const[,,e,t,r]=n;return{src:t,alt:e,title:r}}})]}});var jy=Wy;let Ms,Ts;if(typeof WeakMap<"u"){let n=new WeakMap;Ms=e=>n.get(e),Ts=(e,t)=>(n.set(e,t),t)}else{const n=[];let t=0;Ms=r=>{for(let i=0;i(t==10&&(t=0),n[t++]=r,n[t++]=i)}var J=class{constructor(n,e,t,r){this.width=n,this.height=e,this.map=t,this.problems=r}findCell(n){for(let e=0;e=t){(s||(s=[])).push({type:"overlong_rowspan",pos:u,n:y-w});break}const C=i+w*e;for(let O=0;Or&&(s+=c.attrs.colspan)}}for(let o=0;o1&&(t=!0)}e==-1?e=s:e!=s&&(e=Math.max(e,s))}return e}function Ky(n,e,t){n.problems||(n.problems=[]);const r={};for(let i=0;i0;e--)if(n.node(e).type.spec.tableRole=="row")return n.node(0).resolve(n.before(e+1));return null}function Jy(n){for(let e=n.depth;e>0;e--){const t=n.node(e).type.spec.tableRole;if(t==="cell"||t==="header_cell")return n.node(e)}return null}function Ne(n){const e=n.selection.$head;for(let t=e.depth;t>0;t--)if(e.node(t).type.spec.tableRole=="row")return!0;return!1}function Ci(n){const e=n.selection;if("$anchorCell"in e&&e.$anchorCell)return e.$anchorCell.pos>e.$headCell.pos?e.$anchorCell:e.$headCell;if("node"in e&&e.node&&e.node.type.spec.tableRole=="cell")return e.$anchor;const t=Bt(e.$head)||Gy(e.$head);if(t)return t;throw new RangeError(`No cell found around position ${e.head}`)}function Gy(n){for(let e=n.nodeAfter,t=n.pos;e;e=e.firstChild,t++){const r=e.type.spec.tableRole;if(r=="cell"||r=="header_cell")return n.doc.resolve(t)}for(let e=n.nodeBefore,t=n.pos;e;e=e.lastChild,t--){const r=e.type.spec.tableRole;if(r=="cell"||r=="header_cell")return n.doc.resolve(t-e.nodeSize)}}function Es(n){return n.parent.type.spec.tableRole=="row"&&!!n.nodeAfter}function Yy(n){return n.node(0).resolve(n.pos+n.nodeAfter.nodeSize)}function po(n,e){return n.depth==e.depth&&n.pos>=e.start(-1)&&n.pos<=e.end(-1)}function _u(n,e,t){const r=n.node(-1),i=J.get(r),s=n.start(-1),o=i.nextCell(n.pos-s,e,t);return o==null?null:n.node(0).resolve(s+o)}function $t(n,e,t=1){const r={...n,colspan:n.colspan-t};return r.colwidth&&(r.colwidth=r.colwidth.slice(),r.colwidth.splice(e,t),r.colwidth.some(i=>i>0)||(r.colwidth=null)),r}function Uu(n,e,t=1){const r={...n,colspan:n.colspan+t};if(r.colwidth){r.colwidth=r.colwidth.slice();for(let i=0;iu!=t.pos-s);a.unshift(t.pos-s);const c=a.map(u=>{const d=r.nodeAt(u);if(!d)throw new RangeError(`No cell with offset ${u} found`);const f=s+u+1;return new ac(l.resolve(f),l.resolve(f+d.content.size))});super(c[0].$from,c[0].$to,c),this.$anchorCell=e,this.$headCell=t}map(e,t){const r=e.resolve(t.map(this.$anchorCell.pos)),i=e.resolve(t.map(this.$headCell.pos));if(Es(r)&&Es(i)&&po(r,i)){const s=this.$anchorCell.node(-1)!=r.node(-1);return s&&this.isRowSelection()?Fe.rowSelection(r,i):s&&this.isColSelection()?Fe.colSelection(r,i):new Fe(r,i)}return v.between(r,i)}content(){const e=this.$anchorCell.node(-1),t=J.get(e),r=this.$anchorCell.start(-1),i=t.rectBetween(this.$anchorCell.pos-r,this.$headCell.pos-r),s={},o=[];for(let a=i.top;a0||g>0){let y=p.attrs;if(m>0&&(y=$t(y,0,m)),g>0&&(y=$t(y,y.colspan-g,g)),h.lefti.bottom){const y={...p.attrs,rowspan:Math.min(h.bottom,i.bottom)-Math.max(h.top,i.top)};h.top0)return!1;const r=e+this.$anchorCell.nodeAfter.attrs.rowspan,i=t+this.$headCell.nodeAfter.attrs.rowspan;return Math.max(r,i)==this.$headCell.node(-1).childCount}static colSelection(e,t=e){const r=e.node(-1),i=J.get(r),s=e.start(-1),o=i.findCell(e.pos-s),l=i.findCell(t.pos-s),a=e.node(0);return o.top<=l.top?(o.top>0&&(e=a.resolve(s+i.map[o.left])),l.bottom0&&(t=a.resolve(s+i.map[l.left])),o.bottom0)return!1;const o=i+this.$anchorCell.nodeAfter.attrs.colspan,l=s+this.$headCell.nodeAfter.attrs.colspan;return Math.max(o,l)==t.width}eq(e){return e instanceof Fe&&e.$anchorCell.pos==this.$anchorCell.pos&&e.$headCell.pos==this.$headCell.pos}static rowSelection(e,t=e){const r=e.node(-1),i=J.get(r),s=e.start(-1),o=i.findCell(e.pos-s),l=i.findCell(t.pos-s),a=e.node(0);return o.left<=l.left?(o.left>0&&(e=a.resolve(s+i.map[o.top*i.width])),l.right0&&(t=a.resolve(s+i.map[l.top*i.width])),o.right{e.push(Q.node(r,r+t.nodeSize,{class:"selectedCell"}))}),I.create(n.doc,e)}function e0({$from:n,$to:e}){if(n.pos==e.pos||n.pos=0&&!(n.after(i+1)=0&&!(e.before(s+1)>e.start(s));s--,r--);return t==r&&/row|table/.test(n.node(i).type.spec.tableRole)}function t0({$from:n,$to:e}){let t,r;for(let i=n.depth;i>0;i--){const s=n.node(i);if(s.type.spec.tableRole==="cell"||s.type.spec.tableRole==="header_cell"){t=s;break}}for(let i=e.depth;i>0;i--){const s=e.node(i);if(s.type.spec.tableRole==="cell"||s.type.spec.tableRole==="header_cell"){r=s;break}}return t!==r&&e.parentOffset===0}function n0(n,e,t){const r=(e||n).selection,i=(e||n).doc;let s,o;if(r instanceof T&&(o=r.node.type.spec.tableRole)){if(o=="cell"||o=="header_cell")s=F.create(i,r.from);else if(o=="row"){const l=i.resolve(r.from+1);s=F.rowSelection(l,l)}else if(!t){const l=J.get(r.node),a=r.from+1,c=a+l.map[l.width*l.height-1];s=F.create(i,a+1,c)}}else r instanceof v&&e0(r)?s=v.create(i,r.from):r instanceof v&&t0(r)&&(s=v.create(i,r.$from.start(),r.$from.end()));return s&&(e||(e=n.tr)).setSelection(s),e}const r0=new W("fix-tables");function qu(n,e,t,r){const i=n.childCount,s=e.childCount;e:for(let o=0,l=0;o{i.type.spec.tableRole=="table"&&(t=i0(n,i,s,t))};return e?e.doc!=n.doc&&qu(e.doc,n.doc,0,r):n.doc.descendants(r),t}function i0(n,e,t,r){const i=J.get(e);if(!i.problems)return r;r||(r=n.tr);const s=[];for(let a=0;a0){let h="cell";u.firstChild&&(h=u.firstChild.type.spec.tableRole);const p=[];for(let g=0;g0?-1:0;Xy(e,r,i+s)&&(s=i==0||i==e.width?null:0);for(let o=0;o0&&i0&&e.map[l-1]==a||i0?-1:0;c0(e,r,i+l)&&(l=i==0||i==e.height?null:0);for(let c=0,u=e.width*i;c0&&i0&&d==e.map[u-e.width]){const f=t.nodeAt(d).attrs;n.setNodeMarkup(n.mapping.slice(l).map(d+r),null,{...f,rowspan:f.rowspan-1}),c+=f.colspan-1}else if(i0&&t[s]==t[s-1]||r.right0&&t[i]==t[i-n]||r.bottom0){const u=a+1+c.content.size,d=Kl(c)?a+1:u;s.replaceWith(d+r.tableStart,u+r.tableStart,l)}s.setSelection(new F(s.doc.resolve(a+r.tableStart))),e(s)}return!0}function Jl(n,e){const t=ce(n.schema);return m0(({node:r})=>t[r.type.spec.tableRole])(n,e)}function m0(n){return(e,t)=>{const r=e.selection;let i,s;if(r instanceof F){if(r.$anchorCell.pos!=r.$headCell.pos)return!1;i=r.$anchorCell.nodeAfter,s=r.$anchorCell.pos}else{var o;if(i=Jy(r.$from),!i)return!1;s=(o=Bt(r.$from))===null||o===void 0?void 0:o.pos}if(i==null||s==null||i.attrs.colspan==1&&i.attrs.rowspan==1)return!1;if(t){let l=i.attrs;const a=[],c=l.colwidth;l.rowspan>1&&(l={...l,rowspan:1}),l.colspan>1&&(l={...l,colspan:1});const u=Le(e),d=e.tr;for(let h=0;h{o.attrs[n]!==e&&s.setNodeMarkup(l,null,{...o.attrs,[n]:e})}):s.setNodeMarkup(i.pos,null,{...i.nodeAfter.attrs,[n]:e}),r(s)}return!0}}function y0(n){return function(e,t){if(!Ne(e))return!1;if(t){const r=ce(e.schema),i=Le(e),s=e.tr,o=i.map.cellsInRect(n=="column"?{left:i.left,top:0,right:i.right,bottom:i.map.height}:n=="row"?{left:0,top:i.top,right:i.map.width,bottom:i.bottom}:i),l=o.map(a=>i.table.nodeAt(a));for(let a=0;a{const h=f+s.tableStart,p=o.doc.nodeAt(h);p&&o.setNodeMarkup(h,d,p.attrs)}),r(o)}return!0}}Hn("row",{useDeprecatedLogic:!0});Hn("column",{useDeprecatedLogic:!0});const b0=Hn("cell",{useDeprecatedLogic:!0});function k0(n,e){if(e<0){const t=n.nodeBefore;if(t)return n.pos-t.nodeSize;for(let r=n.index(-1)-1,i=n.before();r>=0;r--){const s=n.node(-1).child(r),o=s.lastChild;if(o)return i-1-o.nodeSize;i-=s.nodeSize}}else{if(n.index()0;r--)if(t.node(r).type.spec.tableRole=="table")return e&&e(n.tr.delete(t.before(r),t.after(r)).scrollIntoView()),!0;return!1}function nr(n,e){const t=n.selection;if(!(t instanceof F))return!1;if(e){const r=n.tr,i=ce(n.schema).cell.createAndFill().content;t.forEachCell((s,o)=>{s.content.eq(i)||r.replace(r.mapping.map(o+1),r.mapping.map(o+s.nodeSize-1),new x(i,0,0))}),r.docChanged&&e(r)}return!0}function S0(n){if(n.size===0)return null;let{content:e,openStart:t,openEnd:r}=n;for(;e.childCount==1&&(t>0&&r>0||e.child(0).type.spec.tableRole=="table");)t--,r--,e=e.child(0).content;const i=e.child(0),s=i.type.spec.tableRole,o=i.type.schema,l=[];if(s=="row")for(let a=0;a=0;o--){const{rowspan:l,colspan:a}=s.child(o).attrs;for(let c=i;c=e.length&&e.push(b.empty),t[i]r&&(f=f.type.createChecked($t(f.attrs,f.attrs.colspan,u+f.attrs.colspan-r),f.content)),c.push(f),u+=f.attrs.colspan;for(let h=1;hi&&(d=d.type.create({...d.attrs,rowspan:Math.max(1,i-d.attrs.rowspan)},d.content)),a.push(d)}s.push(b.from(a))}t=s,e=i}return{width:n,height:e,rows:t}}function v0(n,e,t,r,i,s,o){const l=n.doc.type.schema,a=ce(l);let c,u;if(i>e.width)for(let d=0,f=0;de.height){const d=[];for(let p=0,m=(e.height-1)*e.width;p=e.width?!1:t.nodeAt(e.map[m+p]).type==a.header_cell;d.push(g?u||(u=a.header_cell.createAndFill()):c||(c=a.cell.createAndFill()))}const f=a.row.create(null,b.from(d)),h=[];for(let p=e.height;p{if(!i)return!1;const s=t.selection;if(s instanceof F)return gr(t,r,N.near(s.$headCell,e));if(n!="horiz"&&!s.empty)return!1;const o=Xu(i,n,e);if(o==null)return!1;if(n=="horiz")return gr(t,r,N.near(t.doc.resolve(s.head+e),e));{const l=t.doc.resolve(o),a=_u(l,n,e);let c;return a?c=N.near(a,1):e<0?c=N.near(t.doc.resolve(l.before(-1)),-1):c=N.near(t.doc.resolve(l.after(-1)),1),gr(t,r,c)}}}function ir(n,e){return(t,r,i)=>{if(!i)return!1;const s=t.selection;let o;if(s instanceof F)o=s;else{const a=Xu(i,n,e);if(a==null)return!1;o=new F(t.doc.resolve(a))}const l=_u(o.$headCell,n,e);return l?gr(t,r,new F(o.$anchorCell,l)):!1}}function T0(n,e){const t=n.state.doc,r=Bt(t.resolve(e));return r?(n.dispatch(n.state.tr.setSelection(new F(r))),!0):!1}function E0(n,e,t){if(!Ne(n.state))return!1;let r=S0(t);const i=n.state.selection;if(i instanceof F){r||(r={width:1,height:1,rows:[b.from(As(ce(n.state.schema).cell,t))]});const s=i.$anchorCell.node(-1),o=i.$anchorCell.start(-1),l=J.get(s).rectBetween(i.$anchorCell.pos-o,i.$headCell.pos-o);return r=x0(r,l.right-l.left,l.bottom-l.top),Zl(n.state,n.dispatch,o,l,r),!0}else if(r){const s=Ci(n.state),o=s.start(-1);return Zl(n.state,n.dispatch,o,J.get(s.node(-1)).findCell(s.pos-o),r),!0}else return!1}function A0(n,e){var t;if(e.button!=0||e.ctrlKey||e.metaKey)return;const r=ea(n,e.target);let i;if(e.shiftKey&&n.state.selection instanceof F)s(n.state.selection.$anchorCell,e),e.preventDefault();else if(e.shiftKey&&r&&(i=Bt(n.state.selection.$anchor))!=null&&((t=Ui(n,e))===null||t===void 0?void 0:t.pos)!=i.pos)s(i,e),e.preventDefault();else if(!r)return;function s(a,c){let u=Ui(n,c);const d=rt.getState(n.state)==null;if(!u||!po(a,u))if(d)u=a;else return;const f=new F(a,u);if(d||!n.state.selection.eq(f)){const h=n.state.tr.setSelection(f);d&&h.setMeta(rt,a.pos),n.dispatch(h)}}function o(){n.root.removeEventListener("mouseup",o),n.root.removeEventListener("dragstart",o),n.root.removeEventListener("mousemove",l),rt.getState(n.state)!=null&&n.dispatch(n.state.tr.setMeta(rt,-1))}function l(a){const c=a,u=rt.getState(n.state);let d;if(u!=null)d=n.state.doc.resolve(u);else if(ea(n,c.target)!=r&&(d=Ui(n,e),!d))return o();d&&s(d,c)}n.root.addEventListener("mouseup",o),n.root.addEventListener("dragstart",o),n.root.addEventListener("mousemove",l)}function Xu(n,e,t){if(!(n.state.selection instanceof v))return null;const{$head:r}=n.state.selection;for(let i=r.depth-1;i>=0;i--){const s=r.node(i);if((t<0?r.index(i):r.indexAfter(i))!=(t<0?0:s.childCount))return null;if(s.type.spec.tableRole=="cell"||s.type.spec.tableRole=="header_cell"){const o=r.before(i),l=e=="vert"?t>0?"down":"up":t>0?"right":"left";return n.endOfTextblock(l)?o:null}}return null}function ea(n,e){for(;e&&e!=n.dom;e=e.parentNode)if(e.nodeName=="TD"||e.nodeName=="TH")return e;return null}function Ui(n,e){const t=n.posAtCoords({left:e.clientX,top:e.clientY});if(!t)return null;let{inside:r,pos:i}=t;return r>=0&&Bt(n.state.doc.resolve(r))||Bt(n.state.doc.resolve(i))}var N0=class{constructor(e,t){this.node=e,this.defaultCellMinWidth=t,this.dom=document.createElement("div"),this.dom.className="tableWrapper",this.table=this.dom.appendChild(document.createElement("table")),this.table.style.setProperty("--default-cell-min-width",`${t}px`),this.colgroup=this.table.appendChild(document.createElement("colgroup")),Ns(e,this.colgroup,this.table,t),this.contentDOM=this.table.appendChild(document.createElement("tbody"))}update(e){return e.type!=this.node.type?!1:(this.node=e,Ns(e,this.colgroup,this.table,this.defaultCellMinWidth),!0)}ignoreMutation(e){return e.type=="attributes"&&(e.target==this.table||this.colgroup.contains(e.target))}};function Ns(n,e,t,r,i,s){let o=0,l=!0,a=e.firstChild;const c=n.firstChild;if(c){for(let d=0,f=0;dnew r(d,t,f)),new R0(-1,!1)},apply(o,l){return l.apply(o)}},props:{attributes:o=>{const l=ge.getState(o);return l&&l.activeHandle>-1?{class:"resize-cursor"}:{}},handleDOMEvents:{mousemove:(o,l)=>{D0(o,l,n,i)},mouseleave:o=>{I0(o)},mousedown:(o,l)=>{L0(o,l,e,t)}},decorations:o=>{const l=ge.getState(o);if(l&&l.activeHandle>-1)return H0(o,l.activeHandle)},nodeViews:{}}});return s}var R0=class yr{constructor(e,t){this.activeHandle=e,this.dragging=t}apply(e){const t=this,r=e.getMeta(ge);if(r&&r.setHandle!=null)return new yr(r.setHandle,!1);if(r&&r.setDragging!==void 0)return new yr(t.activeHandle,r.setDragging);if(t.activeHandle>-1&&e.docChanged){let i=e.mapping.map(t.activeHandle,-1);return Es(e.doc.resolve(i))||(i=-1),new yr(i,t.dragging)}return t}};function D0(n,e,t,r){if(!n.editable)return;const i=ge.getState(n.state);if(i&&!i.dragging){const s=z0(e.target);let o=-1;if(s){const{left:l,right:a}=s.getBoundingClientRect();e.clientX-l<=t?o=ta(n,e,"left",t):a-e.clientX<=t&&(o=ta(n,e,"right",t))}if(o!=i.activeHandle){if(!r&&o!==-1){const l=n.state.doc.resolve(o),a=l.node(-1),c=J.get(a),u=l.start(-1);if(c.colCount(l.pos-u)+l.nodeAfter.attrs.colspan-1==c.width-1)return}Qu(n,o)}}}function I0(n){if(!n.editable)return;const e=ge.getState(n.state);e&&e.activeHandle>-1&&!e.dragging&&Qu(n,-1)}function L0(n,e,t,r){var i;if(!n.editable)return!1;const s=(i=n.dom.ownerDocument.defaultView)!==null&&i!==void 0?i:window,o=ge.getState(n.state);if(!o||o.activeHandle==-1||o.dragging)return!1;const l=n.state.doc.nodeAt(o.activeHandle),a=P0(n,o.activeHandle,l.attrs);n.dispatch(n.state.tr.setMeta(ge,{setDragging:{startX:e.clientX,startWidth:a}}));function c(d){s.removeEventListener("mouseup",c),s.removeEventListener("mousemove",u);const f=ge.getState(n.state);f?.dragging&&(B0(n,f.activeHandle,na(f.dragging,d,t)),n.dispatch(n.state.tr.setMeta(ge,{setDragging:null})))}function u(d){if(!d.which)return c(d);const f=ge.getState(n.state);if(f&&f.dragging){const h=na(f.dragging,d,t);ra(n,f.activeHandle,h,r)}}return ra(n,o.activeHandle,a,r),s.addEventListener("mouseup",c),s.addEventListener("mousemove",u),e.preventDefault(),!0}function P0(n,e,{colspan:t,colwidth:r}){const i=r&&r[r.length-1];if(i)return i;const s=n.domAtPos(e);let o=s.node.childNodes[s.offset].offsetWidth,l=t;if(r)for(let a=0;aV0(n),renderHTML:n=>{const e=Fn(n.align);return dy(e)?{style:`text-align: ${e}`}:{}}}}function j0(n){var e;const t=n.parentElement,r=n.closest("table");if(!t||!r)return null;const i=Array.from(t.children).indexOf(n),s=(e=r.querySelectorAll("colgroup > col")[i])===null||e===void 0?void 0:e.getAttribute("width");return s?[parseInt(s,10)]:null}function ed(n){const e=n.getAttribute("colwidth");return e?e.split(",").map(t=>parseInt(t,10)):j0(n)}const _0=/[ \t\r\n\f]+/g;function td(n){var e;return n.children.length>0?!1:((e=n.textContent)!==null&&e!==void 0?e:"").replace(_0,"")===""}function nd(n){const e=n.createAndFill();if(!e)throw new Error(`[tiptap error]: "${n.name}" has no default content to backfill.`);return e.content}function Rr(n,e,t){if(!(t in e))return;const r=e[t];(r===1||r==="1"||r===null||r===void 0)&&delete n[t]}const rd=_.create({name:"tableCell",addOptions(){return{HTMLAttributes:{}}},content:"block+",addAttributes(){return{colspan:{default:1},rowspan:{default:1},colwidth:{default:null,parseHTML:ed},align:Zu()}},tableRole:"cell",isolating:!0,parseHTML(){return[{tag:"td",getAttrs:n=>td(n)?{}:!1,getContent:(n,e)=>nd(e.nodes[this.name])},{tag:"td"}]},renderHTML({HTMLAttributes:n}){const e=H(this.options.HTMLAttributes,n);return Rr(e,n,"colspan"),Rr(e,n,"rowspan"),["td",e,0]}}),id=_.create({name:"tableHeader",addOptions(){return{HTMLAttributes:{}}},content:"block+",addAttributes(){return{colspan:{default:1},rowspan:{default:1},colwidth:{default:null,parseHTML:ed},align:Zu()}},tableRole:"header_cell",isolating:!0,parseHTML(){return[{tag:"th",getAttrs:n=>td(n)?{}:!1,getContent:(n,e)=>nd(e.nodes[this.name])},{tag:"th"}]},renderHTML({HTMLAttributes:n}){const e=H(this.options.HTMLAttributes,n);return Rr(e,n,"colspan"),Rr(e,n,"rowspan"),["th",e,0]}}),sd=_.create({name:"tableRow",addOptions(){return{HTMLAttributes:{}}},content:"(tableCell | tableHeader)*",tableRole:"row",parseHTML(){return[{tag:"tr"}]},renderHTML({HTMLAttributes:n}){return["tr",H(this.options.HTMLAttributes,n),0]}});function Os(n,e){return e?["width",`${Math.max(e,n)}px`]:["min-width",`${n}px`]}function ia(n,e,t,r,i,s){let o=0,l=!0,a=e.firstChild;const c=n.firstChild;if(c!==null)for(let f=0,h=0;f{const r=n.nodes[t];r.spec.tableRole&&(e[r.spec.tableRole]=r)}),n.cached.tableNodeTypes=e,e}function J0(n,e,t,r,i){const s=q0(n),o=[],l=[];for(let c=0;c{const{selection:e}=n.state;if(!od(e))return!1;let t=0;const r=$n(e.ranges[0].$from,i=>i.type.name==="table");return r?.node.descendants(i=>{if(i.type.name==="table")return!1;["tableCell","tableHeader"].includes(i.type.name)&&(t+=1)}),t!==e.ranges.length?!1:(n.commands.deleteTable(),!0)};function oa(n,e){const t=n.mapping.map(e),r=$n(n.selection.$from,o=>o.type.name==="table");if(r?.pos===t)return;const i=n.doc.nodeAt(t);if(!i)return;const s=t+i.nodeSize-1;n.setSelection(v.near(n.doc.resolve(s),-1))}function G0(n){let e="",t=0;for(;ta==="|"?"\\|":a)+n.slice(i,i+r),t=i+r,s=!0;break}i+=o}s||(e+=n.slice(t,t+r),t+=r)}return e}function Y0(n){return n.split(` +`).map(e=>!e.includes("|")||!e.includes("`")?e:G0(e)).join(` +`)}function X0(n){return(n||"").replaceAll(""," ").replace(/\s+/g," ").trim()}function la(n,e){return e?n.split(e).join(` +`):n}function Q0(n){return n.replace(/\\.|\|/g,e=>e==="|"?"\\|":e)}function Z0(n,e,t={}){if(!n||!n.content||n.content.length===0)return"";const r=[];n.content.forEach(f=>{const h=[];f.content&&f.content.forEach(p=>{let m="";p.content&&Array.isArray(p.content)&&p.content.length>1?m=p.content.map(w=>la(e.renderChildren(w),t.cellLineSeparator)).join(` +`):m=la(p.content?e.renderChildren(p.content):"",t.cellLineSeparator);const g=Q0(X0(m.replace(/[ \t]*\r?\n[ \t]*/g,"
"))),y=p.type==="tableHeader",k=W0(p.attrs);h.push({text:g,isHeader:y,align:k})}),r.push(h)});const i=r.reduce((f,h)=>Math.max(f,h.length),0);if(i===0)return"";const s=Array.from({length:i}).fill(0);r.forEach(f=>{for(let p=0;ps[p]&&(s[p]=m),s[p]<3&&(s[p]=3)}});const o=(f,h)=>f+" ".repeat(Math.max(0,h-f.length)),l=r[0],a=l.some(f=>f.isHeader),c=Array.from({length:i}).fill(null);r.forEach(f=>{for(let p=0;pa&&l[h]&&l[h].text||"");return u+=`| ${d.map((f,h)=>o(f,s[h])).join(" | ")} | +`,u+=`| ${s.map((f,h)=>{const p=Math.max(3,f),m=c[h];return m==="left"?`:${"-".repeat(p)}`:m==="right"?`${"-".repeat(p)}:`:m==="center"?`:${"-".repeat(p)}:`:"-".repeat(p)}).join(" | ")} | +`,(a?r.slice(1):r).forEach(f=>{u+=`| ${Array.from({length:i}).fill(0).map((h,p)=>o(f[p]&&f[p].text||"",s[p])).join(" | ")} | +`}),u}const eb=new W("preserveCellSelectionOnContextMenu");function tb(n,e){const t=n.posAtCoords({left:e.clientX,top:e.clientY});if(t)return t.pos;if(!(e.target instanceof Node))return null;try{return n.posAtDOM(e.target,0)}catch{return null}}function nb(n,e){let t=!1;return n.forEachCell((r,i)=>{e>=i&&e{const t=[],r=Array.isArray(n.align)?n.align:[];if(n.header){const i=[];n.header.forEach((s,o)=>{var l;const a=Fn((l=r[o])!==null&&l!==void 0?l:s.align),c=a?{align:a}:{};i.push(e.createNode("tableHeader",c,[{type:"paragraph",content:e.parseInline(s.tokens)}]))}),t.push(e.createNode("tableRow",{},i))}return n.rows&&n.rows.forEach(i=>{const s=[];i.forEach((o,l)=>{var a;const c=Fn((a=r[l])!==null&&a!==void 0?a:o.align),u=c?{align:c}:{};s.push(e.createNode("tableCell",u,[{type:"paragraph",content:e.parseInline(o.tokens)}]))}),t.push(e.createNode("tableRow",{},s))}),e.createNode("table",void 0,t)},renderMarkdown:(n,e)=>Z0(n,e),markdownTokenizer:{name:"table",level:"block",start:n=>{const e=n.split(` +`);if(e.length<2)return-1;const t=e[1];return!/^[ \t|:]*-[ \t|:-]*$/.test(t)||!t.includes("|")?-1:e[0].includes("|")?0:-1},tokenize(n,e,t){const r=n.indexOf(` + +`),i=r>=0?n.slice(0,r):n,s=i.split(` +`);if(s.length<2)return;const o=s[1];if(!/^[ \t|:]*-[ \t|:-]*$/.test(o)||!o.includes("|"))return;const l=Y0(i);if(l===i)return;const a=t.blockTokens(l)[0];if(a?.type!=="table"||!a.raw)return;const c=a.raw.split(` +`).length,u=n.split(` +`).slice(0,c).join(` +`);return{...a,raw:u}}},addCommands(){return{insertTable:({rows:n=3,cols:e=3,withHeaderRow:t=!0}={})=>({tr:r,dispatch:i,editor:s})=>{const o=J0(s.schema,n,e,t);if(i){const l=r.selection.from+1;r.replaceSelectionWith(o).scrollIntoView().setSelection(v.near(r.doc.resolve(l)))}return!0},addColumnBefore:()=>({state:n,dispatch:e})=>s0(n,e),addColumnAfter:()=>({state:n,dispatch:e})=>o0(n,e),deleteColumn:()=>({state:n,dispatch:e})=>{const t=$n(n.selection.$from,r=>r.type.name==="table");return a0(n,e&&(r=>{t&&oa(r,t.pos),e(r)}))},addRowBefore:()=>({state:n,dispatch:e})=>u0(n,e),addRowAfter:()=>({state:n,dispatch:e})=>d0(n,e),deleteRow:()=>({state:n,dispatch:e})=>{const t=$n(n.selection.$from,r=>r.type.name==="table");return h0(n,e&&(r=>{t&&oa(r,t.pos),e(r)}))},deleteTable:()=>({state:n,dispatch:e})=>w0(n,e),mergeCells:()=>({state:n,dispatch:e})=>ql(n,e),splitCell:()=>({state:n,dispatch:e})=>Jl(n,e),toggleHeaderColumn:()=>({state:n,dispatch:e})=>Hn("column")(n,e),toggleHeaderRow:()=>({state:n,dispatch:e})=>Hn("row")(n,e),toggleHeaderCell:()=>({state:n,dispatch:e})=>b0(n,e),mergeOrSplit:()=>({state:n,dispatch:e})=>ql(n,e)?!0:Jl(n,e),setCellAttribute:(n,e)=>({state:t,dispatch:r})=>g0(n,e)(t,r),goToNextCell:()=>({state:n,dispatch:e})=>Yl(1)(n,e),goToPreviousCell:()=>({state:n,dispatch:e})=>Yl(-1)(n,e),fixTables:()=>({state:n,dispatch:e})=>(e&&Ju(n),!0),setCellSelection:n=>({tr:e,dispatch:t})=>{if(t){const r=F.create(e.doc,n.anchorCell,n.headCell);e.setSelection(r)}return!0}}},addKeyboardShortcuts(){return{Tab:()=>this.editor.commands.goToNextCell()?!0:this.editor.can().addRowAfter()?this.editor.chain().addRowAfter().goToNextCell().run():!1,"Shift-Tab":()=>this.editor.commands.goToPreviousCell(),Backspace:sr,"Mod-Backspace":sr,Delete:sr,"Mod-Delete":sr}},addProseMirrorPlugins(){return[...this.options.resizable&&this.editor.isEditable?[O0({handleWidth:this.options.handleWidth,cellMinWidth:this.options.cellMinWidth,defaultCellMinWidth:this.options.cellMinWidth,View:this.options.View,lastColumnResizable:this.options.lastColumnResizable})]:[],F0({allowTableNodeSelection:this.options.allowTableNodeSelection}),rb()]},addNodeView(){const n=this.options.resizable&&this.editor.isEditable,e=this.options.View;return n||!e?null:({node:t,view:r,HTMLAttributes:i})=>{const s=H(this.options.HTMLAttributes,i);return new e(t,this.options.cellMinWidth,r,s)}},extendNodeSchema(n){const e={name:n.name,options:n.options,storage:n.storage};return{tableRole:L(M(n,"tableRole",e))}}});j.create({name:"tableKit",addExtensions(){const n=[];return this.options.table!==!1&&n.push(ld.configure(this.options.table)),this.options.tableCell!==!1&&n.push(rd.configure(this.options.tableCell)),this.options.tableHeader!==!1&&n.push(id.configure(this.options.tableHeader)),this.options.tableRow!==!1&&n.push(sd.configure(this.options.tableRow)),n}});const ad=new WeakSet,cd=new WeakSet;function bt(n){const e=n;return ad.add(e),e}function Rs(n){return Array.isArray(n)&&ad.has(n)}function ud(n){return n.flatMap(e=>e==null?[]:Array.isArray(e)&&cd.has(e)&&!Rs(e)?ud(e):[e])}function ib(n,e){if(n==="slot")return 0;if(n instanceof Function){const i=n(e);return Array.isArray(i)&&!Rs(i)&&!cd.has(i)?bt(i):i}const{children:t,...r}=e??{};if(n==="svg")throw new Error("SVG elements are not supported in the JSX syntax, use the array syntax instead");if(Array.isArray(t)){if(Rs(t))return bt([n,r,t]);if(t.length===0)return bt([n,r]);const i=ud(t);return i.length===0?bt([n,r]):bt([n,r,...i])}return t!=null?bt([n,r,t]):bt([n,r])}const Dr=(n,e)=>ib(n,e),sb=(n,e)=>{var t;const{state:r}=n,{selection:i}=r;if(!i.empty)return!1;const{$from:s}=i;if(s.parentOffset!==0)return!1;const o=s.depth-1;if(o<0)return!1;const l=s.node(o),a=s.index(o);if(a===0)return!1;if(l.type===e)return n.commands.lift(e.name);const c=l.child(a-1);if(c.type!==e||!(!((t=c.lastChild)===null||t===void 0)&&t.isTextblock))return!1;const u=s.before()-1-1;return n.commands.command(({tr:d,dispatch:f})=>{if(!f)return!0;const h=s.parent.content,p=new x(h,0,0);return d.replace(u,s.after(),p),d.setSelection(v.create(d.doc,u+h.size)),d.scrollIntoView(),f(d),!0})},ob=/^\s*>\s$/,lb=_.create({name:"blockquote",addOptions(){return{HTMLAttributes:{}}},content:"block+",group:"block",defining:!0,parseHTML(){return[{tag:"blockquote"}]},renderHTML({HTMLAttributes:n}){return Dr("blockquote",{...H(this.options.HTMLAttributes,n),children:Dr("slot",{})})},parseMarkdown:(n,e)=>{var t;const r=(t=e.parseBlockChildren)!==null&&t!==void 0?t:e.parseChildren;return e.createNode("blockquote",void 0,r(n.tokens||[]))},renderMarkdown:(n,e)=>{if(!n.content)return"";const t=">",r=[];return n.content.forEach((i,s)=>{var o,l;const a=((o=(l=e.renderChild)===null||l===void 0?void 0:l.call(e,i,s))!==null&&o!==void 0?o:e.renderChildren([i])).split(` `).map(c=>c.trim()===""?t:`${t} ${c}`);r.push(a.join(` `))}),r.join(` ${t} -`)},addCommands(){return{setBlockquote:()=>({commands:n})=>n.wrapIn(this.name),toggleBlockquote:()=>({commands:n})=>n.toggleWrap(this.name),unsetBlockquote:()=>({commands:n})=>n.lift(this.name)}},addKeyboardShortcuts(){return{"Mod-Shift-b":()=>this.editor.commands.toggleBlockquote(),Backspace:()=>sg(this.editor,this.type)}},addInputRules(){return[_t({find:og,type:this.type})]}}),ag=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))$/,cg=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))/g,ug=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))$/,dg=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))/g,fg=Et.create({name:"bold",addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:"strong"},{tag:"b",getAttrs:n=>n.style.fontWeight!=="normal"&&null},{style:"font-weight=400",clearMark:n=>n.type.name===this.name},{style:"font-weight",getAttrs:n=>/^(bold(er)?|[5-9]\d{2,})$/.test(n)&&null}]},renderHTML({HTMLAttributes:n}){return cr("strong",{...J(this.options.HTMLAttributes,n),children:cr("slot",{})})},markdownTokenName:"strong",parseMarkdown:(n,e)=>e.applyMark("bold",e.parseInline(n.tokens||[])),markdownOptions:{htmlReopen:{open:"",close:""}},renderMarkdown:(n,e)=>`**${e.renderChildren(n)}**`,addCommands(){return{setBold:()=>({commands:n})=>n.setMark(this.name),toggleBold:()=>({commands:n})=>n.toggleMark(this.name),unsetBold:()=>({commands:n})=>n.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-b":()=>this.editor.commands.toggleBold(),"Mod-B":()=>this.editor.commands.toggleBold()}},addInputRules(){return[vt({find:ag,type:this.type}),vt({find:ug,type:this.type})]},addPasteRules(){return[it({find:cg,type:this.type}),it({find:dg,type:this.type})]}}),hg=n=>{const e=/`([^`]+)`(?!`)$/.exec(n);return!e||e.index>0&&n[e.index-1]==="`"?null:{index:e.index,text:e[0],replaceWith:e[1]}},pg=n=>{const e=/`([^`]+)`(?!`)/g,t=[];let r;for(;(r=e.exec(n))!==null;)r.index>0&&n[r.index-1]==="`"||t.push({index:r.index,text:r[0],replaceWith:r[1]});return t};function mg(n){const e=new Set((n.match(/`+/g)||[]).map(r=>r.length));let t=1;for(;e.has(t);)t+=1;return t}const gg=Et.create({name:"code",addOptions(){return{HTMLAttributes:{}}},excludes:"_",code:!0,exitable:!0,parseHTML(){return[{tag:"code"}]},renderHTML({HTMLAttributes:n}){return["code",J(this.options.HTMLAttributes,n),0]},markdownTokenName:"codespan",parseMarkdown:(n,e)=>e.applyMark("code",[{type:"text",text:n.text||""}]),renderMarkdown:(n,e,t)=>{var r;if(!n.content)return"";const i=typeof(t==null||(r=t.meta)===null||r===void 0?void 0:r.markText)=="string"?t.meta.markText:"",s="`".repeat(mg(i)),o=i.startsWith("`")||i.endsWith("`")?" ":"";return`${s}${o}${e.renderChildren(n.content)}${o}${s}`},addCommands(){return{setCode:()=>({commands:n})=>n.setMark(this.name),toggleCode:()=>({commands:n})=>n.toggleMark(this.name),unsetCode:()=>({commands:n})=>n.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-e":()=>this.editor.commands.toggleCode()}},addInputRules(){return[vt({find:hg,type:this.type})]},addPasteRules(){return[it({find:pg,type:this.type})]}}),ki=4,yg=/^```([a-z]+)?[\s\n]$/,bg=/^~~~([a-z]+)?[\s\n]$/,kg=pe.create({name:"codeBlock",addOptions(){return{languageClassPrefix:"language-",exitOnTripleEnter:!0,exitOnArrowDown:!0,exitOnArrowUp:!0,defaultLanguage:null,enableTabIndentation:!1,tabSize:ki,HTMLAttributes:{}}},content:"text*",marks:"",group:"block",code:!0,defining:!0,addAttributes(){return{language:{default:this.options.defaultLanguage,parseHTML:n=>{var e;const{languageClassPrefix:t}=this.options;if(!t)return null;const r=[...((e=n.firstElementChild)===null||e===void 0?void 0:e.classList)||[]].filter(i=>i.startsWith(t)).map(i=>i.replace(t,""))[0];return r||null},rendered:!1}}},parseHTML(){return[{tag:"pre",preserveWhitespace:"full"}]},renderHTML({node:n,HTMLAttributes:e}){return["pre",J(this.options.HTMLAttributes,e),["code",{class:n.attrs.language?this.options.languageClassPrefix+n.attrs.language:null},0]]},markdownTokenName:"code",parseMarkdown:(n,e)=>{var t,r;return((t=n.raw)===null||t===void 0?void 0:t.startsWith("```"))===!1&&((r=n.raw)===null||r===void 0?void 0:r.startsWith("~~~"))===!1&&n.codeBlockStyle!=="indented"?[]:e.createNode("codeBlock",{language:n.lang||null},n.text?[e.createTextNode(n.text)]:[])},renderMarkdown:(n,e)=>{var t;let r="";const i=((t=n.attrs)===null||t===void 0?void 0:t.language)||"";return n.content?r=[`\`\`\`${i}`,e.renderChildren(n.content),"```"].join(` +`)},addCommands(){return{setBlockquote:()=>({commands:n})=>n.wrapIn(this.name),toggleBlockquote:()=>({commands:n})=>n.toggleWrap(this.name),unsetBlockquote:()=>({commands:n})=>n.lift(this.name)}},addKeyboardShortcuts(){return{"Mod-Shift-b":()=>this.editor.commands.toggleBlockquote(),Backspace:()=>sb(this.editor,this.type)}},addInputRules(){return[sn({find:ob,type:this.type})]}}),ab=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))$/,cb=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))/g,ub=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))$/,db=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))/g,fb=gt.create({name:"bold",addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:"strong"},{tag:"b",getAttrs:n=>n.style.fontWeight!=="normal"&&null},{style:"font-weight=400",clearMark:n=>n.type.name===this.name},{style:"font-weight",getAttrs:n=>/^(bold(er)?|[5-9]\d{2,})$/.test(n)&&null}]},renderHTML({HTMLAttributes:n}){return Dr("strong",{...H(this.options.HTMLAttributes,n),children:Dr("slot",{})})},markdownTokenName:"strong",parseMarkdown:(n,e)=>e.applyMark("bold",e.parseInline(n.tokens||[])),markdownOptions:{htmlReopen:{open:"",close:""}},renderMarkdown:(n,e)=>`**${e.renderChildren(n)}**`,addCommands(){return{setBold:()=>({commands:n})=>n.setMark(this.name),toggleBold:()=>({commands:n})=>n.toggleMark(this.name),unsetBold:()=>({commands:n})=>n.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-b":()=>this.editor.commands.toggleBold(),"Mod-B":()=>this.editor.commands.toggleBold()}},addInputRules(){return[zt({find:ab,type:this.type}),zt({find:ub,type:this.type})]},addPasteRules(){return[ft({find:cb,type:this.type}),ft({find:db,type:this.type})]}}),hb=n=>{const e=/`([^`]+)`(?!`)$/.exec(n);return!e||e.index>0&&n[e.index-1]==="`"?null:{index:e.index,text:e[0],replaceWith:e[1]}},pb=n=>{const e=/`([^`]+)`(?!`)/g,t=[];let r;for(;(r=e.exec(n))!==null;)r.index>0&&n[r.index-1]==="`"||t.push({index:r.index,text:r[0],replaceWith:r[1]});return t};function mb(n){const e=new Set((n.match(/`+/g)||[]).map(r=>r.length));let t=1;for(;e.has(t);)t+=1;return t}const gb=gt.create({name:"code",addOptions(){return{HTMLAttributes:{}}},excludes:"_",code:!0,exitable:!0,parseHTML(){return[{tag:"code"}]},renderHTML({HTMLAttributes:n}){return["code",H(this.options.HTMLAttributes,n),0]},markdownTokenName:"codespan",parseMarkdown:(n,e)=>e.applyMark("code",[{type:"text",text:n.text||""}]),renderMarkdown:(n,e,t)=>{var r;if(!n.content)return"";const i=typeof(t==null||(r=t.meta)===null||r===void 0?void 0:r.markText)=="string"?t.meta.markText:"",s="`".repeat(mb(i)),o=i.startsWith("`")||i.endsWith("`")?" ":"";return`${s}${o}${e.renderChildren(n.content)}${o}${s}`},addCommands(){return{setCode:()=>({commands:n})=>n.setMark(this.name),toggleCode:()=>({commands:n})=>n.toggleMark(this.name),unsetCode:()=>({commands:n})=>n.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-e":()=>this.editor.commands.toggleCode()}},addInputRules(){return[zt({find:hb,type:this.type})]},addPasteRules(){return[ft({find:pb,type:this.type})]}}),Ki=4,yb=/^```([a-z]+)?[\s\n]$/,bb=/^~~~([a-z]+)?[\s\n]$/,kb=_.create({name:"codeBlock",addOptions(){return{languageClassPrefix:"language-",exitOnTripleEnter:!0,exitOnArrowDown:!0,exitOnArrowUp:!0,defaultLanguage:null,enableTabIndentation:!1,tabSize:Ki,HTMLAttributes:{}}},content:"text*",marks:"",group:"block",code:!0,defining:!0,addAttributes(){return{language:{default:this.options.defaultLanguage,parseHTML:n=>{var e;const{languageClassPrefix:t}=this.options;if(!t)return null;const r=[...((e=n.firstElementChild)===null||e===void 0?void 0:e.classList)||[]].filter(i=>i.startsWith(t)).map(i=>i.replace(t,""))[0];return r||null},rendered:!1}}},parseHTML(){return[{tag:"pre",preserveWhitespace:"full"}]},renderHTML({node:n,HTMLAttributes:e}){return["pre",H(this.options.HTMLAttributes,e),["code",{class:n.attrs.language?this.options.languageClassPrefix+n.attrs.language:null},0]]},markdownTokenName:"code",parseMarkdown:(n,e)=>{var t,r;return((t=n.raw)===null||t===void 0?void 0:t.startsWith("```"))===!1&&((r=n.raw)===null||r===void 0?void 0:r.startsWith("~~~"))===!1&&n.codeBlockStyle!=="indented"?[]:e.createNode("codeBlock",{language:n.lang||null},n.text?[e.createTextNode(n.text)]:[])},renderMarkdown:(n,e)=>{var t;let r="";const i=((t=n.attrs)===null||t===void 0?void 0:t.language)||"";return n.content?r=[`\`\`\`${i}`,e.renderChildren(n.content),"```"].join(` `):r=`\`\`\`${i} -\`\`\``,r},addCommands(){return{setCodeBlock:n=>({commands:e})=>e.setNode(this.name,n),toggleCodeBlock:n=>({commands:e})=>e.toggleNode(this.name,"paragraph",n)}},addKeyboardShortcuts(){return{"Mod-Alt-c":()=>this.editor.commands.toggleCodeBlock(),Backspace:()=>{const{empty:n,$anchor:e}=this.editor.state.selection,t=e.pos===1;return!n||e.parent.type.name!==this.name?!1:t||!e.parent.textContent.length?this.editor.commands.clearNodes():!1},Tab:({editor:n})=>{var e;if(!this.options.enableTabIndentation)return!1;const t=(e=this.options.tabSize)!==null&&e!==void 0?e:ki,{state:r}=n,{selection:i}=r,{$from:s,empty:o}=i;if(s.parent.type!==this.type)return!1;const l=" ".repeat(t);return o?n.commands.insertContent(l):n.commands.command(({tr:a})=>{const{from:c,to:u}=i,d=r.doc.textBetween(c,u,` +\`\`\``,r},addCommands(){return{setCodeBlock:n=>({commands:e})=>e.setNode(this.name,n),toggleCodeBlock:n=>({commands:e})=>e.toggleNode(this.name,"paragraph",n)}},addKeyboardShortcuts(){return{"Mod-Alt-c":()=>this.editor.commands.toggleCodeBlock(),Backspace:()=>{const{empty:n,$anchor:e}=this.editor.state.selection,t=e.pos===1;return!n||e.parent.type.name!==this.name?!1:t||!e.parent.textContent.length?this.editor.commands.clearNodes():!1},Tab:({editor:n})=>{var e;if(!this.options.enableTabIndentation)return!1;const t=(e=this.options.tabSize)!==null&&e!==void 0?e:Ki,{state:r}=n,{selection:i}=r,{$from:s,empty:o}=i;if(s.parent.type!==this.type)return!1;const l=" ".repeat(t);return o?n.commands.insertContent(l):n.commands.command(({tr:a})=>{const{from:c,to:u}=i,d=r.doc.textBetween(c,u,` `,` `).split(` `).map(f=>l+f).join(` -`);return a.replaceWith(c,u,r.schema.text(d)),!0})},"Shift-Tab":({editor:n})=>{var e;if(!this.options.enableTabIndentation)return!1;const t=(e=this.options.tabSize)!==null&&e!==void 0?e:ki,{state:r}=n,{selection:i}=r,{$from:s,empty:o}=i;return s.parent.type!==this.type?!1:o?n.commands.command(({tr:l})=>{var a;const{pos:c}=s,u=s.start(),d=s.end(),f=r.doc.textBetween(u,d,` +`);return a.replaceWith(c,u,r.schema.text(d)),!0})},"Shift-Tab":({editor:n})=>{var e;if(!this.options.enableTabIndentation)return!1;const t=(e=this.options.tabSize)!==null&&e!==void 0?e:Ki,{state:r}=n,{selection:i}=r,{$from:s,empty:o}=i;return s.parent.type!==this.type?!1:o?n.commands.command(({tr:l})=>{var a;const{pos:c}=s,u=s.start(),d=s.end(),f=r.doc.textBetween(u,d,` `,` `).split(` -`);let h=0,p=0;const m=c-u;for(let x=0;x=m){h=x;break}p+=f[x].length+1}const g=((a=f[h].match(/^ */))===null||a===void 0?void 0:a[0])||"",y=Math.min(g.length,t);if(y===0)return!0;let S=u;for(let x=0;x{const{from:a,to:c}=i,u=r.doc.textBetween(a,c,` +`);let h=0,p=0;const m=c-u;for(let w=0;w=m){h=w;break}p+=f[w].length+1}const g=((a=f[h].match(/^ */))===null||a===void 0?void 0:a[0])||"",y=Math.min(g.length,t);if(y===0)return!0;let k=u;for(let w=0;w{const{from:a,to:c}=i,u=r.doc.textBetween(a,c,` `,` `).split(` `).map(d=>{var f;const h=((f=d.match(/^ */))===null||f===void 0?void 0:f[0])||"",p=Math.min(h.length,t);return d.slice(p)}).join(` `);return l.replaceWith(a,c,r.schema.text(u)),!0})},Enter:({editor:n})=>{if(!this.options.exitOnTripleEnter)return!1;const{state:e}=n,{selection:t}=e,{$from:r,empty:i}=t;if(!i||r.parent.type!==this.type)return!1;const s=r.parentOffset===r.parent.nodeSize-2,o=r.parent.textContent.endsWith(` -`);return!s||!o?!1:n.chain().command(({tr:l})=>(l.delete(r.pos-2,r.pos),!0)).exitCode().run()},ArrowUp:({editor:n})=>{if(!this.options.exitOnArrowUp)return!1;const{state:e}=n,{selection:t}=e,{$from:r,empty:i}=t;if(!i||r.parent.type!==this.type||r.parentOffset!==0)return!1;const s=r.before();return s>0?!1:n.commands.insertDefaultBlock({pos:s})},ArrowDown:({editor:n})=>{if(!this.options.exitOnArrowDown)return!1;const{state:e}=n,{selection:t,doc:r}=e,{$from:i,empty:s}=t;if(!s||i.parent.type!==this.type||i.parentOffset!==i.parent.nodeSize-2)return!1;const o=i.after();return o===void 0?!1:r.nodeAt(o)?n.commands.command(({tr:l})=>(l.setSelection(O.near(r.resolve(o))),!0)):n.commands.exitCode()}}},addInputRules(){return[Ji({find:yg,type:this.type,getAttributes:n=>({language:n[1]})}),Ji({find:bg,type:this.type,getAttributes:n=>({language:n[1]})})]},addProseMirrorPlugins(){return[new $({key:new _("codeBlockVSCodeHandler"),props:{handlePaste:(n,e)=>{if(!e.clipboardData||this.editor.isActive(this.type.name))return!1;const t=e.clipboardData.getData("text/plain"),r=e.clipboardData.getData("vscode-editor-data"),i=r?JSON.parse(r):void 0,s=i?.mode;if(!t||!s)return!1;const{tr:o,schema:l}=n.state,a=l.text(t.replace(/\r\n?/g,` -`));return o.replaceSelectionWith(this.type.create({language:s},a)),o.selection.$from.parent.type!==this.type&&o.setSelection(T.near(o.doc.resolve(Math.max(0,o.selection.from-2)))),o.setMeta("paste",!0),n.dispatch(o),!0}}})]}}),Sg=pe.create({name:"doc",topNode:!0,content:"block+",renderMarkdown:(n,e)=>n.content?e.renderChildren(n.content,` +`);return!s||!o?!1:n.chain().command(({tr:l})=>(l.delete(r.pos-2,r.pos),!0)).exitCode().run()},ArrowUp:({editor:n})=>{if(!this.options.exitOnArrowUp)return!1;const{state:e}=n,{selection:t}=e,{$from:r,empty:i}=t;if(!i||r.parent.type!==this.type||r.parentOffset!==0)return!1;const s=r.before();return s>0?!1:n.commands.insertDefaultBlock({pos:s})},ArrowDown:({editor:n})=>{if(!this.options.exitOnArrowDown)return!1;const{state:e}=n,{selection:t,doc:r}=e,{$from:i,empty:s}=t;if(!s||i.parent.type!==this.type||i.parentOffset!==i.parent.nodeSize-2)return!1;const o=i.after();return o===void 0?!1:r.nodeAt(o)?n.commands.command(({tr:l})=>(l.setSelection(N.near(r.resolve(o))),!0)):n.commands.exitCode()}}},addInputRules(){return[vs({find:yb,type:this.type,getAttributes:n=>({language:n[1]})}),vs({find:bb,type:this.type,getAttributes:n=>({language:n[1]})})]},addProseMirrorPlugins(){return[new z({key:new W("codeBlockVSCodeHandler"),props:{handlePaste:(n,e)=>{if(!e.clipboardData||this.editor.isActive(this.type.name))return!1;const t=e.clipboardData.getData("text/plain"),r=e.clipboardData.getData("vscode-editor-data"),i=r?JSON.parse(r):void 0,s=i?.mode;if(!t||!s)return!1;const{tr:o,schema:l}=n.state,a=l.text(t.replace(/\r\n?/g,` +`));return o.replaceSelectionWith(this.type.create({language:s},a)),o.selection.$from.parent.type!==this.type&&o.setSelection(v.near(o.doc.resolve(Math.max(0,o.selection.from-2)))),o.setMeta("paste",!0),n.dispatch(o),!0}}})]}}),wb=_.create({name:"doc",topNode:!0,content:"block+",renderMarkdown:(n,e)=>n.content?e.renderChildren(n.content,` -`):""}),xg=pe.create({name:"hardBreak",markdownTokenName:"br",addOptions(){return{keepMarks:!0,HTMLAttributes:{}}},inline:!0,group:"inline",selectable:!1,linebreakReplacement:!0,parseHTML(){return[{tag:"br"}]},renderHTML({HTMLAttributes:n}){return["br",J(this.options.HTMLAttributes,n)]},renderText(){return` +`):""}),Sb=_.create({name:"hardBreak",markdownTokenName:"br",addOptions(){return{keepMarks:!0,HTMLAttributes:{}}},inline:!0,group:"inline",selectable:!1,linebreakReplacement:!0,parseHTML(){return[{tag:"br"}]},renderHTML({HTMLAttributes:n}){return["br",H(this.options.HTMLAttributes,n)]},renderText(){return` `},renderMarkdown:()=>` -`,parseMarkdown:()=>({type:"hardBreak"}),addCommands(){return{setHardBreak:()=>({commands:n,chain:e,state:t,editor:r})=>n.first([()=>n.exitCode(),()=>n.command(()=>{const{selection:i,storedMarks:s}=t;if(i.$from.parent.type.spec.isolating)return!1;const{keepMarks:o}=this.options,{splittableMarks:l}=r.extensionManager,a=s||i.$to.parentOffset&&i.$from.marks();return e().insertContent({type:this.name}).command(({tr:c,dispatch:u})=>{if(u&&a&&o){const d=a.filter(f=>l.includes(f.type.name));c.ensureMarks(d)}return!0}).scrollIntoView().run()})])}},addKeyboardShortcuts(){return{"Mod-Enter":()=>this.editor.commands.setHardBreak(),"Shift-Enter":()=>this.editor.commands.setHardBreak()}}}),wg=pe.create({name:"heading",addOptions(){return{levels:[1,2,3,4,5,6],HTMLAttributes:{}}},content:"inline*",group:"block",defining:!0,addAttributes(){return{level:{default:1,rendered:!1}}},parseHTML(){return this.options.levels.map(n=>({tag:`h${n}`,attrs:{level:n}}))},renderHTML({node:n,HTMLAttributes:e}){return[`h${this.options.levels.includes(n.attrs.level)?n.attrs.level:this.options.levels[0]}`,J(this.options.HTMLAttributes,e),0]},parseMarkdown:(n,e)=>e.createNode("heading",{level:n.depth||1},e.parseInline(n.tokens||[])),renderMarkdown:(n,e)=>{var t;const r=!((t=n.attrs)===null||t===void 0)&&t.level?parseInt(n.attrs.level,10):1,i="#".repeat(r);return n.content?`${i} ${e.renderChildren(n.content)}`:""},addCommands(){return{setHeading:n=>({commands:e})=>this.options.levels.includes(n.level)?e.setNode(this.name,n):!1,toggleHeading:n=>({commands:e})=>this.options.levels.includes(n.level)?e.toggleNode(this.name,"paragraph",n):!1}},addKeyboardShortcuts(){return this.options.levels.reduce((n,e)=>({...n,[`Mod-Alt-${e}`]:()=>this.editor.commands.toggleHeading({level:e})}),{})},addInputRules(){return this.options.levels.map(n=>Ji({find:new RegExp(`^(#{${Math.min(...this.options.levels)},${n}})\\s$`),type:this.type,getAttributes:{level:n}}))}}),Cg=pe.create({name:"horizontalRule",addOptions(){return{HTMLAttributes:{},nextNodeType:"paragraph"}},group:"block",parseHTML(){return[{tag:"hr"}]},renderHTML({HTMLAttributes:n}){return["hr",J(this.options.HTMLAttributes,n)]},markdownTokenName:"hr",parseMarkdown:(n,e)=>e.createNode("horizontalRule"),renderMarkdown:()=>"---",addCommands(){return{setHorizontalRule:()=>({chain:n,state:e})=>{if(!Am(e,e.schema.nodes[this.name]))return!1;const{selection:t}=e,{$to:r}=t,i=n();return Mc(t)?i.insertContentAt(r.pos,{type:this.name}):i.insertContent({type:this.name}),i.command(({state:s,tr:o,dispatch:l})=>{if(l){const{$to:a}=o.selection,c=a.end();if(a.nodeAfter)a.nodeAfter.isTextblock?o.setSelection(T.create(o.doc,a.pos+1)):a.nodeAfter.isBlock?o.setSelection(E.create(o.doc,a.pos)):o.setSelection(T.create(o.doc,a.pos));else{const u=s.schema.nodes[this.options.nextNodeType]||a.parent.type.contentMatch.defaultType,d=u?.create();d&&(o.insert(c,d),o.setSelection(T.create(o.doc,c+1)))}o.scrollIntoView()}return!0}).run()}}},addInputRules(){return[rg({find:/^(?:---|—-|___\s|\*\*\*\s)$/,type:this.type})]}}),Mg=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))$/,vg=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))/g,Eg=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))$/,Tg=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))/g,Ag=Et.create({name:"italic",addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:"em"},{tag:"i",getAttrs:n=>n.style.fontStyle!=="normal"&&null},{style:"font-style=normal",clearMark:n=>n.type.name===this.name},{style:"font-style=italic"}]},renderHTML({HTMLAttributes:n}){return["em",J(this.options.HTMLAttributes,n),0]},addCommands(){return{setItalic:()=>({commands:n})=>n.setMark(this.name),toggleItalic:()=>({commands:n})=>n.toggleMark(this.name),unsetItalic:()=>({commands:n})=>n.unsetMark(this.name)}},markdownTokenName:"em",parseMarkdown:(n,e)=>e.applyMark("italic",e.parseInline(n.tokens||[])),markdownOptions:{htmlReopen:{open:"",close:""}},renderMarkdown:(n,e)=>`*${e.renderChildren(n)}*`,addKeyboardShortcuts(){return{"Mod-i":()=>this.editor.commands.toggleItalic(),"Mod-I":()=>this.editor.commands.toggleItalic()}},addInputRules(){return[vt({find:Mg,type:this.type}),vt({find:Eg,type:this.type})]},addPasteRules(){return[it({find:vg,type:this.type}),it({find:Tg,type:this.type})]}}),Og="aaa1rp3bb0ott3vie4c1le2ogado5udhabi7c0ademy5centure6ountant0s9o1tor4d0s1ult4e0g1ro2tna4f0l1rica5g0akhan5ency5i0g1rbus3force5tel5kdn3l0ibaba4pay4lfinanz6state5y2sace3tom5m0azon4ericanexpress7family11x2fam3ica3sterdam8nalytics7droid5quan4z2o0l2partments8p0le4q0uarelle8r0ab1mco4chi3my2pa2t0e3s0da2ia2sociates9t0hleta5torney7u0ction5di0ble3o3spost5thor3o0s4w0s2x0a2z0ure5ba0by2idu3namex4d1k2r0celona5laycard4s5efoot5gains6seball5ketball8uhaus5yern5b0c1t1va3cg1n2d1e0ats2uty4er2rlin4st0buy5t2f1g1h0arti5i0ble3d1ke2ng0o3o1z2j1lack0friday9ockbuster8g1omberg7ue3m0s1w2n0pparibas9o0ats3ehringer8fa2m1nd2o0k0ing5sch2tik2on4t1utique6x2r0adesco6idgestone9oadway5ker3ther5ussels7s1t1uild0ers6siness6y1zz3v1w1y1z0h3ca0b1fe2l0l1vinklein9m0era3p2non3petown5ital0one8r0avan4ds2e0er0s4s2sa1e1h1ino4t0ering5holic7ba1n1re3c1d1enter4o1rn3f0a1d2g1h0anel2nel4rity4se2t2eap3intai5ristmas6ome4urch5i0priani6rcle4sco3tadel4i0c2y3k1l0aims4eaning6ick2nic1que6othing5ud3ub0med6m1n1o0ach3des3ffee4llege4ogne5m0mbank4unity6pany2re3uter5sec4ndos3struction8ulting7tact3ractors9oking4l1p2rsica5untry4pon0s4rses6pa2r0edit0card4union9icket5own3s1uise0s6u0isinella9v1w1x1y0mru3ou3z2dad1nce3ta1e1ing3sun4y2clk3ds2e0al0er2s3gree4livery5l1oitte5ta3mocrat6ntal2ist5si0gn4v2hl2iamonds6et2gital5rect0ory7scount3ver5h2y2j1k1m1np2o0cs1tor4g1mains5t1wnload7rive4tv2ubai3pont4rban5vag2r2z2earth3t2c0o2deka3u0cation8e1g1mail3erck5nergy4gineer0ing9terprises10pson4quipment8r0icsson6ni3s0q1tate5t1u0rovision8s2vents5xchange6pert3osed4ress5traspace10fage2il1rwinds6th3mily4n0s2rm0ers5shion4t3edex3edback6rrari3ero6i0delity5o2lm2nal1nce1ial7re0stone6mdale6sh0ing5t0ness6j1k1lickr3ghts4r2orist4wers5y2m1o0o0d1tball6rd1ex2sale4um3undation8x2r0ee1senius7l1ogans4ntier7tr2ujitsu5n0d2rniture7tbol5yi3ga0l0lery3o1up4me0s3p1rden4y2b0iz3d0n2e0a1nt0ing5orge5f1g0ee3h1i0ft0s3ves2ing5l0ass3e1obal2o4m0ail3bh2o1x2n1odaddy5ld0point6f2odyear5g0le4p1t1v2p1q1r0ainger5phics5tis4een3ipe3ocery4up4s1t1u0cci3ge2ide2tars5ru3w1y2hair2mburg5ngout5us3bo2dfc0bank7ealth0care8lp1sinki6re1mes5iphop4samitsu7tachi5v2k0t2m1n1ockey4ldings5iday5medepot5goods5s0ense7nda3rse3spital5t0ing5t0els3mail5use3w2r1sbc3t1u0ghes5yatt3undai7ibm2cbc2e1u2d1e0ee3fm2kano4l1m0amat4db2mo0bilien9n0c1dustries8finiti5o2g1k1stitute6urance4e4t0ernational10uit4vestments10o1piranga7q1r0ish4s0maili5t0anbul7t0au2v3jaguar4va3cb2e0ep2tzt3welry6io2ll2m0p2nj2o0bs1urg4t1y2p0morgan6rs3uegos4niper7kaufen5ddi3e0rryhotels6properties14fh2g1h1i0a1ds2m1ndle4tchen5wi3m1n1oeln3matsu5sher5p0mg2n2r0d1ed3uokgroup8w1y0oto4z2la0caixa5mborghini8er3nd0rover6xess5salle5t0ino3robe5w0yer5b1c1ds2ease3clerc5frak4gal2o2xus4gbt3i0dl2fe0insurance9style7ghting6ke2lly3mited4o2ncoln4k2ve1ing5k1lc1p2oan0s3cker3us3l1ndon4tte1o3ve3pl0financial11r1s1t0d0a3u0ndbeck6xe1ury5v1y2ma0drid4if1son4keup4n0agement7go3p1rket0ing3s4riott5shalls7ttel5ba2c0kinsey7d1e0d0ia3et2lbourne7me1orial6n0u2rck0msd7g1h1iami3crosoft7l1ni1t2t0subishi9k1l0b1s2m0a2n1o0bi0le4da2e1i1m1nash3ey2ster5rmon3tgage6scow4to0rcycles9v0ie4p1q1r1s0d2t0n1r2u0seum3ic4v1w1x1y1z2na0b1goya4me2vy3ba2c1e0c1t0bank4flix4work5ustar5w0s2xt0direct7us4f0l2g0o2hk2i0co2ke1on3nja3ssan1y5l1o0kia3rton4w0ruz3tv4p1r0a1w2tt2u1yc2z2obi1server7ffice5kinawa6layan0group9lo3m0ega4ne1g1l0ine5oo2pen3racle3nge4g0anic5igins6saka4tsuka4t2vh3pa0ge2nasonic7ris2s1tners4s1y3y2ccw3e0t2f0izer5g1h0armacy6d1ilips5one2to0graphy6s4ysio5ics1tet2ures6d1n0g1k2oneer5zza4k1l0ace2y0station9umbing5s3m1n0c2ohl2ker3litie5rn2st3r0axi3ess3ime3o0d0uctions8f1gressive8mo2perties3y5tection8u0dential9s1t1ub2w0c2y2qa1pon3uebec3st5racing4dio4e0ad1lestate6tor2y4cipes5d0umbrella9hab3ise0n3t2liance6n0t0als5pair3ort3ublican8st0aurant8view0s5xroth6ich0ardli6oh3l1o1p2o0cks3deo3gers4om3s0vp3u0gby3hr2n2w0e2yukyu6sa0arland6fe0ty4kura4le1on3msclub4ung5ndvik0coromant12ofi4p1rl2s1ve2xo3b0i1s2c0b1haeffler7midt4olarships8ol3ule3warz5ience5ot3d1e0arch3t2cure1ity6ek2lect4ner3rvices6ven3w1x0y3fr2g1h0angrila6rp3ell3ia1ksha5oes2p0ping5uji3w3i0lk2na1gles5te3j1k0i0n2y0pe4l0ing4m0art3ile4n0cf3o0ccer3ial4ftbank4ware6hu2lar2utions7ng1y2y2pa0ce3ort2t3r0l2s1t0ada2ples4r1tebank4farm7c0group6ockholm6rage3e3ream4udio2y3yle4u0cks3pplies3y2ort5rf1gery5zuki5v1watch4iss4x1y0dney4stems6z2tab1ipei4lk2obao4rget4tamotors6r2too4x0i3c0i2d0k2eam2ch0nology8l1masek5nnis4va3f1g1h0d1eater2re6iaa2ckets5enda4ps2res2ol4j0maxx4x2k0maxx5l1m0all4n1o0day3kyo3ols3p1ray3shiba5tal3urs3wn2yota3s3r0ade1ing4ining5vel0ers0insurance16ust3v2t1ube2i1nes3shu4v0s2w1z2ua1bank3s2g1k1nicom3versity8o2ol2ps2s1y1z2va0cations7na1guard7c1e0gas3ntures6risign5mögensberater2ung14sicherung10t2g1i0ajes4deo3g1king4llas4n1p1rgin4sa1ion4va1o3laanderen9n1odka3lvo3te1ing3o2yage5u2wales2mart4ter4ng0gou5tch0es6eather0channel12bcam3er2site5d0ding5ibo2r3f1hoswho6ien2ki2lliamhill9n0dows4e1ners6me2oodside6rk0s2ld3w2s1tc1f3xbox3erox4ihuan4n2xx2yz3yachts4hoo3maxun5ndex5e1odobashi7ga2kohama6u0tube6t1un3za0ppos4ra3ero3ip2m1one3uerich6w2",Ng="ελ1υ2бг1ел3дети4ею2католик6ом3мкд2он1сква6онлайн5рг3рус2ф2сайт3рб3укр3қаз3հայ3ישראל5קום3ابوظبي5رامكو5لاردن4بحرين5جزائر5سعودية6عليان5مغرب5مارات5یران5بارت2زار4يتك3ھارت5تونس4سودان3رية5شبكة4عراق2ب2مان4فلسطين6قطر3كاثوليك6وم3مصر2ليسيا5وريتانيا7قع4همراه5پاکستان7ڀارت4कॉम3नेट3भारत0म्3ोत5संगठन5বাংলা5ভারত2ৰত4ਭਾਰਤ4ભારત4ଭାରତ4இந்தியா6லங்கை6சிங்கப்பூர்11భారత్5ಭಾರತ4ഭാരതം5ලංකා4คอม3ไทย3ລາວ3გე2みんな3アマゾン4クラウド4グーグル4コム2ストア3セール3ファッション6ポイント4世界2中信1国1國1文网3亚马逊3企业2佛山2信息2健康2八卦2公司1益2台湾1灣2商城1店1标2嘉里0大酒店5在线2大拿2天主教3娱乐2家電2广东2微博2慈善2我爱你3手机2招聘2政务1府2新加坡2闻2时尚2書籍2机构2淡马锡3游戏2澳門2点看2移动2组织机构4网址1店1站1络2联通2谷歌2购物2通販2集团2電訊盈科4飞利浦3食品2餐厅2香格里拉3港2닷넷1컴2삼성2한국2",Yi="numeric",Xi="ascii",Qi="alpha",an="asciinumeric",tn="alphanumeric",Zi="domain",Hc="emoji",Dg="scheme",Ig="slashscheme",Si="whitespace";function Rg(n,e){return n in e||(e[n]=[]),e[n]}function pt(n,e,t){e[Yi]&&(e[an]=!0,e[tn]=!0),e[Xi]&&(e[an]=!0,e[Qi]=!0),e[an]&&(e[tn]=!0),e[Qi]&&(e[tn]=!0),e[tn]&&(e[Zi]=!0),e[Hc]&&(e[Zi]=!0);for(const r in e){const i=Rg(r,t);i.indexOf(n)<0&&i.push(n)}}function Lg(n,e){const t={};for(const r in e)e[r].indexOf(n)>=0&&(t[r]=!0);return t}function ce(n=null){this.j={},this.jr=[],this.jd=null,this.t=n}ce.groups={};ce.prototype={accepts(){return!!this.t},go(n){const e=this,t=e.j[n];if(t)return t;for(let r=0;rn.ta(e,t,r,i),V=(n,e,t,r,i)=>n.tr(e,t,r,i),ol=(n,e,t,r,i)=>n.ts(e,t,r,i),k=(n,e,t,r,i)=>n.tt(e,t,r,i),Le="WORD",es="UWORD",jc="ASCIINUMERICAL",Wc="ALPHANUMERICAL",vn="LOCALHOST",ts="TLD",ns="UTLD",Yn="SCHEME",Pt="SLASH_SCHEME",As="NUM",rs="WS",Os="NL",cn="OPENBRACE",un="CLOSEBRACE",ur="OPENBRACKET",dr="CLOSEBRACKET",fr="OPENPAREN",hr="CLOSEPAREN",pr="OPENANGLEBRACKET",mr="CLOSEANGLEBRACKET",gr="FULLWIDTHLEFTPAREN",yr="FULLWIDTHRIGHTPAREN",br="LEFTCORNERBRACKET",kr="RIGHTCORNERBRACKET",Sr="LEFTWHITECORNERBRACKET",xr="RIGHTWHITECORNERBRACKET",wr="FULLWIDTHLESSTHAN",Cr="FULLWIDTHGREATERTHAN",Mr="AMPERSAND",vr="APOSTROPHE",Er="ASTERISK",qe="AT",Tr="BACKSLASH",Ar="BACKTICK",Or="CARET",mt="COLON",Ns="COMMA",Nr="DOLLAR",Ee="DOT",Dr="EQUALS",Ds="EXCLAMATION",ye="HYPHEN",dn="PERCENT",Ir="PIPE",Rr="PLUS",Lr="POUND",fn="QUERY",Is="QUOTE",Kc="FULLWIDTHMIDDLEDOT",Rs="SEMI",Te="SLASH",hn="TILDE",Pr="UNDERSCORE",_c="EMOJI",Br="SYM";var Uc=Object.freeze({__proto__:null,ALPHANUMERICAL:Wc,AMPERSAND:Mr,APOSTROPHE:vr,ASCIINUMERICAL:jc,ASTERISK:Er,AT:qe,BACKSLASH:Tr,BACKTICK:Ar,CARET:Or,CLOSEANGLEBRACKET:mr,CLOSEBRACE:un,CLOSEBRACKET:dr,CLOSEPAREN:hr,COLON:mt,COMMA:Ns,DOLLAR:Nr,DOT:Ee,EMOJI:_c,EQUALS:Dr,EXCLAMATION:Ds,FULLWIDTHGREATERTHAN:Cr,FULLWIDTHLEFTPAREN:gr,FULLWIDTHLESSTHAN:wr,FULLWIDTHMIDDLEDOT:Kc,FULLWIDTHRIGHTPAREN:yr,HYPHEN:ye,LEFTCORNERBRACKET:br,LEFTWHITECORNERBRACKET:Sr,LOCALHOST:vn,NL:Os,NUM:As,OPENANGLEBRACKET:pr,OPENBRACE:cn,OPENBRACKET:ur,OPENPAREN:fr,PERCENT:dn,PIPE:Ir,PLUS:Rr,POUND:Lr,QUERY:fn,QUOTE:Is,RIGHTCORNERBRACKET:kr,RIGHTWHITECORNERBRACKET:xr,SCHEME:Yn,SEMI:Rs,SLASH:Te,SLASH_SCHEME:Pt,SYM:Br,TILDE:hn,TLD:ts,UNDERSCORE:Pr,UTLD:ns,UWORD:es,WORD:Le,WS:rs});const De=/[a-z]/,Yt=/\p{L}/u,xi=/\p{Emoji}/u,Ie=/\d/,wi=/\s/,ll="\r",Ci=` -`,Pg="️",Bg="‍",Mi="";let Vn=null,Hn=null;function zg(n=[]){const e={};ce.groups=e;const t=new ce;Vn==null&&(Vn=al(Og)),Hn==null&&(Hn=al(Ng)),k(t,"'",vr),k(t,"{",cn),k(t,"}",un),k(t,"[",ur),k(t,"]",dr),k(t,"(",fr),k(t,")",hr),k(t,"<",pr),k(t,">",mr),k(t,"(",gr),k(t,")",yr),k(t,"「",br),k(t,"」",kr),k(t,"『",Sr),k(t,"』",xr),k(t,"<",wr),k(t,">",Cr),k(t,"&",Mr),k(t,"*",Er),k(t,"@",qe),k(t,"`",Ar),k(t,"^",Or),k(t,":",mt),k(t,",",Ns),k(t,"$",Nr),k(t,".",Ee),k(t,"=",Dr),k(t,"!",Ds),k(t,"-",ye),k(t,"%",dn),k(t,"|",Ir),k(t,"+",Rr),k(t,"#",Lr),k(t,"?",fn),k(t,'"',Is),k(t,"/",Te),k(t,";",Rs),k(t,"~",hn),k(t,"_",Pr),k(t,"\\",Tr),k(t,"・",Kc);const r=V(t,Ie,As,{[Yi]:!0});V(r,Ie,r);const i=V(r,De,jc,{[an]:!0}),s=V(r,Yt,Wc,{[tn]:!0}),o=V(t,De,Le,{[Xi]:!0});V(o,Ie,i),V(o,De,o),V(i,Ie,i),V(i,De,i);const l=V(t,Yt,es,{[Qi]:!0});V(l,De),V(l,Ie,s),V(l,Yt,l),V(s,Ie,s),V(s,De),V(s,Yt,s);const a=k(t,Ci,Os,{[Si]:!0}),c=k(t,ll,rs,{[Si]:!0}),u=V(t,wi,rs,{[Si]:!0});k(t,Mi,u),k(c,Ci,a),k(c,Mi,u),V(c,wi,u),k(u,ll),k(u,Ci),V(u,wi,u),k(u,Mi,u);const d=V(t,xi,_c,{[Hc]:!0});k(d,"#"),V(d,xi,d),k(d,Pg,d);const f=k(d,Bg);k(f,"#"),V(f,xi,d);const h=[[De,o],[Ie,i]],p=[[De,null],[Yt,l],[Ie,s]];for(let m=0;mm[0]>g[0]?1:-1);for(let m=0;m=0?S[Zi]=!0:De.test(g)?Ie.test(g)?S[an]=!0:S[Xi]=!0:S[Yi]=!0,ol(t,g,g,S)}return ol(t,"localhost",vn,{ascii:!0}),t.jd=new ce(Br),{start:t,tokens:Object.assign({groups:e},Uc)}}function qc(n,e){const t=$g(e.replace(/[A-Z]/g,l=>l.toLowerCase())),r=t.length,i=[];let s=0,o=0;for(;o=0&&(d+=t[o].length,f++),c+=t[o].length,s+=t[o].length,o++;s-=d,o-=f,c-=d,i.push({t:u.t,v:e.slice(s-c,s),s:s-c,e:s})}return i}function $g(n){const e=[],t=n.length;let r=0;for(;r56319||r+1===t||(s=n.charCodeAt(r+1))<56320||s>57343?n[r]:n.slice(r,r+2);e.push(o),r+=o.length}return e}function We(n,e,t,r,i){let s;const o=e.length;for(let l=0;l=0;)s++;if(s>0){e.push(t.join(""));for(let o=parseInt(n.substring(r,r+s),10);o>0;o--)t.pop();r+=s}else t.push(n[r]),r++}return e}const En={defaultProtocol:"http",events:null,format:cl,formatHref:cl,nl2br:!1,tagName:"a",target:null,rel:null,validate:!0,truncate:1/0,className:null,attributes:null,ignoreTags:[],render:null};function Ls(n,e=null){let t=Object.assign({},En);n&&(t=Object.assign(t,n instanceof Ls?n.o:n));const r=t.ignoreTags,i=[];for(let s=0;st?r.substring(0,t)+"…":r},toFormattedHref(n){return n.get("formatHref",this.toHref(n.get("defaultProtocol")),this)},startIndex(){return this.tk[0].s},endIndex(){return this.tk[this.tk.length-1].e},toObject(n=En.defaultProtocol){return{type:this.t,value:this.toString(),isLink:this.isLink,href:this.toHref(n),start:this.startIndex(),end:this.endIndex()}},toFormattedObject(n){return{type:this.t,value:this.toFormattedString(n),isLink:this.isLink,href:this.toFormattedHref(n),start:this.startIndex(),end:this.endIndex()}},validate(n){return n.get("validate",this.toString(),this)},render(n){const e=this,t=this.toHref(n.get("defaultProtocol")),r=n.get("formatHref",t,this),i=n.get("tagName",t,e),s=this.toFormattedString(n),o={},l=n.get("className",t,e),a=n.get("target",t,e),c=n.get("rel",t,e),u=n.getObj("attributes",t,e),d=n.getObj("events",t,e);return o.href=r,l&&(o.class=l),a&&(o.target=a),c&&(o.rel=c),u&&Object.assign(o,u),{tagName:i,attributes:o,content:s,eventListeners:d}}};function Qr(n,e){class t extends Jc{constructor(i,s){super(i,s),this.t=n}}for(const r in e)t.prototype[r]=e[r];return t.t=n,t}const Fg=Qr("email",{isLink:!0,toHref(){return"mailto:"+this.toString()}}),ul=Qr("text"),Vg=Qr("nl"),jn=Qr("url",{isLink:!0,toHref(n=En.defaultProtocol){return this.hasProtocol()?this.v:`${n}://${this.v}`},hasProtocol(){const n=this.tk;return n.length>=2&&n[0].t!==vn&&n[1].t===mt}}),ge=n=>new ce(n);function Hg({groups:n}){const e=n.domain.concat([Mr,Er,qe,Tr,Ar,Or,Nr,Dr,ye,As,dn,Ir,Rr,Lr,Te,Br,hn,Pr]),t=[vr,mt,Ns,Ee,Ds,dn,fn,Is,Rs,pr,mr,cn,un,dr,ur,fr,hr,gr,yr,br,kr,Sr,xr,wr,Cr],r=[Mr,vr,Er,Tr,Ar,Or,Nr,Dr,ye,cn,un,dn,Ir,Rr,Lr,fn,Te,Br,hn,Pr],i=ge(),s=k(i,hn);N(s,r,s),N(s,n.domain,s);const o=ge(),l=ge(),a=ge();N(i,n.domain,o),N(i,n.scheme,l),N(i,n.slashscheme,a),N(o,r,s),N(o,n.domain,o);const c=k(o,qe);k(s,qe,c),k(l,qe,c),k(a,qe,c);const u=k(s,Ee);N(u,r,s),N(u,n.domain,s);const d=ge();N(c,n.domain,d),N(d,n.domain,d);const f=k(d,Ee);N(f,n.domain,d);const h=ge(Fg);N(f,n.tld,h),N(f,n.utld,h),k(c,vn,h);const p=k(d,ye);k(p,ye,p),N(p,n.domain,d),N(h,n.domain,d),k(h,Ee,f),k(h,ye,p);const m=k(o,ye),g=k(o,Ee);k(m,ye,m),N(m,n.domain,o),N(g,r,s),N(g,n.domain,o);const y=ge(jn);N(g,n.tld,y),N(g,n.utld,y),N(y,n.domain,o),N(y,r,s),k(y,Ee,g),k(y,ye,m),k(y,qe,c);const S=k(y,mt),x=ge(jn);N(S,n.numeric,x);const C=ge(jn),I=ge();N(C,e,C),N(C,t,I),N(I,e,C),N(I,t,I),k(y,Te,C),k(x,Te,C);const F=k(l,mt),A=k(a,mt),R=k(A,Te),P=k(R,Te);N(l,n.domain,o),k(l,Ee,g),k(l,ye,m),N(a,n.domain,o),k(a,Ee,g),k(a,ye,m),N(F,n.domain,C),k(F,Te,C),k(F,fn,C),N(P,n.domain,C),N(P,e,C),k(P,Te,C);const X=[[cn,un],[ur,dr],[fr,hr],[pr,mr],[gr,yr],[br,kr],[Sr,xr],[wr,Cr]];for(let me=0;me=0&&f++,i++,u++;if(f<0)i-=u,i0&&(s.push(vi(ul,e,o)),o=[]),i-=f,u-=f;const h=d.t,p=t.slice(i-u,i);s.push(vi(h,e,p))}}return o.length>0&&s.push(vi(ul,e,o)),s}function vi(n,e,t){const r=t[0].s,i=t[t.length-1].e,s=e.slice(r,i);return new n(s,t)}const Wg=typeof console<"u"&&console&&console.warn||(()=>{}),Kg="until manual call of linkify.init(). Register all schemes and plugins before invoking linkify the first time.",z={scanner:null,parser:null,tokenQueue:[],pluginQueue:[],customSchemes:[],initialized:!1};function _g(){return ce.groups={},z.scanner=null,z.parser=null,z.tokenQueue=[],z.pluginQueue=[],z.customSchemes=[],z.initialized=!1,z}function dl(n,e=!1){if(z.initialized&&Wg(`linkifyjs: already initialized - will not register custom scheme "${n}" ${Kg}`),!/^[0-9a-z]+(-[0-9a-z]+)*$/.test(n))throw new Error(`linkifyjs: incorrect scheme format. +`,parseMarkdown:()=>({type:"hardBreak"}),addCommands(){return{setHardBreak:()=>({commands:n,chain:e,state:t,editor:r})=>n.first([()=>n.exitCode(),()=>n.command(()=>{const{selection:i,storedMarks:s}=t;if(i.$from.parent.type.spec.isolating)return!1;const{keepMarks:o}=this.options,{splittableMarks:l}=r.extensionManager,a=s||i.$to.parentOffset&&i.$from.marks();return e().insertContent({type:this.name}).command(({tr:c,dispatch:u})=>{if(u&&a&&o){const d=a.filter(f=>l.includes(f.type.name));c.ensureMarks(d)}return!0}).scrollIntoView().run()})])}},addKeyboardShortcuts(){return{"Mod-Enter":()=>this.editor.commands.setHardBreak(),"Shift-Enter":()=>this.editor.commands.setHardBreak()}}}),Cb=_.create({name:"heading",addOptions(){return{levels:[1,2,3,4,5,6],HTMLAttributes:{}}},content:"inline*",group:"block",defining:!0,addAttributes(){return{level:{default:1,rendered:!1}}},parseHTML(){return this.options.levels.map(n=>({tag:`h${n}`,attrs:{level:n}}))},renderHTML({node:n,HTMLAttributes:e}){return[`h${this.options.levels.includes(n.attrs.level)?n.attrs.level:this.options.levels[0]}`,H(this.options.HTMLAttributes,e),0]},parseMarkdown:(n,e)=>e.createNode("heading",{level:n.depth||1},e.parseInline(n.tokens||[])),renderMarkdown:(n,e)=>{var t;const r=!((t=n.attrs)===null||t===void 0)&&t.level?parseInt(n.attrs.level,10):1,i="#".repeat(r);return n.content?`${i} ${e.renderChildren(n.content)}`:""},addCommands(){return{setHeading:n=>({commands:e})=>this.options.levels.includes(n.level)?e.setNode(this.name,n):!1,toggleHeading:n=>({commands:e})=>this.options.levels.includes(n.level)?e.toggleNode(this.name,"paragraph",n):!1}},addKeyboardShortcuts(){return this.options.levels.reduce((n,e)=>({...n,[`Mod-Alt-${e}`]:()=>this.editor.commands.toggleHeading({level:e})}),{})},addInputRules(){return this.options.levels.map(n=>vs({find:new RegExp(`^(#{${Math.min(...this.options.levels)},${n}})\\s$`),type:this.type,getAttributes:{level:n}}))}}),xb=_.create({name:"horizontalRule",addOptions(){return{HTMLAttributes:{},nextNodeType:"paragraph"}},group:"block",parseHTML(){return[{tag:"hr"}]},renderHTML({HTMLAttributes:n}){return["hr",H(this.options.HTMLAttributes,n)]},markdownTokenName:"hr",parseMarkdown:(n,e)=>e.createNode("horizontalRule"),renderMarkdown:()=>"---",addCommands(){return{setHorizontalRule:()=>({chain:n,state:e})=>{if(!ly(e,e.schema.nodes[this.name]))return!1;const{selection:t}=e,{$to:r}=t,i=n();return Nu(t)?i.insertContentAt(r.pos,{type:this.name}):i.insertContent({type:this.name}),i.command(({state:s,tr:o,dispatch:l})=>{if(l){const{$to:a}=o.selection,c=a.end();if(a.nodeAfter)a.nodeAfter.isTextblock?o.setSelection(v.create(o.doc,a.pos+1)):a.nodeAfter.isBlock?o.setSelection(T.create(o.doc,a.pos)):o.setSelection(v.create(o.doc,a.pos));else{const u=s.schema.nodes[this.options.nextNodeType]||a.parent.type.contentMatch.defaultType,d=u?.create();d&&(o.insert(c,d),o.setSelection(v.create(o.doc,c+1)))}o.scrollIntoView()}return!0}).run()}}},addInputRules(){return[Wu({find:/^(?:---|—-|___\s|\*\*\*\s)$/,type:this.type})]}}),vb=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))$/,Mb=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))/g,Tb=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))$/,Eb=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))/g,Ab=gt.create({name:"italic",addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:"em"},{tag:"i",getAttrs:n=>n.style.fontStyle!=="normal"&&null},{style:"font-style=normal",clearMark:n=>n.type.name===this.name},{style:"font-style=italic"}]},renderHTML({HTMLAttributes:n}){return["em",H(this.options.HTMLAttributes,n),0]},addCommands(){return{setItalic:()=>({commands:n})=>n.setMark(this.name),toggleItalic:()=>({commands:n})=>n.toggleMark(this.name),unsetItalic:()=>({commands:n})=>n.unsetMark(this.name)}},markdownTokenName:"em",parseMarkdown:(n,e)=>e.applyMark("italic",e.parseInline(n.tokens||[])),markdownOptions:{htmlReopen:{open:"",close:""}},renderMarkdown:(n,e)=>`*${e.renderChildren(n)}*`,addKeyboardShortcuts(){return{"Mod-i":()=>this.editor.commands.toggleItalic(),"Mod-I":()=>this.editor.commands.toggleItalic()}},addInputRules(){return[zt({find:vb,type:this.type}),zt({find:Tb,type:this.type})]},addPasteRules(){return[ft({find:Mb,type:this.type}),ft({find:Eb,type:this.type})]}}),Nb="aaa1rp3bb0ott3vie4c1le2ogado5udhabi7c0ademy5centure6ountant0s9o1tor4d0s1ult4e0g1ro2tna4f0l1rica5g0akhan5ency5i0g1rbus3force5tel5kdn3l0ibaba4pay4lfinanz6state5y2sace3tom5m0azon4ericanexpress7family11x2fam3ica3sterdam8nalytics7droid5quan4z2o0l2partments8p0le4q0uarelle8r0ab1mco4chi3my2pa2t0e3s0da2ia2sociates9t0hleta5torney7u0ction5di0ble3o3spost5thor3o0s4w0s2x0a2z0ure5ba0by2idu3namex4d1k2r0celona5laycard4s5efoot5gains6seball5ketball8uhaus5yern5b0c1t1va3cg1n2d1e0ats2uty4er2rlin4st0buy5t2f1g1h0arti5i0ble3d1ke2ng0o3o1z2j1lack0friday9ockbuster8g1omberg7ue3m0s1w2n0pparibas9o0ats3ehringer8fa2m1nd2o0k0ing5sch2tik2on4t1utique6x2r0adesco6idgestone9oadway5ker3ther5ussels7s1t1uild0ers6siness6y1zz3v1w1y1z0h3ca0b1fe2l0l1vinklein9m0era3p2non3petown5ital0one8r0avan4ds2e0er0s4s2sa1e1h1ino4t0ering5holic7ba1n1re3c1d1enter4o1rn3f0a1d2g1h0anel2nel4rity4se2t2eap3intai5ristmas6ome4urch5i0priani6rcle4sco3tadel4i0c2y3k1l0aims4eaning6ick2nic1que6othing5ud3ub0med6m1n1o0ach3des3ffee4llege4ogne5m0mbank4unity6pany2re3uter5sec4ndos3struction8ulting7tact3ractors9oking4l1p2rsica5untry4pon0s4rses6pa2r0edit0card4union9icket5own3s1uise0s6u0isinella9v1w1x1y0mru3ou3z2dad1nce3ta1e1ing3sun4y2clk3ds2e0al0er2s3gree4livery5l1oitte5ta3mocrat6ntal2ist5si0gn4v2hl2iamonds6et2gital5rect0ory7scount3ver5h2y2j1k1m1np2o0cs1tor4g1mains5t1wnload7rive4tv2ubai3pont4rban5vag2r2z2earth3t2c0o2deka3u0cation8e1g1mail3erck5nergy4gineer0ing9terprises10pson4quipment8r0icsson6ni3s0q1tate5t1u0rovision8s2vents5xchange6pert3osed4ress5traspace10fage2il1rwinds6th3mily4n0s2rm0ers5shion4t3edex3edback6rrari3ero6i0delity5o2lm2nal1nce1ial7re0stone6mdale6sh0ing5t0ness6j1k1lickr3ghts4r2orist4wers5y2m1o0o0d1tball6rd1ex2sale4um3undation8x2r0ee1senius7l1ogans4ntier7tr2ujitsu5n0d2rniture7tbol5yi3ga0l0lery3o1up4me0s3p1rden4y2b0iz3d0n2e0a1nt0ing5orge5f1g0ee3h1i0ft0s3ves2ing5l0ass3e1obal2o4m0ail3bh2o1x2n1odaddy5ld0point6f2odyear5g0le4p1t1v2p1q1r0ainger5phics5tis4een3ipe3ocery4up4s1t1u0cci3ge2ide2tars5ru3w1y2hair2mburg5ngout5us3bo2dfc0bank7ealth0care8lp1sinki6re1mes5iphop4samitsu7tachi5v2k0t2m1n1ockey4ldings5iday5medepot5goods5s0ense7nda3rse3spital5t0ing5t0els3mail5use3w2r1sbc3t1u0ghes5yatt3undai7ibm2cbc2e1u2d1e0ee3fm2kano4l1m0amat4db2mo0bilien9n0c1dustries8finiti5o2g1k1stitute6urance4e4t0ernational10uit4vestments10o1piranga7q1r0ish4s0maili5t0anbul7t0au2v3jaguar4va3cb2e0ep2tzt3welry6io2ll2m0p2nj2o0bs1urg4t1y2p0morgan6rs3uegos4niper7kaufen5ddi3e0rryhotels6properties14fh2g1h1i0a1ds2m1ndle4tchen5wi3m1n1oeln3matsu5sher5p0mg2n2r0d1ed3uokgroup8w1y0oto4z2la0caixa5mborghini8er3nd0rover6xess5salle5t0ino3robe5w0yer5b1c1ds2ease3clerc5frak4gal2o2xus4gbt3i0dl2fe0insurance9style7ghting6ke2lly3mited4o2ncoln4k2ve1ing5k1lc1p2oan0s3cker3us3l1ndon4tte1o3ve3pl0financial11r1s1t0d0a3u0ndbeck6xe1ury5v1y2ma0drid4if1son4keup4n0agement7go3p1rket0ing3s4riott5shalls7ttel5ba2c0kinsey7d1e0d0ia3et2lbourne7me1orial6n0u2rck0msd7g1h1iami3crosoft7l1ni1t2t0subishi9k1l0b1s2m0a2n1o0bi0le4da2e1i1m1nash3ey2ster5rmon3tgage6scow4to0rcycles9v0ie4p1q1r1s0d2t0n1r2u0seum3ic4v1w1x1y1z2na0b1goya4me2vy3ba2c1e0c1t0bank4flix4work5ustar5w0s2xt0direct7us4f0l2g0o2hk2i0co2ke1on3nja3ssan1y5l1o0kia3rton4w0ruz3tv4p1r0a1w2tt2u1yc2z2obi1server7ffice5kinawa6layan0group9lo3m0ega4ne1g1l0ine5oo2pen3racle3nge4g0anic5igins6saka4tsuka4t2vh3pa0ge2nasonic7ris2s1tners4s1y3y2ccw3e0t2f0izer5g1h0armacy6d1ilips5one2to0graphy6s4ysio5ics1tet2ures6d1n0g1k2oneer5zza4k1l0ace2y0station9umbing5s3m1n0c2ohl2ker3litie5rn2st3r0axi3ess3ime3o0d0uctions8f1gressive8mo2perties3y5tection8u0dential9s1t1ub2w0c2y2qa1pon3uebec3st5racing4dio4e0ad1lestate6tor2y4cipes5d0umbrella9hab3ise0n3t2liance6n0t0als5pair3ort3ublican8st0aurant8view0s5xroth6ich0ardli6oh3l1o1p2o0cks3deo3gers4om3s0vp3u0gby3hr2n2w0e2yukyu6sa0arland6fe0ty4kura4le1on3msclub4ung5ndvik0coromant12ofi4p1rl2s1ve2xo3b0i1s2c0b1haeffler7midt4olarships8ol3ule3warz5ience5ot3d1e0arch3t2cure1ity6ek2lect4ner3rvices6ven3w1x0y3fr2g1h0angrila6rp3ell3ia1ksha5oes2p0ping5uji3w3i0lk2na1gles5te3j1k0i0n2y0pe4l0ing4m0art3ile4n0cf3o0ccer3ial4ftbank4ware6hu2lar2utions7ng1y2y2pa0ce3ort2t3r0l2s1t0ada2ples4r1tebank4farm7c0group6ockholm6rage3e3ream4udio2y3yle4u0cks3pplies3y2ort5rf1gery5zuki5v1watch4iss4x1y0dney4stems6z2tab1ipei4lk2obao4rget4tamotors6r2too4x0i3c0i2d0k2eam2ch0nology8l1masek5nnis4va3f1g1h0d1eater2re6iaa2ckets5enda4ps2res2ol4j0maxx4x2k0maxx5l1m0all4n1o0day3kyo3ols3p1ray3shiba5tal3urs3wn2yota3s3r0ade1ing4ining5vel0ers0insurance16ust3v2t1ube2i1nes3shu4v0s2w1z2ua1bank3s2g1k1nicom3versity8o2ol2ps2s1y1z2va0cations7na1guard7c1e0gas3ntures6risign5mögensberater2ung14sicherung10t2g1i0ajes4deo3g1king4llas4n1p1rgin4sa1ion4va1o3laanderen9n1odka3lvo3te1ing3o2yage5u2wales2mart4ter4ng0gou5tch0es6eather0channel12bcam3er2site5d0ding5ibo2r3f1hoswho6ien2ki2lliamhill9n0dows4e1ners6me2oodside6rk0s2ld3w2s1tc1f3xbox3erox4ihuan4n2xx2yz3yachts4hoo3maxun5ndex5e1odobashi7ga2kohama6u0tube6t1un3za0ppos4ra3ero3ip2m1one3uerich6w2",Ob="ελ1υ2бг1ел3дети4ею2католик6ом3мкд2он1сква6онлайн5рг3рус2ф2сайт3рб3укр3қаз3հայ3ישראל5קום3ابوظبي5رامكو5لاردن4بحرين5جزائر5سعودية6عليان5مغرب5مارات5یران5بارت2زار4يتك3ھارت5تونس4سودان3رية5شبكة4عراق2ب2مان4فلسطين6قطر3كاثوليك6وم3مصر2ليسيا5وريتانيا7قع4همراه5پاکستان7ڀارت4कॉम3नेट3भारत0म्3ोत5संगठन5বাংলা5ভারত2ৰত4ਭਾਰਤ4ભારત4ଭାରତ4இந்தியா6லங்கை6சிங்கப்பூர்11భారత్5ಭಾರತ4ഭാരതം5ලංකා4คอม3ไทย3ລາວ3გე2みんな3アマゾン4クラウド4グーグル4コム2ストア3セール3ファッション6ポイント4世界2中信1国1國1文网3亚马逊3企业2佛山2信息2健康2八卦2公司1益2台湾1灣2商城1店1标2嘉里0大酒店5在线2大拿2天主教3娱乐2家電2广东2微博2慈善2我爱你3手机2招聘2政务1府2新加坡2闻2时尚2書籍2机构2淡马锡3游戏2澳門2点看2移动2组织机构4网址1店1站1络2联通2谷歌2购物2通販2集团2電訊盈科4飞利浦3食品2餐厅2香格里拉3港2닷넷1컴2삼성2한국2",Ds="numeric",Is="ascii",Ls="alpha",Cn="asciinumeric",gn="alphanumeric",Ps="domain",dd="emoji",Rb="scheme",Db="slashscheme",qi="whitespace";function Ib(n,e){return n in e||(e[n]=[]),e[n]}function vt(n,e,t){e[Ds]&&(e[Cn]=!0,e[gn]=!0),e[Is]&&(e[Cn]=!0,e[Ls]=!0),e[Cn]&&(e[gn]=!0),e[Ls]&&(e[gn]=!0),e[gn]&&(e[Ps]=!0),e[dd]&&(e[Ps]=!0);for(const r in e){const i=Ib(r,t);i.indexOf(n)<0&&i.push(n)}}function Lb(n,e){const t={};for(const r in e)e[r].indexOf(n)>=0&&(t[r]=!0);return t}function he(n=null){this.j={},this.jr=[],this.jd=null,this.t=n}he.groups={};he.prototype={accepts(){return!!this.t},go(n){const e=this,t=e.j[n];if(t)return t;for(let r=0;rn.ta(e,t,r,i),U=(n,e,t,r,i)=>n.tr(e,t,r,i),aa=(n,e,t,r,i)=>n.ts(e,t,r,i),S=(n,e,t,r,i)=>n.tt(e,t,r,i),Ve="WORD",zs="UWORD",fd="ASCIINUMERICAL",hd="ALPHANUMERICAL",Vn="LOCALHOST",Bs="TLD",$s="UTLD",br="SCHEME",qt="SLASH_SCHEME",mo="NUM",Hs="WS",go="NL",xn="OPENBRACE",vn="CLOSEBRACE",Ir="OPENBRACKET",Lr="CLOSEBRACKET",Pr="OPENPAREN",zr="CLOSEPAREN",Br="OPENANGLEBRACKET",$r="CLOSEANGLEBRACKET",Hr="FULLWIDTHLEFTPAREN",Fr="FULLWIDTHRIGHTPAREN",Vr="LEFTCORNERBRACKET",Wr="RIGHTCORNERBRACKET",jr="LEFTWHITECORNERBRACKET",_r="RIGHTWHITECORNERBRACKET",Ur="FULLWIDTHLESSTHAN",Kr="FULLWIDTHGREATERTHAN",qr="AMPERSAND",Jr="APOSTROPHE",Gr="ASTERISK",tt="AT",Yr="BACKSLASH",Xr="BACKTICK",Qr="CARET",Mt="COLON",yo="COMMA",Zr="DOLLAR",Re="DOT",ei="EQUALS",bo="EXCLAMATION",Se="HYPHEN",Mn="PERCENT",ti="PIPE",ni="PLUS",ri="POUND",Tn="QUERY",ko="QUOTE",pd="FULLWIDTHMIDDLEDOT",wo="SEMI",De="SLASH",En="TILDE",ii="UNDERSCORE",md="EMOJI",si="SYM";var gd=Object.freeze({__proto__:null,ALPHANUMERICAL:hd,AMPERSAND:qr,APOSTROPHE:Jr,ASCIINUMERICAL:fd,ASTERISK:Gr,AT:tt,BACKSLASH:Yr,BACKTICK:Xr,CARET:Qr,CLOSEANGLEBRACKET:$r,CLOSEBRACE:vn,CLOSEBRACKET:Lr,CLOSEPAREN:zr,COLON:Mt,COMMA:yo,DOLLAR:Zr,DOT:Re,EMOJI:md,EQUALS:ei,EXCLAMATION:bo,FULLWIDTHGREATERTHAN:Kr,FULLWIDTHLEFTPAREN:Hr,FULLWIDTHLESSTHAN:Ur,FULLWIDTHMIDDLEDOT:pd,FULLWIDTHRIGHTPAREN:Fr,HYPHEN:Se,LEFTCORNERBRACKET:Vr,LEFTWHITECORNERBRACKET:jr,LOCALHOST:Vn,NL:go,NUM:mo,OPENANGLEBRACKET:Br,OPENBRACE:xn,OPENBRACKET:Ir,OPENPAREN:Pr,PERCENT:Mn,PIPE:ti,PLUS:ni,POUND:ri,QUERY:Tn,QUOTE:ko,RIGHTCORNERBRACKET:Wr,RIGHTWHITECORNERBRACKET:_r,SCHEME:br,SEMI:wo,SLASH:De,SLASH_SCHEME:qt,SYM:si,TILDE:En,TLD:Bs,UNDERSCORE:ii,UTLD:$s,UWORD:zs,WORD:Ve,WS:Hs});const Be=/[a-z]/,un=/\p{L}/u,Ji=/\p{Emoji}/u,$e=/\d/,Gi=/\s/,ca="\r",Yi=` +`,Pb="️",zb="‍",Xi="";let or=null,lr=null;function Bb(n=[]){const e={};he.groups=e;const t=new he;or==null&&(or=ua(Nb)),lr==null&&(lr=ua(Ob)),S(t,"'",Jr),S(t,"{",xn),S(t,"}",vn),S(t,"[",Ir),S(t,"]",Lr),S(t,"(",Pr),S(t,")",zr),S(t,"<",Br),S(t,">",$r),S(t,"(",Hr),S(t,")",Fr),S(t,"「",Vr),S(t,"」",Wr),S(t,"『",jr),S(t,"』",_r),S(t,"<",Ur),S(t,">",Kr),S(t,"&",qr),S(t,"*",Gr),S(t,"@",tt),S(t,"`",Xr),S(t,"^",Qr),S(t,":",Mt),S(t,",",yo),S(t,"$",Zr),S(t,".",Re),S(t,"=",ei),S(t,"!",bo),S(t,"-",Se),S(t,"%",Mn),S(t,"|",ti),S(t,"+",ni),S(t,"#",ri),S(t,"?",Tn),S(t,'"',ko),S(t,"/",De),S(t,";",wo),S(t,"~",En),S(t,"_",ii),S(t,"\\",Yr),S(t,"・",pd);const r=U(t,$e,mo,{[Ds]:!0});U(r,$e,r);const i=U(r,Be,fd,{[Cn]:!0}),s=U(r,un,hd,{[gn]:!0}),o=U(t,Be,Ve,{[Is]:!0});U(o,$e,i),U(o,Be,o),U(i,$e,i),U(i,Be,i);const l=U(t,un,zs,{[Ls]:!0});U(l,Be),U(l,$e,s),U(l,un,l),U(s,$e,s),U(s,Be),U(s,un,s);const a=S(t,Yi,go,{[qi]:!0}),c=S(t,ca,Hs,{[qi]:!0}),u=U(t,Gi,Hs,{[qi]:!0});S(t,Xi,u),S(c,Yi,a),S(c,Xi,u),U(c,Gi,u),S(u,ca),S(u,Yi),U(u,Gi,u),S(u,Xi,u);const d=U(t,Ji,md,{[dd]:!0});S(d,"#"),U(d,Ji,d),S(d,Pb,d);const f=S(d,zb);S(f,"#"),U(f,Ji,d);const h=[[Be,o],[$e,i]],p=[[Be,null],[un,l],[$e,s]];for(let m=0;mm[0]>g[0]?1:-1);for(let m=0;m=0?k[Ps]=!0:Be.test(g)?$e.test(g)?k[Cn]=!0:k[Is]=!0:k[Ds]=!0,aa(t,g,g,k)}return aa(t,"localhost",Vn,{ascii:!0}),t.jd=new he(si),{start:t,tokens:Object.assign({groups:e},gd)}}function yd(n,e){const t=$b(e.replace(/[A-Z]/g,l=>l.toLowerCase())),r=t.length,i=[];let s=0,o=0;for(;o=0&&(d+=t[o].length,f++),c+=t[o].length,s+=t[o].length,o++;s-=d,o-=f,c-=d,i.push({t:u.t,v:e.slice(s-c,s),s:s-c,e:s})}return i}function $b(n){const e=[],t=n.length;let r=0;for(;r56319||r+1===t||(s=n.charCodeAt(r+1))<56320||s>57343?n[r]:n.slice(r,r+2);e.push(o),r+=o.length}return e}function Xe(n,e,t,r,i){let s;const o=e.length;for(let l=0;l=0;)s++;if(s>0){e.push(t.join(""));for(let o=parseInt(n.substring(r,r+s),10);o>0;o--)t.pop();r+=s}else t.push(n[r]),r++}return e}const Wn={defaultProtocol:"http",events:null,format:da,formatHref:da,nl2br:!1,tagName:"a",target:null,rel:null,validate:!0,truncate:1/0,className:null,attributes:null,ignoreTags:[],render:null};function So(n,e=null){let t=Object.assign({},Wn);n&&(t=Object.assign(t,n instanceof So?n.o:n));const r=t.ignoreTags,i=[];for(let s=0;st?r.substring(0,t)+"…":r},toFormattedHref(n){return n.get("formatHref",this.toHref(n.get("defaultProtocol")),this)},startIndex(){return this.tk[0].s},endIndex(){return this.tk[this.tk.length-1].e},toObject(n=Wn.defaultProtocol){return{type:this.t,value:this.toString(),isLink:this.isLink,href:this.toHref(n),start:this.startIndex(),end:this.endIndex()}},toFormattedObject(n){return{type:this.t,value:this.toFormattedString(n),isLink:this.isLink,href:this.toFormattedHref(n),start:this.startIndex(),end:this.endIndex()}},validate(n){return n.get("validate",this.toString(),this)},render(n){const e=this,t=this.toHref(n.get("defaultProtocol")),r=n.get("formatHref",t,this),i=n.get("tagName",t,e),s=this.toFormattedString(n),o={},l=n.get("className",t,e),a=n.get("target",t,e),c=n.get("rel",t,e),u=n.getObj("attributes",t,e),d=n.getObj("events",t,e);return o.href=r,l&&(o.class=l),a&&(o.target=a),c&&(o.rel=c),u&&Object.assign(o,u),{tagName:i,attributes:o,content:s,eventListeners:d}}};function xi(n,e){class t extends bd{constructor(i,s){super(i,s),this.t=n}}for(const r in e)t.prototype[r]=e[r];return t.t=n,t}const Hb=xi("email",{isLink:!0,toHref(){return"mailto:"+this.toString()}}),fa=xi("text"),Fb=xi("nl"),ar=xi("url",{isLink:!0,toHref(n=Wn.defaultProtocol){return this.hasProtocol()?this.v:`${n}://${this.v}`},hasProtocol(){const n=this.tk;return n.length>=2&&n[0].t!==Vn&&n[1].t===Mt}}),we=n=>new he(n);function Vb({groups:n}){const e=n.domain.concat([qr,Gr,tt,Yr,Xr,Qr,Zr,ei,Se,mo,Mn,ti,ni,ri,De,si,En,ii]),t=[Jr,Mt,yo,Re,bo,Mn,Tn,ko,wo,Br,$r,xn,vn,Lr,Ir,Pr,zr,Hr,Fr,Vr,Wr,jr,_r,Ur,Kr],r=[qr,Jr,Gr,Yr,Xr,Qr,Zr,ei,Se,xn,vn,Mn,ti,ni,ri,Tn,De,si,En,ii],i=we(),s=S(i,En);R(s,r,s),R(s,n.domain,s);const o=we(),l=we(),a=we();R(i,n.domain,o),R(i,n.scheme,l),R(i,n.slashscheme,a),R(o,r,s),R(o,n.domain,o);const c=S(o,tt);S(s,tt,c),S(l,tt,c),S(a,tt,c);const u=S(s,Re);R(u,r,s),R(u,n.domain,s);const d=we();R(c,n.domain,d),R(d,n.domain,d);const f=S(d,Re);R(f,n.domain,d);const h=we(Hb);R(f,n.tld,h),R(f,n.utld,h),S(c,Vn,h);const p=S(d,Se);S(p,Se,p),R(p,n.domain,d),R(h,n.domain,d),S(h,Re,f),S(h,Se,p);const m=S(o,Se),g=S(o,Re);S(m,Se,m),R(m,n.domain,o),R(g,r,s),R(g,n.domain,o);const y=we(ar);R(g,n.tld,y),R(g,n.utld,y),R(y,n.domain,o),R(y,r,s),S(y,Re,g),S(y,Se,m),S(y,tt,c);const k=S(y,Mt),w=we(ar);R(k,n.numeric,w);const C=we(ar),O=we();R(C,e,C),R(C,t,O),R(O,e,C),R(O,t,O),S(y,De,C),S(w,De,C);const B=S(l,Mt),E=S(a,Mt),D=S(E,De),P=S(D,De);R(l,n.domain,o),S(l,Re,g),S(l,Se,m),R(a,n.domain,o),S(a,Re,g),S(a,Se,m),R(B,n.domain,C),S(B,De,C),S(B,Tn,C),R(P,n.domain,C),R(P,e,C),S(P,De,C);const te=[[xn,vn],[Ir,Lr],[Pr,zr],[Br,$r],[Hr,Fr],[Vr,Wr],[jr,_r],[Ur,Kr]];for(let ke=0;ke=0&&f++,i++,u++;if(f<0)i-=u,i0&&(s.push(Qi(fa,e,o)),o=[]),i-=f,u-=f;const h=d.t,p=t.slice(i-u,i);s.push(Qi(h,e,p))}}return o.length>0&&s.push(Qi(fa,e,o)),s}function Qi(n,e,t){const r=t[0].s,i=t[t.length-1].e,s=e.slice(r,i);return new n(s,t)}const jb=typeof console<"u"&&console&&console.warn||(()=>{}),_b="until manual call of linkify.init(). Register all schemes and plugins before invoking linkify the first time.",V={scanner:null,parser:null,tokenQueue:[],pluginQueue:[],customSchemes:[],initialized:!1};function Ub(){return he.groups={},V.scanner=null,V.parser=null,V.tokenQueue=[],V.pluginQueue=[],V.customSchemes=[],V.initialized=!1,V}function ha(n,e=!1){if(V.initialized&&jb(`linkifyjs: already initialized - will not register custom scheme "${n}" ${_b}`),!/^[0-9a-z]+(-[0-9a-z]+)*$/.test(n))throw new Error(`linkifyjs: incorrect scheme format. 1. Must only contain digits, lowercase ASCII letters or "-" 2. Cannot start or end with "-" -3. "-" cannot repeat`);z.customSchemes.push([n,e])}function Ug(){z.scanner=zg(z.customSchemes);for(let n=0;nd.mark.type===t);if(!a.length)return;const{nodeAfter:c}=s;if(c&&a.some(d=>d.mark.isInSet(c.marks)))return;const u=n.storedMarks;n.removeMark(l,e.to,t),n.setStoredMarks(u),n.selection.empty&&n.selection.from===e.to&&n.removeStoredMark(t)}function Qg(n){return n.length===1?n[0].isLink:n.length===3&&n[1].isLink?["()","[]"].includes(n[0].value+n[2].value):!1}function Zg(n){return new $({key:new _("autolink"),appendTransaction:(e,t,r)=>{const i=e.some(a=>a.docChanged)&&!t.doc.eq(r.doc),s=e.some(a=>a.getMeta("preventAutolink"));if(!i||s)return;const{tr:o}=r,l=bc(t.doc,[...e]);if(!e.some(Rh)){const a=[];l.steps.forEach((c,u)=>{if(!(c instanceof H)||!c.slice.size)return;const d=l.mapping.slice(u+1),f=d.map(c.from,1),h=d.map(c.from+c.slice.size,-1);fu.to-c.to),a.forEach(c=>Xg(o,c,n.type))}if(Gr(l).forEach(({newRange:a})=>{const c=vp(r.doc,a,f=>f.isTextblock);let u,d;if(c.length>1)u=c[0],d=r.doc.textBetween(u.pos,u.pos+u.node.nodeSize,void 0," ");else if(c.length){const f=r.doc.textBetween(a.from,a.to," "," ");if(!Jg.test(f))return;u=c[0],d=r.doc.textBetween(u.pos,a.to,void 0," ")}if(u&&d){const f=d.split(qg).filter(Boolean);if(f.length<=0)return!1;const h=f[f.length-1],p=u.pos+d.lastIndexOf(h);if(!h)return!1;const m=Ps(h).map(g=>g.toObject(n.defaultProtocol));if(!Qg(m))return!1;m.filter(g=>g.isLink).map(g=>({...g,from:p+g.start+1,to:p+g.end+1})).filter(g=>r.schema.marks.code?!r.doc.rangeHasMark(g.from,g.to,r.schema.marks.code):!0).filter(g=>n.validate(g.value)).filter(g=>n.shouldAutoLink(g.value)).forEach(g=>{Yr(g.from,g.to,r.doc).some(y=>y.mark.type===n.type)||o.addMark(g.from,g.to,n.type.create({href:g.href}))})}}),!!o.steps.length)return o}})}function ey(n){return new $({key:new _("handleClickLink"),props:{handleClick:(e,t,r)=>{if(r.button!==0||!e.editable)return!1;let i=null;if(r.target instanceof HTMLAnchorElement)i=r.target;else{const a=r.target;if(!a)return!1;const c=n.editor.view.dom;i=a.closest("a"),i&&!c.contains(i)&&(i=null)}if(!i)return!1;let s=!1;if(n.enableClickSelection&&(s=n.editor.commands.extendMarkRange(n.type.name)),n.openOnClick){var o,l;const a=Cc(e.state,n.type.name),c=(o=i.href)!==null&&o!==void 0?o:a.href,u=(l=i.target)!==null&&l!==void 0?l:a.target;c&&(window.open(c,u),s=!0)}return s}}})}const ty=/\[([^[\]]+)\]\(((?:[^\s()]|\([^\s()]*\))+)(?:\s+(?:(["'])(.*?)\3|“(.*?)”|‘(.*?)’))?\)$/,ny=/\[([^[\]]+)\]\(((?:[^\s()]|\([^\s()]*\))+)(?:\s+(?:(["'])(.*?)\3|“(.*?)”|‘(.*?)’))?\)/g;function Yc(n,e){let t=0;for(let r=e-1;r>=0&&n[r]==="\\";r-=1)t+=1;return t%2===1}function ry(n,e){let t=0,r=0;for(;r0}function Xc(n,e,t){var r,i;const[,s,o]=e;return(e.index?n[e.index-1]:void 0)==="!"||Yc(n,(r=e.index)!==null&&r!==void 0?r:0)||ry(n,(i=e.index)!==null&&i!==void 0?i:0)?!1:!!s.trim()&&t(o)}function Qc(n){var e,t;const[r,i,s,,o,l,a]=n,c=(e=o??l)!==null&&e!==void 0?e:a;return{index:(t=n.index)!==null&&t!==void 0?t:0,text:r,replaceWith:i,data:{href:s,title:c||null,markdown:!0}}}function iy(n,e){return n.index{const r=ty.exec(t);return!r||!Xc(t,r,n.isAllowedHref)?null:Qc(r)},type:n.type,getAttributes:Zc});return new In({find:e.find,handler:t=>{const r=e.handler(t);return r!==null&&t.state.tr.steps.length&&t.state.tr.setMeta("preventAutolink",!0),r}})}function oy(n){const e=it({find:t=>{var r,i;const s=[];for(const l of t.matchAll(ny))Xc(t,l,n.isAllowedHref)&&s.push(Qc(l));const o=((r=(i=n.findPlainUrls)===null||i===void 0?void 0:i.call(n,t))!==null&&r!==void 0?r:[]).filter(l=>!s.some(a=>iy(a,l)));return[...s,...o]},type:n.type,getAttributes:Zc});return new Pc({find:e.find,handler:t=>{var r;const i=e.handler(t);return i!==null&&t.state.tr.steps.length&&(!((r=t.match.data)===null||r===void 0)&&r.markdown)&&t.state.tr.setMeta("preventAutolink",!0),i}})}function ly(n){return new $({key:new _("handlePasteLink"),props:{handlePaste:(e,t,r)=>{const{shouldAutoLink:i}=n,{state:s}=e,{selection:o}=s,{empty:l}=o;if(l)return!1;let a="";r.content.forEach(u=>{a+=u.textContent});const c=Gc(a,{defaultProtocol:n.defaultProtocol}).find(u=>u.isLink&&u.value===a);return!a||!c||i!==void 0&&!i(c.value)?!1:n.editor.commands.setMark(n.type,{href:c.href})}}})}function Re(n,e){const t=["http","https","ftp","ftps","mailto","tel","callto","sms","cid","xmpp"];return e&&e.forEach(r=>{const i=typeof r=="string"?r:r.scheme;i&&t.push(i)}),!n||n.replace(Yg,"").match(new RegExp(`^(?:(?:${t.map(r=>r.replace(/[-/\\^$*+?.()|[\]{}]/g,"\\$&")).join("|")}):|[^a-z]|[a-z0-9+.\\-]+(?:[^a-z+.\\-:]|$))`,"i"))}const ay=Et.create({name:"link",priority:1e3,keepOnSplit:!1,exitable:!0,onCreate(){this.options.validate&&!this.options.shouldAutoLink&&(this.options.shouldAutoLink=this.options.validate,console.warn("The `validate` option is deprecated. Rename to the `shouldAutoLink` option instead.")),this.options.protocols.forEach(n=>{if(typeof n=="string"){dl(n);return}dl(n.scheme,n.optionalSlashes)})},onDestroy(){_g()},inclusive(){return this.options.autolink},addOptions(){return{openOnClick:!0,enableClickSelection:!1,linkOnPaste:!0,markdownLinks:!1,autolink:!0,protocols:[],defaultProtocol:"http",HTMLAttributes:{target:"_blank",rel:"noopener noreferrer nofollow",class:null},isAllowedUri:(n,e)=>!!Re(n,e.protocols),validate:n=>!!n,shouldAutoLink:n=>{const e=/^[a-z][a-z0-9+.-]*:\/\//i.test(n),t=/^[a-z][a-z0-9+.-]*:/i.test(n);if(e||t&&!n.includes("@"))return!0;const r=(n.includes("@")?n.split("@").pop():n).split(/[/?#:]/)[0];return!(/^\d{1,3}(\.\d{1,3}){3}$/.test(r)||!/\./.test(r))}}},addAttributes(){var n,e,t;return{href:{default:null,parseHTML(r){return r.getAttribute("href")}},target:{default:(n=this.options.HTMLAttributes.target)!==null&&n!==void 0?n:null},rel:{default:(e=this.options.HTMLAttributes.rel)!==null&&e!==void 0?e:null},class:{default:(t=this.options.HTMLAttributes.class)!==null&&t!==void 0?t:null},title:{default:null}}},parseHTML(){return[{tag:"a[href]",getAttrs:n=>{const e=n.getAttribute("href");return!e||!this.options.isAllowedUri(e,{defaultValidate:t=>!!Re(t,this.options.protocols),protocols:this.options.protocols,defaultProtocol:this.options.defaultProtocol})?!1:null}}]},renderHTML({HTMLAttributes:n}){return this.options.isAllowedUri(n.href,{defaultValidate:e=>!!Re(e,this.options.protocols),protocols:this.options.protocols,defaultProtocol:this.options.defaultProtocol})?["a",J(this.options.HTMLAttributes,n),0]:["a",J(this.options.HTMLAttributes,{...n,href:""}),0]},markdownTokenName:"link",parseMarkdown:(n,e)=>e.applyMark("link",e.parseInline(n.tokens||[]),{href:n.href,title:n.title||null}),renderMarkdown:(n,e)=>{var t,r,i,s;const o=(t=(r=n.attrs)===null||r===void 0?void 0:r.href)!==null&&t!==void 0?t:"",l=(i=(s=n.attrs)===null||s===void 0?void 0:s.title)!==null&&i!==void 0?i:"",a=e.renderChildren(n);return l?`[${a}](${o} "${l}")`:`[${a}](${o})`},addCommands(){return{setLink:n=>({chain:e})=>{const{href:t}=n;return this.options.isAllowedUri(t,{defaultValidate:r=>!!Re(r,this.options.protocols),protocols:this.options.protocols,defaultProtocol:this.options.defaultProtocol})?e().setMark(this.name,n).setMeta("preventAutolink",!0).run():!1},toggleLink:n=>({chain:e})=>{const{href:t}=n||{};return t&&!this.options.isAllowedUri(t,{defaultValidate:r=>!!Re(r,this.options.protocols),protocols:this.options.protocols,defaultProtocol:this.options.defaultProtocol})?!1:e().toggleMark(this.name,n,{extendEmptyMarkRange:!0}).setMeta("preventAutolink",!0).run()},unsetLink:()=>({chain:n})=>n().unsetMark(this.name,{extendEmptyMarkRange:!0}).setMeta("preventAutolink",!0).run()}},addInputRules(){return this.options.markdownLinks?[sy({type:this.type,isAllowedHref:n=>this.options.isAllowedUri(n,{defaultValidate:e=>!!Re(e,this.options.protocols),protocols:this.options.protocols,defaultProtocol:this.options.defaultProtocol})})]:[]},addPasteRules(){const n=e=>{const t=[];if(e){const{protocols:r,defaultProtocol:i}=this.options;Gc(e).filter(s=>s.isLink&&this.options.isAllowedUri(s.value,{defaultValidate:o=>!!Re(o,r),protocols:r,defaultProtocol:i})).forEach(s=>{this.options.shouldAutoLink(s.value)&&t.push({text:s.value,data:{href:s.href},index:s.start})})}return t};return this.options.markdownLinks?[oy({type:this.type,isAllowedHref:e=>this.options.isAllowedUri(e,{defaultValidate:t=>!!Re(t,this.options.protocols),protocols:this.options.protocols,defaultProtocol:this.options.defaultProtocol}),findPlainUrls:n})]:[it({find:n,type:this.type,getAttributes:e=>{var t;return{href:(t=e.data)===null||t===void 0?void 0:t.href}}})]},addProseMirrorPlugins(){const n=[],{protocols:e,defaultProtocol:t}=this.options;return this.options.autolink&&n.push(Zg({type:this.type,defaultProtocol:this.options.defaultProtocol,validate:r=>this.options.isAllowedUri(r,{defaultValidate:i=>!!Re(i,e),protocols:e,defaultProtocol:t}),shouldAutoLink:this.options.shouldAutoLink})),n.push(ey({type:this.type,editor:this.editor,openOnClick:this.options.openOnClick==="whenNotEditable"?!0:this.options.openOnClick,enableClickSelection:this.options.enableClickSelection})),this.options.linkOnPaste&&n.push(ly({editor:this.editor,defaultProtocol:this.options.defaultProtocol,type:this.type,shouldAutoLink:this.options.shouldAutoLink})),n}}),cy="listItem",fl="textStyle",hl=/^\s*([-+*])\s$/,eu=pe.create({name:"bulletList",addOptions(){return{itemTypeName:"listItem",HTMLAttributes:{},keepMarks:!1,keepAttributes:!1}},group:"block list",content(){return`${this.options.itemTypeName}+`},parseHTML(){return[{tag:"ul"}]},renderHTML({HTMLAttributes:n}){return["ul",J(this.options.HTMLAttributes,n),0]},markdownTokenName:"list",parseMarkdown:(n,e)=>n.type!=="list"||n.ordered?[]:{type:"bulletList",content:n.items?e.parseChildren(n.items):[]},renderMarkdown:(n,e)=>n.content?e.renderChildren(n.content,` -`):"",markdownOptions:{indentsContent:!0},addCommands(){return{toggleBulletList:()=>({commands:n,chain:e})=>this.options.keepAttributes?e().toggleList(this.name,this.options.itemTypeName,this.options.keepMarks).updateAttributes(cy,this.editor.getAttributes(fl)).run():n.toggleList(this.name,this.options.itemTypeName,this.options.keepMarks)}},addKeyboardShortcuts(){return{"Mod-Shift-8":()=>this.editor.commands.toggleBulletList()}},addInputRules(){let n=_t({find:hl,type:this.type});return(this.options.keepMarks||this.options.keepAttributes)&&(n=_t({find:hl,type:this.type,keepMarks:this.options.keepMarks,keepAttributes:this.options.keepAttributes,getAttributes:()=>this.editor.getAttributes(fl),editor:this.editor})),[n]}}),uy=(n,e,t)=>{const{selection:r}=n;if(!r.empty)return null;const{$from:i}=r;if(!i.parent.isTextblock||i.parentOffset!==i.parent.content.size)return null;let s=-1;for(let h=i.depth;h>0;h-=1)if(i.node(h).type.name===e){s=h;break}if(s<0)return null;const o=i.node(s),l=i.index(s);if(l+1>=o.childCount)return null;const a=o.child(l+1);if(!t.includes(a.type.name))return null;const c=n.schema.nodes[e];let u=!1;if(a.forEach(h=>{h.type===c&&h.childCount>1&&(u=!0)}),!u)return null;const d=n.doc.resolve(i.after()).nodeAfter;if(!d||!t.includes(d.type.name))return null;const f=[];return d.forEach(h=>{f.push(h)}),f.length===0?null:{listItemDepth:s,nestedList:d,nestedListPos:i.after(),insertPos:i.after(s),items:f}},dy=(n,e,t,r)=>{const i=uy(n,t,r);if(!i)return!1;const{selection:s}=n,{nestedList:o,nestedListPos:l,insertPos:a,items:c}=i,u=n.tr;u.delete(l,l+o.nodeSize);const d=u.mapping.map(a);return u.insert(d,b.from(c)),u.setSelection(s.map(u.doc,u.mapping)),e&&e(u),!0},fy=(n,e,t)=>dy(n.state,n.view.dispatch,e,t),tu=(n,e)=>W.create({name:`${n}BranchingDeleteKeymap`,priority:101,addKeyboardShortcuts(){const t=()=>fy(this.editor,n,e);return{Delete:t,"Mod-Delete":t}}}),nu=[[1e3,"m"],[900,"cm"],[500,"d"],[400,"cd"],[100,"c"],[90,"xc"],[50,"l"],[40,"xl"],[10,"x"],[9,"ix"],[5,"v"],[4,"iv"],[1,"i"]],Wn="abcdefghijklmnopqrstuvwxyz",ru=String.raw`\d+|[ivxlcdmIVXLCDM]+|${"[a-zA-Z]{1,2}"}`;function ei(n){let e=n,t="";for(const[r,i]of nu)for(;e>=r;)t+=i,e-=r;return t}function Bs(n){return ei(n).toUpperCase()}function iu(n){const e=n.toLowerCase();let t=0,r=0;for(;t0?r:1}const t=parseInt(n,10);return Number.isNaN(t)?1:t}function my(n,e){if(n==="numeric")return String(e);switch(n){case"a":return zr(e);case"A":return zr(e).toUpperCase();case"i":return ei(e);case"I":return Bs(e);default:return String(e)}}function gy(n){var e;if(n.length===0)return!1;const t=(e=ti(n[0]))!==null&&e!==void 0?e:"numeric",r=zs(n[0]);if(r<1)return!1;for(let i=0;i{var t;if(n.type!=="list_item")return[];const r=(t=e.parseBlockChildren)!==null&&t!==void 0?t:e.parseChildren;let i=[];if(n.tokens&&n.tokens.length>0){if(Sy(n))return{type:"listItem",content:[{type:"paragraph",content:xy(n.text||"",e)}]};if(n.tokens.some(s=>s.type==="paragraph"))i=r(n.tokens);else{const s=n.tokens[0];if(s&&s.type==="text"&&s.tokens&&s.tokens.length>0){if(i=[{type:"paragraph",content:e.parseInline(s.tokens)}],n.tokens.length>1){const o=r(n.tokens.slice(1));i.push(...o)}}else i=r(n.tokens)}}return i.length===0&&(i=[{type:"paragraph",content:[]}]),{type:"listItem",content:i}},renderMarkdown:(n,e,t)=>Ic(n,e,r=>{if(r.parentType==="bulletList")return"- ";if(r.parentType==="orderedList"){var i,s;const o=((i=r.meta)===null||i===void 0||(i=i.parentAttrs)===null||i===void 0?void 0:i.start)||1;return ky((s=r.meta)===null||s===void 0||(s=s.parentAttrs)===null||s===void 0?void 0:s.type,o-1+(r.index||0),". ")}return"- "},t,{alignNestedToPrefix:t?.parentType==="orderedList"}),addExtensions(){return[tu(this.name,[this.options.bulletListTypeName,this.options.orderedListTypeName])]},addKeyboardShortcuts(){return{Enter:()=>this.editor.commands.splitListItem(this.name),Tab:()=>this.editor.commands.sinkListItem(this.name),"Shift-Tab":()=>this.editor.commands.liftListItem(this.name)}}}),$s=(n,e)=>{const{$from:t}=e.selection,r=q(n,e.schema);let i=null,s=t.depth,o=t.pos,l=null;for(;s>0&&l===null;)i=t.node(s),i.type===r?l=s:(s-=1,o-=1);return l===null?null:{$pos:e.doc.resolve(o),depth:l}},ou=(n,e)=>{const t=$s(n,e);if(!t)return!1;const[,r]=Bp(e,n,t.$pos.pos+4);return r},wy=(n,e,t)=>{const{$anchor:r}=n.selection,i=Math.max(0,r.pos-2),s=n.doc.resolve(i).node();return!(!s||!t.includes(s.type.name))},pl=(n,e,t)=>{if(n.commands.undoInputRule())return!0;if(n.state.selection.from!==n.state.selection.to)return!1;if(!He(n.state,e)&&wy(n.state,e,t)){const{$anchor:s}=n.state.selection,o=n.state.doc.resolve(s.before()-1),l=[];o.node().descendants((u,d)=>{u.type.name===e&&l.push({node:u,pos:d})});const a=l.at(-1);if(!a)return!1;const c=n.state.doc.resolve(o.start()+a.pos+1);return n.chain().cut({from:s.start()-1,to:s.end()+1},c.end()).joinForward().run()}if(!He(n.state,e)||!Hp(n.state))return!1;const{$from:r}=n.state.selection,i=r.depth-1;return r.node(i).type!==n.schema.nodes[e]||r.index(i)!==0?!1:n.chain().liftListItem(e).run()},Cy=(n,e)=>{const t=ou(n,e),r=$s(n,e);return!r||!t?!1:t>r.depth},My=(n,e)=>{const t=ou(n,e),r=$s(n,e);return!r||!t?!1:t{if(!He(n.state,e)||!Vp(n.state,e))return!1;const{selection:t}=n.state,{$from:r,$to:i}=t;return!t.empty&&r.sameParent(i)?!1:Cy(e,n.state)?n.chain().focus(n.state.selection.from+4).lift(e).joinBackward().run():My(e,n.state)?n.chain().joinForward().joinBackward().run():n.commands.joinItemForward()},vy=(n,e,t)=>{const{state:r}=n,{selection:i}=r;if(!i.empty)return!1;const{$from:s}=i;if(s.parentOffset!==0||!s.parent.isTextblock||He(r,e))return!1;const o=zp(s);if(!o||!t.includes(o.type.name))return!1;const l=o.lastChild;if(!l||l.type.name!==e)return!1;const a=s.parent;if(!l.canReplace(l.childCount,l.childCount,b.from(a)))return!1;const c=s.before(),u=s.after(),d=c-2;return n.commands.command(({tr:f,dispatch:h})=>(h&&(f.delete(c,u).insert(d,b.from(a)),f.setSelection(T.create(f.doc,d+1)),f.scrollIntoView()),!0))},lu=W.create({name:"listKeymap",addOptions(){return{listTypes:[{itemName:"listItem",wrapperNames:["bulletList","orderedList"]},{itemName:"taskItem",wrapperNames:["taskList"]}]}},addKeyboardShortcuts(){return{Delete:({editor:n})=>{let e=!1;return this.options.listTypes.forEach(({itemName:t})=>{n.state.schema.nodes[t]!==void 0&&ml(n,t)&&(e=!0)}),e},"Mod-Delete":({editor:n})=>{let e=!1;return this.options.listTypes.forEach(({itemName:t})=>{n.state.schema.nodes[t]!==void 0&&ml(n,t)&&(e=!0)}),e},Backspace:({editor:n})=>{let e=!1;return this.options.listTypes.forEach(({itemName:t,wrapperNames:r})=>{n.state.schema.nodes[t]!==void 0&&pl(n,t,r)&&(e=!0)}),e},"Mod-Backspace":({editor:n})=>{let e=!1;return this.options.listTypes.forEach(({itemName:t,wrapperNames:r})=>{n.state.schema.nodes[t]!==void 0&&pl(n,t,r)&&(e=!0)}),e},Tab:({editor:n})=>{for(const{itemName:e,wrapperNames:t}of this.options.listTypes)if(n.state.schema.nodes[e]!==void 0&&vy(n,e,t))return!0;return!1}}}}),$r=new RegExp(`^(\\s*)(${ru})([.)])\\s+(.*)$`),Ey=/^\s/,Bt={heading:/^#{1,6}(?:\s|$)/,bulletItem:/^[-+*]\s+/,codeFence:/^(?:```|~~~)/,blockMath:/^\$\$/,thematicBreak:/^(?:(?:-[ \t]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})$/};function Ty(n){return $r.test(n.trimStart())}function Ay(n){const e=n.trimStart();return Bt.bulletItem.test(e)||Ty(e)||Bt.heading.test(e)||Bt.thematicBreak.test(e)&&!e.startsWith("-")||/^>\s?/.test(e)||Bt.codeFence.test(e)||Bt.blockMath.test(e)}function Oy(n){return Object.values(Bt).some(e=>e.test(n))}function Ny(n){const e=[],t=[];let r=!1;return n.forEach(i=>{if(r){t.push(i);return}if(i.trim()===""){r=!0,t.push(i);return}if(e.length>0&&Ay(i)){r=!0,t.push(i);return}e.push(i)}),{paragraphLines:e,blockLines:t}}function gl(n){const e=[];let t=0,r=0;for(;td.mark.type===t);if(!a.length)return;const{nodeAfter:c}=s;if(c&&a.some(d=>d.mark.isInSet(c.marks)))return;const u=n.storedMarks;n.removeMark(l,e.to,t),n.setStoredMarks(u),n.selection.empty&&n.selection.from===e.to&&n.removeStoredMark(t)}function Qb(n){return n.length===1?n[0].isLink:n.length===3&&n[1].isLink?["()","[]"].includes(n[0].value+n[2].value):!1}function Zb(n){return new z({key:new W("autolink"),appendTransaction:(e,t,r)=>{const i=e.some(a=>a.docChanged)&&!t.doc.eq(r.doc),s=e.some(a=>a.getMeta("preventAutolink"));if(!i||s)return;const{tr:o}=r,l=xu(t.doc,[...e]);if(!e.some(hm)){const a=[];l.steps.forEach((c,u)=>{if(!(c instanceof K)||!c.slice.size)return;const d=l.mapping.slice(u+1),f=d.map(c.from,1),h=d.map(c.from+c.slice.size,-1);fu.to-c.to),a.forEach(c=>Xb(o,c,n.type))}if(ki(l).forEach(({newRange:a})=>{const c=sg(r.doc,a,f=>f.isTextblock);let u,d;if(c.length>1)u=c[0],d=r.doc.textBetween(u.pos,u.pos+u.node.nodeSize,void 0," ");else if(c.length){const f=r.doc.textBetween(a.from,a.to," "," ");if(!Jb.test(f))return;u=c[0],d=r.doc.textBetween(u.pos,a.to,void 0," ")}if(u&&d){const f=d.split(qb).filter(Boolean);if(f.length<=0)return!1;const h=f[f.length-1],p=u.pos+d.lastIndexOf(h);if(!h)return!1;const m=Co(h).map(g=>g.toObject(n.defaultProtocol));if(!Qb(m))return!1;m.filter(g=>g.isLink).map(g=>({...g,from:p+g.start+1,to:p+g.end+1})).filter(g=>r.schema.marks.code?!r.doc.rangeHasMark(g.from,g.to,r.schema.marks.code):!0).filter(g=>n.validate(g.value)).filter(g=>n.shouldAutoLink(g.value)).forEach(g=>{wi(g.from,g.to,r.doc).some(y=>y.mark.type===n.type)||o.addMark(g.from,g.to,n.type.create({href:g.href}))})}}),!!o.steps.length)return o}})}function ek(n){return new z({key:new W("handleClickLink"),props:{handleClick:(e,t,r)=>{if(r.button!==0||!e.editable)return!1;let i=null;if(r.target instanceof HTMLAnchorElement)i=r.target;else{const a=r.target;if(!a)return!1;const c=n.editor.view.dom;i=a.closest("a"),i&&!c.contains(i)&&(i=null)}if(!i)return!1;let s=!1;if(n.enableClickSelection&&(s=n.editor.commands.extendMarkRange(n.type.name)),n.openOnClick){var o,l;const a=Au(e.state,n.type.name),c=(o=i.href)!==null&&o!==void 0?o:a.href,u=(l=i.target)!==null&&l!==void 0?l:a.target;c&&(window.open(c,u),s=!0)}return s}}})}const tk=/\[([^[\]]+)\]\(((?:[^\s()]|\([^\s()]*\))+)(?:\s+(?:(["'])(.*?)\3|“(.*?)”|‘(.*?)’))?\)$/,nk=/\[([^[\]]+)\]\(((?:[^\s()]|\([^\s()]*\))+)(?:\s+(?:(["'])(.*?)\3|“(.*?)”|‘(.*?)’))?\)/g;function wd(n,e){let t=0;for(let r=e-1;r>=0&&n[r]==="\\";r-=1)t+=1;return t%2===1}function rk(n,e){let t=0,r=0;for(;r0}function Sd(n,e,t){var r,i;const[,s,o]=e;return(e.index?n[e.index-1]:void 0)==="!"||wd(n,(r=e.index)!==null&&r!==void 0?r:0)||rk(n,(i=e.index)!==null&&i!==void 0?i:0)?!1:!!s.trim()&&t(o)}function Cd(n){var e,t;const[r,i,s,,o,l,a]=n,c=(e=o??l)!==null&&e!==void 0?e:a;return{index:(t=n.index)!==null&&t!==void 0?t:0,text:r,replaceWith:i,data:{href:s,title:c||null,markdown:!0}}}function ik(n,e){return n.index{const r=tk.exec(t);return!r||!Sd(t,r,n.isAllowedHref)?null:Cd(r)},type:n.type,getAttributes:xd});return new Gn({find:e.find,handler:t=>{const r=e.handler(t);return r!==null&&t.state.tr.steps.length&&t.state.tr.setMeta("preventAutolink",!0),r}})}function ok(n){const e=ft({find:t=>{var r,i;const s=[];for(const l of t.matchAll(nk))Sd(t,l,n.isAllowedHref)&&s.push(Cd(l));const o=((r=(i=n.findPlainUrls)===null||i===void 0?void 0:i.call(n,t))!==null&&r!==void 0?r:[]).filter(l=>!s.some(a=>ik(a,l)));return[...s,...o]},type:n.type,getAttributes:xd});return new Fu({find:e.find,handler:t=>{var r;const i=e.handler(t);return i!==null&&t.state.tr.steps.length&&(!((r=t.match.data)===null||r===void 0)&&r.markdown)&&t.state.tr.setMeta("preventAutolink",!0),i}})}function lk(n){return new z({key:new W("handlePasteLink"),props:{handlePaste:(e,t,r)=>{const{shouldAutoLink:i}=n,{state:s}=e,{selection:o}=s,{empty:l}=o;if(l)return!1;let a="";r.content.forEach(u=>{a+=u.textContent});const c=kd(a,{defaultProtocol:n.defaultProtocol}).find(u=>u.isLink&&u.value===a);return!a||!c||i!==void 0&&!i(c.value)?!1:n.editor.commands.setMark(n.type,{href:c.href})}}})}function He(n,e){const t=["http","https","ftp","ftps","mailto","tel","callto","sms","cid","xmpp"];return e&&e.forEach(r=>{const i=typeof r=="string"?r:r.scheme;i&&t.push(i)}),!n||n.replace(Yb,"").match(new RegExp(`^(?:(?:${t.map(r=>r.replace(/[-/\\^$*+?.()|[\]{}]/g,"\\$&")).join("|")}):|[^a-z]|[a-z0-9+.\\-]+(?:[^a-z+.\\-:]|$))`,"i"))}const ak=gt.create({name:"link",priority:1e3,keepOnSplit:!1,exitable:!0,onCreate(){this.options.validate&&!this.options.shouldAutoLink&&(this.options.shouldAutoLink=this.options.validate,console.warn("The `validate` option is deprecated. Rename to the `shouldAutoLink` option instead.")),this.options.protocols.forEach(n=>{if(typeof n=="string"){ha(n);return}ha(n.scheme,n.optionalSlashes)})},onDestroy(){Ub()},inclusive(){return this.options.autolink},addOptions(){return{openOnClick:!0,enableClickSelection:!1,linkOnPaste:!0,markdownLinks:!1,autolink:!0,protocols:[],defaultProtocol:"http",HTMLAttributes:{target:"_blank",rel:"noopener noreferrer nofollow",class:null},isAllowedUri:(n,e)=>!!He(n,e.protocols),validate:n=>!!n,shouldAutoLink:n=>{const e=/^[a-z][a-z0-9+.-]*:\/\//i.test(n),t=/^[a-z][a-z0-9+.-]*:/i.test(n);if(e||t&&!n.includes("@"))return!0;const r=(n.includes("@")?n.split("@").pop():n).split(/[/?#:]/)[0];return!(/^\d{1,3}(\.\d{1,3}){3}$/.test(r)||!/\./.test(r))}}},addAttributes(){var n,e,t;return{href:{default:null,parseHTML(r){return r.getAttribute("href")}},target:{default:(n=this.options.HTMLAttributes.target)!==null&&n!==void 0?n:null},rel:{default:(e=this.options.HTMLAttributes.rel)!==null&&e!==void 0?e:null},class:{default:(t=this.options.HTMLAttributes.class)!==null&&t!==void 0?t:null},title:{default:null}}},parseHTML(){return[{tag:"a[href]",getAttrs:n=>{const e=n.getAttribute("href");return!e||!this.options.isAllowedUri(e,{defaultValidate:t=>!!He(t,this.options.protocols),protocols:this.options.protocols,defaultProtocol:this.options.defaultProtocol})?!1:null}}]},renderHTML({HTMLAttributes:n}){return this.options.isAllowedUri(n.href,{defaultValidate:e=>!!He(e,this.options.protocols),protocols:this.options.protocols,defaultProtocol:this.options.defaultProtocol})?["a",H(this.options.HTMLAttributes,n),0]:["a",H(this.options.HTMLAttributes,{...n,href:""}),0]},markdownTokenName:"link",parseMarkdown:(n,e)=>e.applyMark("link",e.parseInline(n.tokens||[]),{href:n.href,title:n.title||null}),renderMarkdown:(n,e)=>{var t,r,i,s;const o=(t=(r=n.attrs)===null||r===void 0?void 0:r.href)!==null&&t!==void 0?t:"",l=(i=(s=n.attrs)===null||s===void 0?void 0:s.title)!==null&&i!==void 0?i:"",a=e.renderChildren(n);return l?`[${a}](${o} "${l}")`:`[${a}](${o})`},addCommands(){return{setLink:n=>({chain:e})=>{const{href:t}=n;return this.options.isAllowedUri(t,{defaultValidate:r=>!!He(r,this.options.protocols),protocols:this.options.protocols,defaultProtocol:this.options.defaultProtocol})?e().setMark(this.name,n).setMeta("preventAutolink",!0).run():!1},toggleLink:n=>({chain:e})=>{const{href:t}=n||{};return t&&!this.options.isAllowedUri(t,{defaultValidate:r=>!!He(r,this.options.protocols),protocols:this.options.protocols,defaultProtocol:this.options.defaultProtocol})?!1:e().toggleMark(this.name,n,{extendEmptyMarkRange:!0}).setMeta("preventAutolink",!0).run()},unsetLink:()=>({chain:n})=>n().unsetMark(this.name,{extendEmptyMarkRange:!0}).setMeta("preventAutolink",!0).run()}},addInputRules(){return this.options.markdownLinks?[sk({type:this.type,isAllowedHref:n=>this.options.isAllowedUri(n,{defaultValidate:e=>!!He(e,this.options.protocols),protocols:this.options.protocols,defaultProtocol:this.options.defaultProtocol})})]:[]},addPasteRules(){const n=e=>{const t=[];if(e){const{protocols:r,defaultProtocol:i}=this.options;kd(e).filter(s=>s.isLink&&this.options.isAllowedUri(s.value,{defaultValidate:o=>!!He(o,r),protocols:r,defaultProtocol:i})).forEach(s=>{this.options.shouldAutoLink(s.value)&&t.push({text:s.value,data:{href:s.href},index:s.start})})}return t};return this.options.markdownLinks?[ok({type:this.type,isAllowedHref:e=>this.options.isAllowedUri(e,{defaultValidate:t=>!!He(t,this.options.protocols),protocols:this.options.protocols,defaultProtocol:this.options.defaultProtocol}),findPlainUrls:n})]:[ft({find:n,type:this.type,getAttributes:e=>{var t;return{href:(t=e.data)===null||t===void 0?void 0:t.href}}})]},addProseMirrorPlugins(){const n=[],{protocols:e,defaultProtocol:t}=this.options;return this.options.autolink&&n.push(Zb({type:this.type,defaultProtocol:this.options.defaultProtocol,validate:r=>this.options.isAllowedUri(r,{defaultValidate:i=>!!He(i,e),protocols:e,defaultProtocol:t}),shouldAutoLink:this.options.shouldAutoLink})),n.push(ek({type:this.type,editor:this.editor,openOnClick:this.options.openOnClick==="whenNotEditable"?!0:this.options.openOnClick,enableClickSelection:this.options.enableClickSelection})),this.options.linkOnPaste&&n.push(lk({editor:this.editor,defaultProtocol:this.options.defaultProtocol,type:this.type,shouldAutoLink:this.options.shouldAutoLink})),n}}),ck="listItem",pa="textStyle",ma=/^\s*([-+*])\s$/,vd=_.create({name:"bulletList",addOptions(){return{itemTypeName:"listItem",HTMLAttributes:{},keepMarks:!1,keepAttributes:!1}},group:"block list",content(){return`${this.options.itemTypeName}+`},parseHTML(){return[{tag:"ul"}]},renderHTML({HTMLAttributes:n}){return["ul",H(this.options.HTMLAttributes,n),0]},markdownTokenName:"list",parseMarkdown:(n,e)=>n.type!=="list"||n.ordered?[]:{type:"bulletList",content:n.items?e.parseChildren(n.items):[]},renderMarkdown:(n,e)=>n.content?e.renderChildren(n.content,` +`):"",markdownOptions:{indentsContent:!0},addCommands(){return{toggleBulletList:()=>({commands:n,chain:e})=>this.options.keepAttributes?e().toggleList(this.name,this.options.itemTypeName,this.options.keepMarks).updateAttributes(ck,this.editor.getAttributes(pa)).run():n.toggleList(this.name,this.options.itemTypeName,this.options.keepMarks)}},addKeyboardShortcuts(){return{"Mod-Shift-8":()=>this.editor.commands.toggleBulletList()}},addInputRules(){let n=sn({find:ma,type:this.type});return(this.options.keepMarks||this.options.keepAttributes)&&(n=sn({find:ma,type:this.type,keepMarks:this.options.keepMarks,keepAttributes:this.options.keepAttributes,getAttributes:()=>this.editor.getAttributes(pa),editor:this.editor})),[n]}}),uk=(n,e,t)=>{const{selection:r}=n;if(!r.empty)return null;const{$from:i}=r;if(!i.parent.isTextblock||i.parentOffset!==i.parent.content.size)return null;let s=-1;for(let h=i.depth;h>0;h-=1)if(i.node(h).type.name===e){s=h;break}if(s<0)return null;const o=i.node(s),l=i.index(s);if(l+1>=o.childCount)return null;const a=o.child(l+1);if(!t.includes(a.type.name))return null;const c=n.schema.nodes[e];let u=!1;if(a.forEach(h=>{h.type===c&&h.childCount>1&&(u=!0)}),!u)return null;const d=n.doc.resolve(i.after()).nodeAfter;if(!d||!t.includes(d.type.name))return null;const f=[];return d.forEach(h=>{f.push(h)}),f.length===0?null:{listItemDepth:s,nestedList:d,nestedListPos:i.after(),insertPos:i.after(s),items:f}},dk=(n,e,t,r)=>{const i=uk(n,t,r);if(!i)return!1;const{selection:s}=n,{nestedList:o,nestedListPos:l,insertPos:a,items:c}=i,u=n.tr;u.delete(l,l+o.nodeSize);const d=u.mapping.map(a);return u.insert(d,b.from(c)),u.setSelection(s.map(u.doc,u.mapping)),e&&e(u),!0},fk=(n,e,t)=>dk(n.state,n.view.dispatch,e,t),Md=(n,e)=>j.create({name:`${n}BranchingDeleteKeymap`,priority:101,addKeyboardShortcuts(){const t=()=>fk(this.editor,n,e);return{Delete:t,"Mod-Delete":t}}}),Td=[[1e3,"m"],[900,"cm"],[500,"d"],[400,"cd"],[100,"c"],[90,"xc"],[50,"l"],[40,"xl"],[10,"x"],[9,"ix"],[5,"v"],[4,"iv"],[1,"i"]],cr="abcdefghijklmnopqrstuvwxyz",Ed=String.raw`\d+|[ivxlcdmIVXLCDM]+|${"[a-zA-Z]{1,2}"}`;function Mi(n){let e=n,t="";for(const[r,i]of Td)for(;e>=r;)t+=i,e-=r;return t}function xo(n){return Mi(n).toUpperCase()}function Ad(n){const e=n.toLowerCase();let t=0,r=0;for(;t0?r:1}const t=parseInt(n,10);return Number.isNaN(t)?1:t}function mk(n,e){if(n==="numeric")return String(e);switch(n){case"a":return oi(e);case"A":return oi(e).toUpperCase();case"i":return Mi(e);case"I":return xo(e);default:return String(e)}}function gk(n){var e;if(n.length===0)return!1;const t=(e=Ti(n[0]))!==null&&e!==void 0?e:"numeric",r=vo(n[0]);if(r<1)return!1;for(let i=0;i{var t;if(n.type!=="list_item")return[];const r=(t=e.parseBlockChildren)!==null&&t!==void 0?t:e.parseChildren;let i=[];if(n.tokens&&n.tokens.length>0){if(wk(n))return{type:"listItem",content:[{type:"paragraph",content:Sk(n.text||"",e)}]};if(n.tokens.some(s=>s.type==="paragraph"))i=r(n.tokens);else{const s=n.tokens[0];if(s&&s.type==="text"&&s.tokens&&s.tokens.length>0){if(i=[{type:"paragraph",content:e.parseInline(s.tokens)}],n.tokens.length>1){const o=r(n.tokens.slice(1));i.push(...o)}}else i=r(n.tokens)}}return i.length===0&&(i=[{type:"paragraph",content:[]}]),{type:"listItem",content:i}},renderMarkdown:(n,e,t)=>Bu(n,e,r=>{if(r.parentType==="bulletList")return"- ";if(r.parentType==="orderedList"){var i,s;const o=((i=r.meta)===null||i===void 0||(i=i.parentAttrs)===null||i===void 0?void 0:i.start)||1;return kk((s=r.meta)===null||s===void 0||(s=s.parentAttrs)===null||s===void 0?void 0:s.type,o-1+(r.index||0),". ")}return"- "},t,{alignNestedToPrefix:t?.parentType==="orderedList"}),addExtensions(){return[Md(this.name,[this.options.bulletListTypeName,this.options.orderedListTypeName])]},addKeyboardShortcuts(){return{Enter:()=>this.editor.commands.splitListItem(this.name),Tab:()=>this.editor.commands.sinkListItem(this.name),"Shift-Tab":()=>this.editor.commands.liftListItem(this.name)}}}),Mo=(n,e)=>{const{$from:t}=e.selection,r=X(n,e.schema);let i=null,s=t.depth,o=t.pos,l=null;for(;s>0&&l===null;)i=t.node(s),i.type===r?l=s:(s-=1,o-=1);return l===null?null:{$pos:e.doc.resolve(o),depth:l}},Od=(n,e)=>{const t=Mo(n,e);if(!t)return!1;const[,r]=mg(e,n,t.$pos.pos+4);return r},Ck=(n,e,t)=>{const{$anchor:r}=n.selection,i=Math.max(0,r.pos-2),s=n.doc.resolve(i).node();return!(!s||!t.includes(s.type.name))},ga=(n,e,t)=>{if(n.commands.undoInputRule())return!0;if(n.state.selection.from!==n.state.selection.to)return!1;if(!Ge(n.state,e)&&Ck(n.state,e,t)){const{$anchor:s}=n.state.selection,o=n.state.doc.resolve(s.before()-1),l=[];o.node().descendants((u,d)=>{u.type.name===e&&l.push({node:u,pos:d})});const a=l.at(-1);if(!a)return!1;const c=n.state.doc.resolve(o.start()+a.pos+1);return n.chain().cut({from:s.start()-1,to:s.end()+1},c.end()).joinForward().run()}if(!Ge(n.state,e)||!wg(n.state))return!1;const{$from:r}=n.state.selection,i=r.depth-1;return r.node(i).type!==n.schema.nodes[e]||r.index(i)!==0?!1:n.chain().liftListItem(e).run()},xk=(n,e)=>{const t=Od(n,e),r=Mo(n,e);return!r||!t?!1:t>r.depth},vk=(n,e)=>{const t=Od(n,e),r=Mo(n,e);return!r||!t?!1:t{if(!Ge(n.state,e)||!kg(n.state,e))return!1;const{selection:t}=n.state,{$from:r,$to:i}=t;return!t.empty&&r.sameParent(i)?!1:xk(e,n.state)?n.chain().focus(n.state.selection.from+4).lift(e).joinBackward().run():vk(e,n.state)?n.chain().joinForward().joinBackward().run():n.commands.joinItemForward()},Mk=(n,e,t)=>{const{state:r}=n,{selection:i}=r;if(!i.empty)return!1;const{$from:s}=i;if(s.parentOffset!==0||!s.parent.isTextblock||Ge(r,e))return!1;const o=gg(s);if(!o||!t.includes(o.type.name))return!1;const l=o.lastChild;if(!l||l.type.name!==e)return!1;const a=s.parent;if(!l.canReplace(l.childCount,l.childCount,b.from(a)))return!1;const c=s.before(),u=s.after(),d=c-2;return n.commands.command(({tr:f,dispatch:h})=>(h&&(f.delete(c,u).insert(d,b.from(a)),f.setSelection(v.create(f.doc,d+1)),f.scrollIntoView()),!0))},Rd=j.create({name:"listKeymap",addOptions(){return{listTypes:[{itemName:"listItem",wrapperNames:["bulletList","orderedList"]},{itemName:"taskItem",wrapperNames:["taskList"]}]}},addKeyboardShortcuts(){return{Delete:({editor:n})=>{let e=!1;return this.options.listTypes.forEach(({itemName:t})=>{n.state.schema.nodes[t]!==void 0&&ya(n,t)&&(e=!0)}),e},"Mod-Delete":({editor:n})=>{let e=!1;return this.options.listTypes.forEach(({itemName:t})=>{n.state.schema.nodes[t]!==void 0&&ya(n,t)&&(e=!0)}),e},Backspace:({editor:n})=>{let e=!1;return this.options.listTypes.forEach(({itemName:t,wrapperNames:r})=>{n.state.schema.nodes[t]!==void 0&&ga(n,t,r)&&(e=!0)}),e},"Mod-Backspace":({editor:n})=>{let e=!1;return this.options.listTypes.forEach(({itemName:t,wrapperNames:r})=>{n.state.schema.nodes[t]!==void 0&&ga(n,t,r)&&(e=!0)}),e},Tab:({editor:n})=>{for(const{itemName:e,wrapperNames:t}of this.options.listTypes)if(n.state.schema.nodes[e]!==void 0&&Mk(n,e,t))return!0;return!1}}}}),li=new RegExp(`^(\\s*)(${Ed})([.)])\\s+(.*)$`),Tk=/^\s/,Jt={heading:/^#{1,6}(?:\s|$)/,bulletItem:/^[-+*]\s+/,codeFence:/^(?:```|~~~)/,blockMath:/^\$\$/,thematicBreak:/^(?:(?:-[ \t]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})$/};function Ek(n){return li.test(n.trimStart())}function Ak(n){const e=n.trimStart();return Jt.bulletItem.test(e)||Ek(e)||Jt.heading.test(e)||Jt.thematicBreak.test(e)&&!e.startsWith("-")||/^>\s?/.test(e)||Jt.codeFence.test(e)||Jt.blockMath.test(e)}function Nk(n){return Object.values(Jt).some(e=>e.test(n))}function Ok(n){const e=[],t=[];let r=!1;return n.forEach(i=>{if(r){t.push(i);return}if(i.trim()===""){r=!0,t.push(i);return}if(e.length>0&&Ak(i)){r=!0,t.push(i);return}e.push(i)}),{paragraphLines:e,blockLines:t}}function ba(n){const e=[];let t=0,r=0;for(;tr.trim().length>0);if(e.length===0)return null;const t=[];for(const r of e){const i=r.trim().match(Dy);if(!i)return null;t.push({marker:i[1],content:i[3]})}return gy(t.map(r=>r.marker))?{type:"orderedList",attrs:by(t[0].marker),content:t.map(r=>({type:"listItem",content:[{type:"paragraph",content:[{type:"text",text:r.content}]}]}))}:null}function au(n,e,t){const r=[];let i=0;for(;ir.trim().length>0);if(e.length===0)return null;const t=[];for(const r of e){const i=r.trim().match(Rk);if(!i)return null;t.push({marker:i[1],content:i[3]})}return gk(t.map(r=>r.marker))?{type:"orderedList",attrs:bk(t[0].marker),content:t.map(r=>({type:"listItem",content:[{type:"paragraph",content:[{type:"text",text:r.content}]}]}))}:null}function Dd(n,e,t){const r=[];let i=0;for(;ie;)f.push(n[d]),d+=1;if(f.length>0){const h=au(f,Math.min(...f.map(p=>p.indent)),t);c.push({type:"list",ordered:!0,start:f[0].number,typeMarker:f[0].type,items:h,raw:f.map(p=>p.raw).join(` -`)})}r.push({type:"list_item",raw:s.raw,tokens:c}),i=d}else i+=1}return r}function Ry(n,e){return n.map(t=>{if(t.type!=="list_item")return e.parseChildren([t])[0];const r=[];return t.tokens&&t.tokens.length>0&&t.tokens.forEach(i=>{if(i.type==="paragraph"||i.type==="list"||i.type==="blockquote"||i.type==="code")r.push(...e.parseChildren([i]));else if(i.type==="text"&&i.tokens){const s=e.parseChildren([i]);r.push({type:"paragraph",content:s})}else{const s=e.parseChildren([i]);s.length>0&&r.push(...s)}}),{type:"listItem",content:r}})}const Ly=64;function yl(n,e){const t=[];let r=0;for(;t.lengthn.hasAttribute("start")?parseInt(n.getAttribute("start")||"",10):1},type:{default:null,parseHTML:n=>{const e=n.getAttribute("type");if(e)return e;const t=n.getAttribute("style");if(t){const i=Sl(t);if(i)return i}const r=n.querySelector("li");if(r){const i=r.getAttribute("style");if(i){const s=Sl(i);if(s)return s}}return null}}}},parseHTML(){return[{tag:"ol"}]},renderHTML({HTMLAttributes:n}){const{start:e,type:t,...r}=n,i=J(this.options.HTMLAttributes,r);return e!==1&&(i.start=e),t&&t!=="1"&&(i.type=t),["ol",i,0]},markdownTokenName:"list",parseMarkdown:(n,e)=>{if(n.type!=="list"||!n.ordered)return[];const t=n.start||1,r=n.typeMarker,i=n.items?Ry(n.items,e):[],s={};return t!==1&&(s.start=t),r&&(s.type=r),Object.keys(s).length>0?{type:"orderedList",attrs:s,content:i}:{type:"orderedList",content:i}},renderMarkdown:(n,e)=>n.content?e.renderChildren(n.content,` -`):"",markdownTokenizer:{name:"orderedList",level:"block",start:()=>-1,tokenize:(n,e,t)=>{var r,i;const[s,o,l]=Py(n);if(s.length===0)return;const a=au(s,s[0].indent,t);if(a.length!==0)return{type:"list",ordered:!0,start:((r=s[0])===null||r===void 0?void 0:r.number)||1,typeMarker:(i=s[0])===null||i===void 0?void 0:i.type,items:a,raw:l.slice(0,o).join(` -`)}}},markdownOptions:{indentsContent:!0},addCommands(){return{toggleOrderedList:()=>({commands:n,chain:e})=>this.options.keepAttributes?e().toggleList(this.name,this.options.itemTypeName,this.options.keepMarks).updateAttributes(By,this.editor.getAttributes(bl)).run():n.toggleList(this.name,this.options.itemTypeName,this.options.keepMarks)}},addKeyboardShortcuts(){return{"Mod-Shift-7":()=>this.editor.commands.toggleOrderedList()}},addProseMirrorPlugins(){return[new $({props:{handlePaste:(n,e)=>{var t,r;const i=(t=e.clipboardData)===null||t===void 0?void 0:t.getData("text/html");if(i?.trim())return!1;const s=(r=e.clipboardData)===null||r===void 0?void 0:r.getData("text/plain");if(!s)return!1;const o=Iy(s);if(!o)return!1;try{const l=n.state.schema.nodeFromJSON(o),a=n.state.tr.replaceSelectionWith(l);return n.dispatch(a),!0}catch{return!1}}}})]},addInputRules(){const n=(t,r)=>(!r.attrs.type||r.attrs.type==="1")&&r.childCount+r.attrs.start===+t[1];let e=_t({find:kl,type:this.type,getAttributes:t=>({start:+t[1]}),joinPredicate:n});return(this.options.keepMarks||this.options.keepAttributes)&&(e=_t({find:kl,type:this.type,keepMarks:this.options.keepMarks,keepAttributes:this.options.keepAttributes,getAttributes:t=>({start:+t[1],...this.editor.getAttributes(bl)}),joinPredicate:n,editor:this.editor})),[e]}}),zy=/^\s*(\[([( |x])?\])\s$/,$y="position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0",Fy=(n,e,t)=>{var r;return(t==null||(r=t.checkboxLabel)===null||r===void 0?void 0:r.call(t,n,e))||`Task item checkbox for ${n.textContent||"empty task item"}`},Vy=pe.create({name:"taskItem",addOptions(){return{nested:!1,HTMLAttributes:{},taskListTypeName:"taskList",a11y:void 0}},content(){return this.options.nested?"paragraph block*":"paragraph+"},defining:!0,addAttributes(){return{checked:{default:!1,keepOnSplit:!1,parseHTML:n=>{const e=n.getAttribute("data-checked");return e===""||e==="true"},renderHTML:n=>({"data-checked":n.checked})}}},parseHTML(){return[{tag:`li[data-type="${this.name}"]`,priority:51,contentElement:n=>{var e;return(e=n.querySelector("div"))!==null&&e!==void 0?e:n}}]},renderHTML({node:n,HTMLAttributes:e}){return["li",J(this.options.HTMLAttributes,e,{"data-type":this.name}),["label",["input",{type:"checkbox",checked:n.attrs.checked?"checked":null}],["span"]],["div",0]]},parseMarkdown:(n,e)=>{const t=[];if(n.tokens&&n.tokens.length>0?t.push(e.createNode("paragraph",{},e.parseInline(n.tokens))):n.text?t.push(e.createNode("paragraph",{},[e.createNode("text",{text:n.text})])):t.push(e.createNode("paragraph",{},[])),n.nestedTokens&&n.nestedTokens.length>0){const r=e.parseChildren(n.nestedTokens);t.push(...r)}return e.createNode("taskItem",{checked:n.checked||!1},t)},renderMarkdown:(n,e)=>{var t;const r=`- [${!((t=n.attrs)===null||t===void 0)&&t.checked?"x":" "}] `;return Ic(n,e,r)},addExtensions(){return this.options.nested?[tu(this.name,[this.options.taskListTypeName])]:[]},addKeyboardShortcuts(){const n={Enter:()=>this.editor.commands.splitListItem(this.name),"Shift-Tab":()=>this.editor.commands.liftListItem(this.name)};return this.options.nested?{...n,Tab:()=>this.editor.commands.sinkListItem(this.name)}:n},addNodeView(){return({node:n,HTMLAttributes:e,getPos:t,editor:r})=>{const i=document.createElement("li"),s=document.createElement("label"),o=document.createElement("span"),l=document.createElement("input"),a=document.createElement("div");o.style.cssText=$y;const c=d=>{const f=Fy(d,d.attrs.checked,this.options.a11y);l.setAttribute("aria-label",f),o.textContent=f};c(n),s.contentEditable="false",l.type="checkbox",l.addEventListener("mousedown",d=>d.preventDefault()),l.addEventListener("change",d=>{if(!r.isEditable&&!this.options.onReadOnlyChecked){l.checked=!l.checked;return}const{checked:f}=d.target;r.isEditable&&typeof t=="function"&&r.chain().focus(void 0,{scrollIntoView:!1}).command(({tr:h})=>{const p=t();if(typeof p!="number")return!1;const m=h.doc.nodeAt(p);return h.setNodeMarkup(p,void 0,{...m?.attrs,checked:f}),!0}).run(),!r.isEditable&&this.options.onReadOnlyChecked&&(this.options.onReadOnlyChecked(n,f)||(l.checked=!l.checked))}),Object.entries(this.options.HTMLAttributes).forEach(([d,f])=>{i.setAttribute(d,f)}),i.dataset.checked=n.attrs.checked,l.checked=n.attrs.checked,s.append(l,o),i.append(s,a),Object.entries(e).forEach(([d,f])=>{i.setAttribute(d,f)});let u=new Set(Object.keys(e));return{dom:i,contentDOM:a,update:d=>{if(d.type!==this.type)return!1;i.dataset.checked=d.attrs.checked,l.checked=d.attrs.checked,c(d);const f=r.extensionManager.attributes,h=Mn(d,f),p=new Set(Object.keys(h)),m=this.options.HTMLAttributes;return u.forEach(g=>{p.has(g)||(g in m?i.setAttribute(g,m[g]):i.removeAttribute(g))}),Object.entries(h).forEach(([g,y])=>{y==null?g in m?i.setAttribute(g,m[g]):i.removeAttribute(g):i.setAttribute(g,y)}),u=p,!0}}}},addInputRules(){return[_t({find:zy,type:this.type,getAttributes:n=>({checked:n[n.length-1]==="x"})})]}}),Hy=pe.create({name:"taskList",addOptions(){return{itemTypeName:"taskItem",HTMLAttributes:{}}},group:"block list",content(){return`${this.options.itemTypeName}+`},parseHTML(){return[{tag:`ul[data-type="${this.name}"]`,priority:51}]},renderHTML({HTMLAttributes:n}){return["ul",J(this.options.HTMLAttributes,n,{"data-type":this.name}),0]},parseMarkdown:(n,e)=>e.createNode("taskList",{},e.parseChildren(n.items||[])),renderMarkdown:(n,e)=>n.content?e.renderChildren(n.content,` -`):"",markdownTokenizer:{name:"taskList",level:"block",start(n){var e;const t=(e=n.match(/^\s*[-+*]\s+\[([ xX])\]\s+/))===null||e===void 0?void 0:e.index;return t!==void 0?t:-1},tokenize(n,e,t){const r=s=>{const o=nl(s,{itemPattern:/^(\s*)([-+*])\s+\[([ xX])\]\s+(.*)$/,extractItemData:l=>({indentLevel:l[1].length,mainContent:l[4],checked:l[3].toLowerCase()==="x"}),createToken:(l,a)=>({type:"taskItem",raw:"",mainContent:l.mainContent,indentLevel:l.indentLevel,checked:l.checked,text:l.mainContent,tokens:t.inlineTokens(l.mainContent),nestedTokens:a}),customNestedParser:r},t);if(o){const l={type:"taskList",raw:o.raw,items:o.items},a=s.slice(o.raw.length);return a.trim()?[l,...t.blockTokens(a)]:[l]}return t.blockTokens(s)},i=nl(n,{itemPattern:/^(\s*)([-+*])\s+\[([ xX])\]\s+(.*)$/,extractItemData:s=>({indentLevel:s[1].length,mainContent:s[4],checked:s[3].toLowerCase()==="x"}),createToken:(s,o)=>({type:"taskItem",raw:"",mainContent:s.mainContent,indentLevel:s.indentLevel,checked:s.checked,text:s.mainContent,tokens:t.inlineTokens(s.mainContent),nestedTokens:o}),customNestedParser:r},t);if(i)return{type:"taskList",raw:i.raw,items:i.items}}},markdownOptions:{indentsContent:!0},addCommands(){return{toggleTaskList:()=>({commands:n})=>n.toggleList(this.name,this.options.itemTypeName)}},addKeyboardShortcuts(){return{"Mod-Shift-9":()=>this.editor.commands.toggleTaskList()}}});W.create({name:"listKit",addExtensions(){const n=[];return this.options.bulletList!==!1&&n.push(eu.configure(this.options.bulletList)),this.options.listItem!==!1&&n.push(su.configure(this.options.listItem)),this.options.listKeymap!==!1&&n.push(lu.configure(this.options.listKeymap)),this.options.orderedList!==!1&&n.push(cu.configure(this.options.orderedList)),this.options.taskItem!==!1&&n.push(Vy.configure(this.options.taskItem)),this.options.taskList!==!1&&n.push(Hy.configure(this.options.taskList)),n}});const Kn=" ",Ei=" ",jy=pe.create({name:"paragraph",priority:1e3,addOptions(){return{HTMLAttributes:{}}},group:"block",content:"inline*",parseHTML(){return[{tag:"p"}]},renderHTML({HTMLAttributes:n}){return["p",J(this.options.HTMLAttributes,n),0]},parseMarkdown:(n,e)=>{const t=n.tokens||[];if(t.length===1&&t[0].type==="image")return e.parseChildren([t[0]]);const r=e.parseInline(t);return t.length===1&&t[0].type==="text"&&(t[0].raw===Kn||t[0].text===Kn||t[0].raw===Ei||t[0].text===Ei)&&r.length===1&&r[0].type==="text"&&(r[0].text===Kn||r[0].text===Ei)?e.createNode("paragraph",void 0,[]):e.createNode("paragraph",void 0,r)},renderMarkdown:(n,e,t)=>{if(!n)return"";const r=Array.isArray(n.content)?n.content:[];if(r.length===0){var i,s;const o=Array.isArray(t==null||(i=t.previousNode)===null||i===void 0?void 0:i.content)?t.previousNode.content:[];return(t==null||(s=t.previousNode)===null||s===void 0?void 0:s.type)==="paragraph"&&o.length===0?Kn:""}return e.renderChildren(r)},addCommands(){return{setParagraph:()=>({commands:n})=>n.setNode(this.name)}},addKeyboardShortcuts(){return{"Mod-Alt-0":()=>this.editor.commands.setParagraph()}}}),Wy=/(?:^|\s)(~~(?!\s+~~)((?:[^~]+))~~(?!\s+~~))$/,Ky=/(?:^|\s)(~~(?!\s+~~)((?:[^~]+))~~(?!\s+~~))/g,_y=Et.create({name:"strike",addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:"s"},{tag:"del"},{tag:"strike"},{style:"text-decoration",consuming:!1,getAttrs:n=>n.includes("line-through")?{}:!1}]},renderHTML({HTMLAttributes:n}){return["s",J(this.options.HTMLAttributes,n),0]},markdownTokenName:"del",parseMarkdown:(n,e)=>e.applyMark("strike",e.parseInline(n.tokens||[])),renderMarkdown:(n,e)=>`~~${e.renderChildren(n)}~~`,addCommands(){return{setStrike:()=>({commands:n})=>n.setMark(this.name),toggleStrike:()=>({commands:n})=>n.toggleMark(this.name),unsetStrike:()=>({commands:n})=>n.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-Shift-s":()=>this.editor.commands.toggleStrike()}},addInputRules(){return[vt({find:Wy,type:this.type})]},addPasteRules(){return[it({find:Ky,type:this.type})]}}),Uy=pe.create({name:"text",group:"inline",parseMarkdown:n=>({type:"text",text:n.text||""}),renderMarkdown:n=>n.text||""}),qy=Et.create({name:"underline",addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:"u"},{style:"text-decoration",consuming:!1,getAttrs:n=>n.includes("underline")?{}:!1}]},renderHTML({HTMLAttributes:n}){return["u",J(this.options.HTMLAttributes,n),0]},parseMarkdown(n,e){return e.applyMark(this.name||"underline",e.parseInline(n.tokens||[]))},renderMarkdown(n,e){return`++${e.renderChildren(n)}++`},markdownTokenizer:{name:"underline",level:"inline",start(n){return n.indexOf("++")},tokenize(n,e,t){const r=/^(\+\+)([\s\S]+?)(\+\+)/.exec(n);if(!r)return;const i=r[2].trim();return{type:"underline",raw:r[0],text:i,tokens:t.inlineTokens(i)}}},addCommands(){return{setUnderline:()=>({commands:n})=>n.setMark(this.name),toggleUnderline:()=>({commands:n})=>n.toggleMark(this.name),unsetUnderline:()=>({commands:n})=>n.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-u":()=>this.editor.commands.toggleUnderline(),"Mod-U":()=>this.editor.commands.toggleUnderline()}}});function Jy(n={}){return new $({view(e){return new Gy(e,n)}})}class Gy{constructor(e,t){var r;this.editorView=e,this.cursorPos=null,this.element=null,this.timeout=-1,this.lastDragEvent=null,this.width=(r=t.width)!==null&&r!==void 0?r:1,this.color=t.color===!1?void 0:t.color||"black",this.class=t.class,this.handlers=["dragover","dragend","drop","dragleave"].map(i=>{let s=o=>{this[i](o)};return e.dom.addEventListener(i,s),{name:i,handler:s}})}destroy(){this.setCursor(null),this.handlers.forEach(({name:e,handler:t})=>this.editorView.dom.removeEventListener(e,t))}update(e,t){if(this.cursorPos!=null&&t.doc!=e.state.doc)if(this.lastDragEvent){let r=this.computeTarget(this.lastDragEvent);r==this.cursorPos?this.updateOverlay():this.setCursor(r)}else this.updateOverlay()}setCursor(e){e!=this.cursorPos&&(this.cursorPos=e,e==null?(this.element.parentNode.removeChild(this.element),this.element=null):this.updateOverlay())}updateOverlay(){let e=this.editorView.state.doc.resolve(this.cursorPos),t=!e.parent.inlineContent,r,i=this.editorView.dom,s=i.getBoundingClientRect(),o=s.width/i.offsetWidth,l=s.height/i.offsetHeight;if(t){let d=e.nodeBefore,f=e.nodeAfter;if(d||f){let h=this.editorView.nodeDOM(this.cursorPos-(d?d.nodeSize:0));if(h){let p=h.getBoundingClientRect(),m=d?p.bottom:p.top;d&&f&&(m=(m+this.editorView.nodeDOM(this.cursorPos).getBoundingClientRect().top)/2);let g=this.width/2*l;r={left:p.left,right:p.right,top:m-g,bottom:m+g}}}}if(!r){let d=this.editorView.coordsAtPos(this.cursorPos),f=this.width/2*o;r={left:d.left-f,right:d.left+f,top:d.top,bottom:d.bottom}}let a=this.editorView.dom.offsetParent;this.element||(this.element=a.appendChild(document.createElement("div")),this.class&&(this.element.className=this.class),this.element.style.cssText="position: absolute; z-index: 50; pointer-events: none;",this.color&&(this.element.style.backgroundColor=this.color)),this.element.classList.toggle("prosemirror-dropcursor-block",t),this.element.classList.toggle("prosemirror-dropcursor-inline",!t);let c,u;if(!a||a==document.body&&getComputedStyle(a).position=="static")c=-pageXOffset,u=-pageYOffset;else{let d=a.getBoundingClientRect(),f=d.width/a.offsetWidth,h=d.height/a.offsetHeight;c=d.left-a.scrollLeft*f,u=d.top-a.scrollTop*h}this.element.style.left=(r.left-c)/o+"px",this.element.style.top=(r.top-u)/l+"px",this.element.style.width=(r.right-r.left)/o+"px",this.element.style.height=(r.bottom-r.top)/l+"px"}scheduleRemoval(e){clearTimeout(this.timeout),this.timeout=setTimeout(()=>this.setCursor(null),e)}computeTarget(e){let t=this.editorView.posAtCoords({left:e.clientX,top:e.clientY}),r=t&&t.inside>=0&&this.editorView.state.doc.nodeAt(t.inside),i=r&&r.type.spec.disableDropCursor,s=typeof i=="function"?i(this.editorView,t,e):i;if(!t||s)return null;let o=t.pos;if(this.editorView.dragging&&this.editorView.dragging.slice){let l=Xl(this.editorView.state.doc,o,this.editorView.dragging.slice);l!=null&&(o=l)}return o}dragover(e){if(!this.editorView.editable)return;this.lastDragEvent=e;let t=this.computeTarget(e);t!=null&&(this.setCursor(t),this.scheduleRemoval(5e3))}dragend(){this.scheduleRemoval(20)}drop(){this.scheduleRemoval(20)}dragleave(e){this.editorView.dom.contains(e.relatedTarget)||this.setCursor(null)}}class j extends O{constructor(e){super(e,e)}map(e,t){let r=e.resolve(t.map(this.head));return j.valid(r)?new j(r):O.near(r)}content(){return w.empty}eq(e){return e instanceof j&&e.head==this.head}toJSON(){return{type:"gapcursor",pos:this.head}}static fromJSON(e,t){if(typeof t.pos!="number")throw new RangeError("Invalid input for GapCursor.fromJSON");return new j(e.resolve(t.pos))}getBookmark(){return new Fs(this.anchor)}static valid(e){let t=e.parent;if(t.inlineContent||!Yy(e)||!Xy(e))return!1;let r=t.type.spec.allowGapCursor;if(r!=null)return r;let i=t.contentMatchAt(e.index()).defaultType;return i&&i.isTextblock}static findGapCursorFrom(e,t,r=!1){e:for(;;){if(!r&&j.valid(e))return e;let i=e.pos,s=null;for(let o=e.depth;;o--){let l=e.node(o);if(t>0?e.indexAfter(o)0){s=l.child(t>0?e.indexAfter(o):e.index(o)-1);break}else if(o==0)return null;i+=t;let a=e.doc.resolve(i);if(j.valid(a))return a}for(;;){let o=t>0?s.firstChild:s.lastChild;if(!o){if(s.isAtom&&!s.isText&&!E.isSelectable(s)){e=e.doc.resolve(i+s.nodeSize*t),r=!1;continue e}break}s=o,i+=t;let l=e.doc.resolve(i);if(j.valid(l))return l}return null}}}j.prototype.visible=!1;j.findFrom=j.findGapCursorFrom;O.jsonID("gapcursor",j);class Fs{constructor(e){this.pos=e}map(e){return new Fs(e.map(this.pos))}resolve(e){let t=e.resolve(this.pos);return j.valid(t)?new j(t):O.near(t)}}function uu(n){return n.isAtom||n.spec.isolating||n.spec.createGapCursor}function Yy(n){for(let e=n.depth;e>=0;e--){let t=n.index(e),r=n.node(e);if(t==0){if(r.type.spec.isolating)return!0;continue}for(let i=r.child(t-1);;i=i.lastChild){if(i.childCount==0&&!i.inlineContent||uu(i.type))return!0;if(i.inlineContent)return!1}}return!0}function Xy(n){for(let e=n.depth;e>=0;e--){let t=n.indexAfter(e),r=n.node(e);if(t==r.childCount){if(r.type.spec.isolating)return!0;continue}for(let i=r.child(t);;i=i.firstChild){if(i.childCount==0&&!i.inlineContent||uu(i.type))return!0;if(i.inlineContent)return!1}}return!0}function Qy(){return new $({props:{decorations:n0,createSelectionBetween(n,e,t){return e.pos==t.pos&&j.valid(t)?new j(t):null},handleClick:e0,handleKeyDown:Zy,handleDOMEvents:{beforeinput:t0}}})}const Zy=tc({ArrowLeft:_n("horiz",-1),ArrowRight:_n("horiz",1),ArrowUp:_n("vert",-1),ArrowDown:_n("vert",1)});function _n(n,e){const t=n=="vert"?e>0?"down":"up":e>0?"right":"left";return function(r,i,s){let o=r.selection,l=e>0?o.$to:o.$from,a=o.empty;if(o instanceof T){if(!s.endOfTextblock(t)||l.depth==0)return!1;a=!1,l=r.doc.resolve(e>0?l.after():l.before())}let c=j.findGapCursorFrom(l,e,a);return c?(i&&i(r.tr.setSelection(new j(c))),!0):!1}}function e0(n,e,t){if(!n||!n.editable)return!1;let r=n.state.doc.resolve(e);if(!j.valid(r))return!1;let i=n.posAtCoords({left:t.clientX,top:t.clientY});return i&&i.inside>-1&&E.isSelectable(n.state.doc.nodeAt(i.inside))?!1:(n.dispatch(n.state.tr.setSelection(new j(r))),!0)}function t0(n,e){if(e.inputType!="insertCompositionText"||!(n.state.selection instanceof j))return!1;let{$from:t}=n.state.selection,r=t.parent.contentMatchAt(t.index()).findWrapping(n.state.schema.nodes.text);if(!r)return!1;let i=b.empty;for(let o=r.length-1;o>=0;o--)i=b.from(r[o].createAndFill(null,i));let s=n.state.tr.replace(t.pos,t.pos,new w(i,0,0));return s.setSelection(T.near(s.doc.resolve(t.pos+1))),n.dispatch(s),!1}function n0(n){if(!(n.selection instanceof j))return null;let e=document.createElement("div");return e.className="ProseMirror-gapcursor",D.create(n.doc,[oe.widget(n.selection.head,e,{key:"gapcursor"})])}W.create({name:"characterCount",addOptions(){return{limit:null,autoTrim:!0,mode:"textSize",textCounter:n=>n.length,wordCounter:n=>n.split(" ").filter(e=>e!=="").length}},addStorage(){return{characters:()=>0,words:()=>0}},onBeforeCreate(){this.storage.characters=n=>{const e=n?.node||this.editor.state.doc;if((n?.mode||this.options.mode)==="textSize"){const t=e.textBetween(0,e.content.size,void 0," ");return this.options.textCounter(t)}return e.nodeSize},this.storage.words=n=>{const e=n?.node||this.editor.state.doc,t=e.textBetween(0,e.content.size," "," ");return this.options.wordCounter(t)}},addProseMirrorPlugins(){let n=!1;return[new $({key:new _("characterCount"),appendTransaction:(e,t,r)=>{if(n)return;const i=this.options.limit,s=this.options.autoTrim;if(i==null||i===0||s===!1){n=!0;return}const o=this.storage.characters({node:r.doc});if(o>i){const l=o-i,a=0,c=l;console.warn(`[CharacterCount] Initial content exceeded limit of ${i} characters. Content was automatically trimmed.`);const u=r.tr.deleteRange(a,c);return n=!0,u}n=!0},filterTransaction:(e,t)=>{const r=this.options.limit;if(!e.docChanged||r===0||r===null||r===void 0)return!0;const i=this.storage.characters({node:t.doc}),s=this.storage.characters({node:e.doc});if(s<=r||i>r&&s>r&&s<=i)return!0;if(i>r&&s>r&&s>i||!e.getMeta("paste"))return!1;const o=e.selection.$head.pos,l=o-(s-r),a=o;return e.deleteRange(l,a),!(this.storage.characters({node:e.doc})>r)}})]}});const r0=W.create({name:"dropCursor",addOptions(){return{color:"currentColor",width:1,class:void 0}},addProseMirrorPlugins(){return[Jy(this.options)]}});W.create({name:"focus",addOptions(){return{className:"has-focus",mode:"all"}},addProseMirrorPlugins(){return[new $({key:new _("focus"),props:{decorations:({doc:n,selection:e})=>{const{isEditable:t,isFocused:r}=this.editor,{anchor:i}=e,s=[];if(!t||!r)return D.create(n,[]);let o=0;this.options.mode==="deepest"&&n.descendants((a,c)=>{if(!a.isText){if(!(i>=c&&i<=c+a.nodeSize-1))return!1;o+=1}});let l=0;return n.descendants((a,c)=>{if(a.isText||!(i>=c&&i<=c+a.nodeSize-1))return!1;if(l+=1,this.options.mode==="deepest"&&o-l>0||this.options.mode==="shallowest"&&l>1)return this.options.mode==="deepest";s.push(oe.node(c,c+a.nodeSize,{class:this.options.className}))}),D.create(n,s)}}})]}});const i0=W.create({name:"gapCursor",addProseMirrorPlugins(){return[Qy()]},extendNodeSchema(n){var e;const t={name:n.name,options:n.options,storage:n.storage};return{allowGapCursor:(e=L(M(n,"allowGapCursor",t)))!==null&&e!==void 0?e:null}}}),du="placeholder",xl=new _("tiptap__placeholder");function fu(n){const{editor:e,placeholder:t,dataAttribute:r,pos:i,node:s,isEmptyDoc:o,hasAnchor:l,classes:{emptyNode:a,emptyEditor:c}}=n,u=[a];return o&&u.push(c),oe.node(i,i+s.nodeSize,{class:u.join(" "),[r]:typeof t=="function"?t({editor:e,node:s,pos:i,hasAnchor:l}):t})}function hu(n,e){return typeof n=="function"?n(e):n}function pu({editor:n,options:e,dataAttribute:t,doc:r,selection:i,from:s,to:o}){const{anchor:l}=i,a=[],c=n.isEmpty;return r.nodesBetween(s,o,(u,d)=>{const f=l>=d&&l<=d+u.nodeSize,h=!u.isLeaf&&Dn(u);return u.type.isTextblock&&(f||!e.showOnlyCurrent)&&h&&a.push(fu({editor:n,isEmptyDoc:c,dataAttribute:t,hasAnchor:f,placeholder:e.placeholder,classes:{emptyEditor:e.emptyEditorClass,emptyNode:hu(e.emptyNodeClass,{editor:n,node:u,pos:d,hasAnchor:f})},node:u,pos:d})),e.includeChildren}),a}function mu({editor:n,options:e,dataAttribute:t,doc:r,selection:i}){if(!(n.isEditable||!e.showOnlyWhenEditable))return null;const{anchor:s}=i,o=[],l=n.isEmpty;if(e.showOnlyCurrent&&!e.includeChildren){const a=r.resolve(s),c=a.depth>0?a.node(1):a.nodeAfter,u=a.depth>0?a.before(1):s;if(c&&c.type.isTextblock&&Dn(c)){const d=s>=u&&s<=u+c.nodeSize;o.push(fu({editor:n,isEmptyDoc:l,dataAttribute:t,hasAnchor:d,placeholder:e.placeholder,classes:{emptyEditor:e.emptyEditorClass,emptyNode:hu(e.emptyNodeClass,{editor:n,node:c,pos:u,hasAnchor:d})},node:c,pos:u}))}}else o.push(...pu({editor:n,options:e,dataAttribute:t,doc:r,selection:i,from:0,to:r.content.size}));return D.create(r,o)}function pn(n,e){const t=n.resolve(e);if(t.depth===0){var r;const s=(r=t.nodeAfter)!==null&&r!==void 0?r:t.nodeBefore;if(!s)return{from:e,to:e};const o=t.nodeAfter?e:e-s.nodeSize;return{from:o,to:o+s.nodeSize}}const i=t.before(1);return{from:i,to:i+t.node(1).nodeSize}}function mn(n,e){return{from:Math.max(0,e.from-1),to:Math.min(n.content.size,e.to-1)}}function s0(n,e,t){const r=[];return n.forEach((i,s)=>{const o=s,l=o+i.nodeSize,a=o+1,c=l+1;ae&&r.push({from:o,to:l})}),r}function o0(n){if(n.length===0)return[];const e=[...n].sort((r,i)=>r.from-i.from),t=[{...e[0]}];for(let r=1;re.from?t.push(mn(n,pn(n,Math.min(e.to,n.content.size+1)-1))):e.fromh.from>=c&&h.to<=u);d.length&&(l=l.remove(d));const f=pu({editor:t,options:r,dataAttribute:i,doc:s,selection:o,from:c,to:u});f.length&&(l=l.add(s,f))}return l}function d0({editor:n,options:e,dataAttribute:t}){return{init(r,i){const s=mu({editor:n,options:e,dataAttribute:t,doc:i.doc,selection:i.selection});return s??D.empty},apply(r,i,s,o){return!r.docChanged&&!r.selectionSet?i:u0({decorations:i.map(r.mapping,r.doc),ranges:a0(r,s,o),editor:n,options:e,dataAttribute:t,doc:o.doc,selection:o.selection})}}}function f0(n){return n.replace(/\s+/g,"-").replace(/[^a-zA-Z0-9-]/g,"").replace(/^[0-9-]+/,"").replace(/^-+/,"").toLowerCase()}function h0({editor:n,options:e}){const t=e.dataAttribute?`data-${f0(e.dataAttribute)}`:`data-${du}`,r=e.showOnlyCurrent&&!e.includeChildren;return new $({key:xl,...r?{}:{state:d0({editor:n,options:e,dataAttribute:t})},props:{decorations:r?({doc:i,selection:s})=>mu({editor:n,options:e,dataAttribute:t,doc:i,selection:s}):i=>{var s;return e.showOnlyWhenEditable&&!n.isEditable?D.empty:(s=xl.getState(i))!==null&&s!==void 0?s:D.empty}}})}W.create({name:"placeholder",addOptions(){return{emptyEditorClass:"is-editor-empty",emptyNodeClass:"is-empty",dataAttribute:du,placeholder:"Write something …",showOnlyWhenEditable:!0,showOnlyCurrent:!0,includeChildren:!1}},addProseMirrorPlugins(){return[h0({editor:this.editor,options:this.options})]}});function is(n,e){return!n.selection.empty&&!Mc(n.selection)&&e.isEditable}function p0(n,e){return is(n,e)&&!e.isFocused&&!e.view.dragging}function m0(){var n;(n=window.getSelection())===null||n===void 0||n.removeAllRanges()}function g0(n){n.focus()}W.create({name:"selection",addOptions(){return{className:"selection"}},addProseMirrorPlugins(){const{editor:n,options:e}=this;return[new $({key:new _("selection"),props:{decorations(t){return p0(t,n)?D.create(t.doc,[oe.inline(t.selection.from,t.selection.to,{class:e.className})]):null},handleDOMEvents:{blur(t){return is(t.state,n)&&m0(),!1},focus(t){return is(t.state,n)&&requestAnimationFrame(()=>{!n.isDestroyed&&t.hasFocus()&&g0(t)}),!1}}}})]}});function wl({types:n,node:e}){return e&&Array.isArray(n)&&n.includes(e.type)||e?.type===n}const y0=W.create({name:"trailingNode",addOptions(){return{node:void 0,notAfter:[]}},addProseMirrorPlugins(){var n;const e=new _(this.name),t=this.options.node||((n=this.editor.schema.topNodeType.contentMatch.defaultType)===null||n===void 0?void 0:n.name)||"paragraph",r=Object.entries(this.editor.schema.nodes).map(([,i])=>i).filter(i=>(this.options.notAfter||[]).concat(t).includes(i.name));return[new $({key:e,appendTransaction:(i,s,o)=>{const{doc:l,tr:a,schema:c}=o,u=e.getState(o),d=l.content.size,f=c.nodes[t];if(!i.some(h=>h.getMeta("skipTrailingNode"))&&u)return a.insert(d,f.create())},state:{init:(i,s)=>{const o=s.tr.doc.lastChild;return!wl({node:o,types:r})},apply:(i,s)=>{if(!i.docChanged||i.getMeta("__uniqueIDTransaction"))return s;const o=i.doc.lastChild;return!wl({node:o,types:r})}}})]}}),b0=W.create({name:"undoRedo",addOptions(){return{depth:100,newGroupDelay:500}},addCommands(){return{undo:()=>({state:n,dispatch:e})=>sc(n,e),redo:()=>({state:n,dispatch:e})=>oc(n,e)}},addProseMirrorPlugins(){return[Ih(this.options)]},addKeyboardShortcuts(){return{"Mod-z":()=>this.editor.commands.undo(),"Shift-Mod-z":()=>this.editor.commands.redo(),"Mod-y":()=>this.editor.commands.redo(),"Mod-я":()=>this.editor.commands.undo(),"Shift-Mod-я":()=>this.editor.commands.redo()}}}),k0=W.create({name:"starterKit",addExtensions(){const n=[];if(this.options.bold!==!1&&n.push(fg.configure(this.options.bold)),this.options.blockquote!==!1&&n.push(lg.configure(this.options.blockquote)),this.options.bulletList!==!1&&n.push(eu.configure(this.options.bulletList)),this.options.code!==!1&&n.push(gg.configure(this.options.code)),this.options.codeBlock!==!1&&n.push(kg.configure(this.options.codeBlock)),this.options.document!==!1&&n.push(Sg.configure(this.options.document)),this.options.dropcursor!==!1&&n.push(r0.configure(this.options.dropcursor)),this.options.gapcursor!==!1&&n.push(i0.configure(this.options.gapcursor)),this.options.hardBreak!==!1&&n.push(xg.configure(this.options.hardBreak)),this.options.heading!==!1&&n.push(wg.configure(this.options.heading)),this.options.undoRedo!==!1&&n.push(b0.configure(this.options.undoRedo)),this.options.horizontalRule!==!1&&n.push(Cg.configure(this.options.horizontalRule)),this.options.italic!==!1&&n.push(Ag.configure(this.options.italic)),this.options.listItem!==!1&&n.push(su.configure(this.options.listItem)),this.options.listKeymap!==!1){var e;n.push(lu.configure((e=this.options)===null||e===void 0?void 0:e.listKeymap))}if(this.options.link!==!1){var t;n.push(ay.configure((t=this.options)===null||t===void 0?void 0:t.link))}if(this.options.orderedList!==!1&&n.push(cu.configure(this.options.orderedList)),this.options.paragraph!==!1&&n.push(jy.configure(this.options.paragraph)),this.options.strike!==!1&&n.push(_y.configure(this.options.strike)),this.options.text!==!1&&n.push(Uy.configure(this.options.text)),this.options.underline!==!1){var r;n.push(qy.configure((r=this.options)===null||r===void 0?void 0:r.underline))}if(this.options.trailingNode!==!1){var i;n.push(y0.configure((i=this.options)===null||i===void 0?void 0:i.trailingNode))}return n}});var S0=k0;function x0(n){const e=st.fromSchema(n.schema),t=document.createElement("div");return t.appendChild(e.serializeFragment(n.state.doc.content,{document})),t.innerHTML}const Cl="golem15-journal-blogeditor",w0="summer-change";class C0 extends HTMLElement{static observedAttributes=["disabled","invalid","locale"];#o="";#r="";#i="";#s="clean";#e;#l;#t;#n={};#a=!1;constructor(){if(super(),Object.prototype.hasOwnProperty.call(this,"value")){const e=this.value;delete this.value,this.value=e}}get value(){switch(this.#s){case"source":return this.#r;case"wysiwyg":return this.#e?x0(this.#e):this.#o;default:return this.#o}}set value(e){const t=typeof e=="string"?e:e==null?"":String(e);t!==this.value&&(this.#o=t,this.#s="clean",this.#i=t,this.#t&&(this.#t.value=t),this.#e?.commands.setContent(t,{emitUpdate:!1}))}get editor(){return this.#e}connectedCallback(){if(this.#e)return;this.classList.add("blogeditor"),this.replaceChildren();const e=document.createElement("div");e.className="blogeditor__bar";const t=document.createElement("div");t.className="blogeditor__tabs",t.setAttribute("role","tablist"),this.#n.wysiwyg=this.#c("WYSIWYG",()=>this.showSource(!1)),this.#n.source=this.#c("Source",()=>this.showSource(!0)),t.append(this.#n.wysiwyg,this.#n.source),e.append(t);const r=document.createElement("div");r.className="blogeditor__content",this.#l=r;const i=document.createElement("textarea");i.className="blogeditor__source",i.spellcheck=!1,i.hidden=!0,i.value=this.value,i.addEventListener("input",()=>this.#f()),this.#t=i,this.append(e,r,i),this.#i=this.value,this.#e=new ng({element:r,injectCSS:!1,editable:!this.hasAttribute("disabled"),extensions:[S0.configure({trailingNode:!1,link:{openOnClick:!1,HTMLAttributes:{target:null,rel:null,class:null}}})],content:this.#i,onUpdate:({transaction:s,appendedTransactions:o})=>{!s.docChanged&&!o.some(l=>l.docChanged)||(this.#s="wysiwyg",this.#u())}}),this.#d(),this.showSource(!1)}disconnectedCallback(){this.#e?.destroy(),this.#e=void 0}attributeChangedCallback(){this.#d()}showSource(e){!this.#t||!this.#l||(e?this.#t.value=this.value:this.#a&&this.#s==="source"&&this.#r!==this.#i&&(this.#i=this.#r,this.#e?.commands.setContent(this.#r,{emitUpdate:!1})),this.#a=e,this.#t.hidden=!e,this.#l.hidden=e,this.#n.wysiwyg?.setAttribute("aria-selected",String(!e)),this.#n.source?.setAttribute("aria-selected",String(e)))}#c(e,t){const r=document.createElement("button");return r.type="button",r.className="blogeditor__tab",r.setAttribute("role","tab"),r.textContent=e,r.addEventListener("click",t),r}#f(){this.#t&&(this.#r=this.#t.value,this.#s="source",this.#u())}#u(){this.dispatchEvent(new CustomEvent(w0,{bubbles:!0,composed:!0,detail:{value:this.value}}))}#d(){const e=this.hasAttribute("disabled"),t=this.hasAttribute("invalid");this.#e&&this.#e.isEditable===e&&this.#e.setEditable(!e,!1),this.#t&&(this.#t.readOnly=e,t?this.#t.setAttribute("aria-invalid","true"):this.#t.removeAttribute("aria-invalid"));const r=this.#e?.view.dom;if(r){t?r.setAttribute("aria-invalid","true"):r.removeAttribute("aria-invalid");const i=this.getAttribute("locale");i?r.setAttribute("lang",i):r.removeAttribute("lang")}}}customElements.get(Cl)||customElements.define(Cl,C0);export{C0 as BlogEditorElement,Cl as TAG}; +`).trim();if(u){const h=t.blockTokens(u);c.push(...h)}let d=i+1;const f=[];for(;de;)f.push(n[d]),d+=1;if(f.length>0){const h=Dd(f,Math.min(...f.map(p=>p.indent)),t);c.push({type:"list",ordered:!0,start:f[0].number,typeMarker:f[0].type,items:h,raw:f.map(p=>p.raw).join(` +`)})}r.push({type:"list_item",raw:s.raw,tokens:c}),i=d}else i+=1}return r}function Ik(n,e){return n.map(t=>{if(t.type!=="list_item")return e.parseChildren([t])[0];const r=[];return t.tokens&&t.tokens.length>0&&t.tokens.forEach(i=>{if(i.type==="paragraph"||i.type==="list"||i.type==="blockquote"||i.type==="code")r.push(...e.parseChildren([i]));else if(i.type==="text"&&i.tokens){const s=e.parseChildren([i]);r.push({type:"paragraph",content:s})}else{const s=e.parseChildren([i]);s.length>0&&r.push(...s)}}),{type:"listItem",content:r}})}const Lk=64;function ka(n,e){const t=[];let r=0;for(;t.lengthn.hasAttribute("start")?parseInt(n.getAttribute("start")||"",10):1},type:{default:null,parseHTML:n=>{const e=n.getAttribute("type");if(e)return e;const t=n.getAttribute("style");if(t){const i=Ca(t);if(i)return i}const r=n.querySelector("li");if(r){const i=r.getAttribute("style");if(i){const s=Ca(i);if(s)return s}}return null}}}},parseHTML(){return[{tag:"ol"}]},renderHTML({HTMLAttributes:n}){const{start:e,type:t,...r}=n,i=H(this.options.HTMLAttributes,r);return e!==1&&(i.start=e),t&&t!=="1"&&(i.type=t),["ol",i,0]},markdownTokenName:"list",parseMarkdown:(n,e)=>{if(n.type!=="list"||!n.ordered)return[];const t=n.start||1,r=n.typeMarker,i=n.items?Ik(n.items,e):[],s={};return t!==1&&(s.start=t),r&&(s.type=r),Object.keys(s).length>0?{type:"orderedList",attrs:s,content:i}:{type:"orderedList",content:i}},renderMarkdown:(n,e)=>n.content?e.renderChildren(n.content,` +`):"",markdownTokenizer:{name:"orderedList",level:"block",start:()=>-1,tokenize:(n,e,t)=>{var r,i;const[s,o,l]=Pk(n);if(s.length===0)return;const a=Dd(s,s[0].indent,t);if(a.length!==0)return{type:"list",ordered:!0,start:((r=s[0])===null||r===void 0?void 0:r.number)||1,typeMarker:(i=s[0])===null||i===void 0?void 0:i.type,items:a,raw:l.slice(0,o).join(` +`)}}},markdownOptions:{indentsContent:!0},addCommands(){return{toggleOrderedList:()=>({commands:n,chain:e})=>this.options.keepAttributes?e().toggleList(this.name,this.options.itemTypeName,this.options.keepMarks).updateAttributes(zk,this.editor.getAttributes(wa)).run():n.toggleList(this.name,this.options.itemTypeName,this.options.keepMarks)}},addKeyboardShortcuts(){return{"Mod-Shift-7":()=>this.editor.commands.toggleOrderedList()}},addProseMirrorPlugins(){return[new z({props:{handlePaste:(n,e)=>{var t,r;const i=(t=e.clipboardData)===null||t===void 0?void 0:t.getData("text/html");if(i?.trim())return!1;const s=(r=e.clipboardData)===null||r===void 0?void 0:r.getData("text/plain");if(!s)return!1;const o=Dk(s);if(!o)return!1;try{const l=n.state.schema.nodeFromJSON(o),a=n.state.tr.replaceSelectionWith(l);return n.dispatch(a),!0}catch{return!1}}}})]},addInputRules(){const n=(t,r)=>(!r.attrs.type||r.attrs.type==="1")&&r.childCount+r.attrs.start===+t[1];let e=sn({find:Sa,type:this.type,getAttributes:t=>({start:+t[1]}),joinPredicate:n});return(this.options.keepMarks||this.options.keepAttributes)&&(e=sn({find:Sa,type:this.type,keepMarks:this.options.keepMarks,keepAttributes:this.options.keepAttributes,getAttributes:t=>({start:+t[1],...this.editor.getAttributes(wa)}),joinPredicate:n,editor:this.editor})),[e]}}),Bk=/^\s*(\[([( |x])?\])\s$/,$k="position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0",Hk=(n,e,t)=>{var r;return(t==null||(r=t.checkboxLabel)===null||r===void 0?void 0:r.call(t,n,e))||`Task item checkbox for ${n.textContent||"empty task item"}`},Fk=_.create({name:"taskItem",addOptions(){return{nested:!1,HTMLAttributes:{},taskListTypeName:"taskList",a11y:void 0}},content(){return this.options.nested?"paragraph block*":"paragraph+"},defining:!0,addAttributes(){return{checked:{default:!1,keepOnSplit:!1,parseHTML:n=>{const e=n.getAttribute("data-checked");return e===""||e==="true"},renderHTML:n=>({"data-checked":n.checked})}}},parseHTML(){return[{tag:`li[data-type="${this.name}"]`,priority:51,contentElement:n=>{var e;return(e=n.querySelector("div"))!==null&&e!==void 0?e:n}}]},renderHTML({node:n,HTMLAttributes:e}){return["li",H(this.options.HTMLAttributes,e,{"data-type":this.name}),["label",["input",{type:"checkbox",checked:n.attrs.checked?"checked":null}],["span"]],["div",0]]},parseMarkdown:(n,e)=>{const t=[];if(n.tokens&&n.tokens.length>0?t.push(e.createNode("paragraph",{},e.parseInline(n.tokens))):n.text?t.push(e.createNode("paragraph",{},[e.createNode("text",{text:n.text})])):t.push(e.createNode("paragraph",{},[])),n.nestedTokens&&n.nestedTokens.length>0){const r=e.parseChildren(n.nestedTokens);t.push(...r)}return e.createNode("taskItem",{checked:n.checked||!1},t)},renderMarkdown:(n,e)=>{var t;const r=`- [${!((t=n.attrs)===null||t===void 0)&&t.checked?"x":" "}] `;return Bu(n,e,r)},addExtensions(){return this.options.nested?[Md(this.name,[this.options.taskListTypeName])]:[]},addKeyboardShortcuts(){const n={Enter:()=>this.editor.commands.splitListItem(this.name),"Shift-Tab":()=>this.editor.commands.liftListItem(this.name)};return this.options.nested?{...n,Tab:()=>this.editor.commands.sinkListItem(this.name)}:n},addNodeView(){return({node:n,HTMLAttributes:e,getPos:t,editor:r})=>{const i=document.createElement("li"),s=document.createElement("label"),o=document.createElement("span"),l=document.createElement("input"),a=document.createElement("div");o.style.cssText=$k;const c=d=>{const f=Hk(d,d.attrs.checked,this.options.a11y);l.setAttribute("aria-label",f),o.textContent=f};c(n),s.contentEditable="false",l.type="checkbox",l.addEventListener("mousedown",d=>d.preventDefault()),l.addEventListener("change",d=>{if(!r.isEditable&&!this.options.onReadOnlyChecked){l.checked=!l.checked;return}const{checked:f}=d.target;r.isEditable&&typeof t=="function"&&r.chain().focus(void 0,{scrollIntoView:!1}).command(({tr:h})=>{const p=t();if(typeof p!="number")return!1;const m=h.doc.nodeAt(p);return h.setNodeMarkup(p,void 0,{...m?.attrs,checked:f}),!0}).run(),!r.isEditable&&this.options.onReadOnlyChecked&&(this.options.onReadOnlyChecked(n,f)||(l.checked=!l.checked))}),Object.entries(this.options.HTMLAttributes).forEach(([d,f])=>{i.setAttribute(d,f)}),i.dataset.checked=n.attrs.checked,l.checked=n.attrs.checked,s.append(l,o),i.append(s,a),Object.entries(e).forEach(([d,f])=>{i.setAttribute(d,f)});let u=new Set(Object.keys(e));return{dom:i,contentDOM:a,update:d=>{if(d.type!==this.type)return!1;i.dataset.checked=d.attrs.checked,l.checked=d.attrs.checked,c(d);const f=r.extensionManager.attributes,h=rn(d,f),p=new Set(Object.keys(h)),m=this.options.HTMLAttributes;return u.forEach(g=>{p.has(g)||(g in m?i.setAttribute(g,m[g]):i.removeAttribute(g))}),Object.entries(h).forEach(([g,y])=>{y==null?g in m?i.setAttribute(g,m[g]):i.removeAttribute(g):i.setAttribute(g,y)}),u=p,!0}}}},addInputRules(){return[sn({find:Bk,type:this.type,getAttributes:n=>({checked:n[n.length-1]==="x"})})]}}),Vk=_.create({name:"taskList",addOptions(){return{itemTypeName:"taskItem",HTMLAttributes:{}}},group:"block list",content(){return`${this.options.itemTypeName}+`},parseHTML(){return[{tag:`ul[data-type="${this.name}"]`,priority:51}]},renderHTML({HTMLAttributes:n}){return["ul",H(this.options.HTMLAttributes,n,{"data-type":this.name}),0]},parseMarkdown:(n,e)=>e.createNode("taskList",{},e.parseChildren(n.items||[])),renderMarkdown:(n,e)=>n.content?e.renderChildren(n.content,` +`):"",markdownTokenizer:{name:"taskList",level:"block",start(n){var e;const t=(e=n.match(/^\s*[-+*]\s+\[([ xX])\]\s+/))===null||e===void 0?void 0:e.index;return t!==void 0?t:-1},tokenize(n,e,t){const r=s=>{const o=Wl(s,{itemPattern:/^(\s*)([-+*])\s+\[([ xX])\]\s+(.*)$/,extractItemData:l=>({indentLevel:l[1].length,mainContent:l[4],checked:l[3].toLowerCase()==="x"}),createToken:(l,a)=>({type:"taskItem",raw:"",mainContent:l.mainContent,indentLevel:l.indentLevel,checked:l.checked,text:l.mainContent,tokens:t.inlineTokens(l.mainContent),nestedTokens:a}),customNestedParser:r},t);if(o){const l={type:"taskList",raw:o.raw,items:o.items},a=s.slice(o.raw.length);return a.trim()?[l,...t.blockTokens(a)]:[l]}return t.blockTokens(s)},i=Wl(n,{itemPattern:/^(\s*)([-+*])\s+\[([ xX])\]\s+(.*)$/,extractItemData:s=>({indentLevel:s[1].length,mainContent:s[4],checked:s[3].toLowerCase()==="x"}),createToken:(s,o)=>({type:"taskItem",raw:"",mainContent:s.mainContent,indentLevel:s.indentLevel,checked:s.checked,text:s.mainContent,tokens:t.inlineTokens(s.mainContent),nestedTokens:o}),customNestedParser:r},t);if(i)return{type:"taskList",raw:i.raw,items:i.items}}},markdownOptions:{indentsContent:!0},addCommands(){return{toggleTaskList:()=>({commands:n})=>n.toggleList(this.name,this.options.itemTypeName)}},addKeyboardShortcuts(){return{"Mod-Shift-9":()=>this.editor.commands.toggleTaskList()}}});j.create({name:"listKit",addExtensions(){const n=[];return this.options.bulletList!==!1&&n.push(vd.configure(this.options.bulletList)),this.options.listItem!==!1&&n.push(Nd.configure(this.options.listItem)),this.options.listKeymap!==!1&&n.push(Rd.configure(this.options.listKeymap)),this.options.orderedList!==!1&&n.push(Id.configure(this.options.orderedList)),this.options.taskItem!==!1&&n.push(Fk.configure(this.options.taskItem)),this.options.taskList!==!1&&n.push(Vk.configure(this.options.taskList)),n}});const ur=" ",Zi=" ",Wk=_.create({name:"paragraph",priority:1e3,addOptions(){return{HTMLAttributes:{}}},group:"block",content:"inline*",parseHTML(){return[{tag:"p"}]},renderHTML({HTMLAttributes:n}){return["p",H(this.options.HTMLAttributes,n),0]},parseMarkdown:(n,e)=>{const t=n.tokens||[];if(t.length===1&&t[0].type==="image")return e.parseChildren([t[0]]);const r=e.parseInline(t);return t.length===1&&t[0].type==="text"&&(t[0].raw===ur||t[0].text===ur||t[0].raw===Zi||t[0].text===Zi)&&r.length===1&&r[0].type==="text"&&(r[0].text===ur||r[0].text===Zi)?e.createNode("paragraph",void 0,[]):e.createNode("paragraph",void 0,r)},renderMarkdown:(n,e,t)=>{if(!n)return"";const r=Array.isArray(n.content)?n.content:[];if(r.length===0){var i,s;const o=Array.isArray(t==null||(i=t.previousNode)===null||i===void 0?void 0:i.content)?t.previousNode.content:[];return(t==null||(s=t.previousNode)===null||s===void 0?void 0:s.type)==="paragraph"&&o.length===0?ur:""}return e.renderChildren(r)},addCommands(){return{setParagraph:()=>({commands:n})=>n.setNode(this.name)}},addKeyboardShortcuts(){return{"Mod-Alt-0":()=>this.editor.commands.setParagraph()}}}),jk=/(?:^|\s)(~~(?!\s+~~)((?:[^~]+))~~(?!\s+~~))$/,_k=/(?:^|\s)(~~(?!\s+~~)((?:[^~]+))~~(?!\s+~~))/g,Uk=gt.create({name:"strike",addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:"s"},{tag:"del"},{tag:"strike"},{style:"text-decoration",consuming:!1,getAttrs:n=>n.includes("line-through")?{}:!1}]},renderHTML({HTMLAttributes:n}){return["s",H(this.options.HTMLAttributes,n),0]},markdownTokenName:"del",parseMarkdown:(n,e)=>e.applyMark("strike",e.parseInline(n.tokens||[])),renderMarkdown:(n,e)=>`~~${e.renderChildren(n)}~~`,addCommands(){return{setStrike:()=>({commands:n})=>n.setMark(this.name),toggleStrike:()=>({commands:n})=>n.toggleMark(this.name),unsetStrike:()=>({commands:n})=>n.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-Shift-s":()=>this.editor.commands.toggleStrike()}},addInputRules(){return[zt({find:jk,type:this.type})]},addPasteRules(){return[ft({find:_k,type:this.type})]}}),Kk=_.create({name:"text",group:"inline",parseMarkdown:n=>({type:"text",text:n.text||""}),renderMarkdown:n=>n.text||""}),qk=gt.create({name:"underline",addOptions(){return{HTMLAttributes:{}}},parseHTML(){return[{tag:"u"},{style:"text-decoration",consuming:!1,getAttrs:n=>n.includes("underline")?{}:!1}]},renderHTML({HTMLAttributes:n}){return["u",H(this.options.HTMLAttributes,n),0]},parseMarkdown(n,e){return e.applyMark(this.name||"underline",e.parseInline(n.tokens||[]))},renderMarkdown(n,e){return`++${e.renderChildren(n)}++`},markdownTokenizer:{name:"underline",level:"inline",start(n){return n.indexOf("++")},tokenize(n,e,t){const r=/^(\+\+)([\s\S]+?)(\+\+)/.exec(n);if(!r)return;const i=r[2].trim();return{type:"underline",raw:r[0],text:i,tokens:t.inlineTokens(i)}}},addCommands(){return{setUnderline:()=>({commands:n})=>n.setMark(this.name),toggleUnderline:()=>({commands:n})=>n.toggleMark(this.name),unsetUnderline:()=>({commands:n})=>n.unsetMark(this.name)}},addKeyboardShortcuts(){return{"Mod-u":()=>this.editor.commands.toggleUnderline(),"Mod-U":()=>this.editor.commands.toggleUnderline()}}});function Jk(n={}){return new z({view(e){return new Gk(e,n)}})}class Gk{constructor(e,t){var r;this.editorView=e,this.cursorPos=null,this.element=null,this.timeout=-1,this.lastDragEvent=null,this.width=(r=t.width)!==null&&r!==void 0?r:1,this.color=t.color===!1?void 0:t.color||"black",this.class=t.class,this.handlers=["dragover","dragend","drop","dragleave"].map(i=>{let s=o=>{this[i](o)};return e.dom.addEventListener(i,s),{name:i,handler:s}})}destroy(){this.setCursor(null),this.handlers.forEach(({name:e,handler:t})=>this.editorView.dom.removeEventListener(e,t))}update(e,t){if(this.cursorPos!=null&&t.doc!=e.state.doc)if(this.lastDragEvent){let r=this.computeTarget(this.lastDragEvent);r==this.cursorPos?this.updateOverlay():this.setCursor(r)}else this.updateOverlay()}setCursor(e){e!=this.cursorPos&&(this.cursorPos=e,e==null?(this.element.parentNode.removeChild(this.element),this.element=null):this.updateOverlay())}updateOverlay(){let e=this.editorView.state.doc.resolve(this.cursorPos),t=!e.parent.inlineContent,r,i=this.editorView.dom,s=i.getBoundingClientRect(),o=s.width/i.offsetWidth,l=s.height/i.offsetHeight;if(t){let d=e.nodeBefore,f=e.nodeAfter;if(d||f){let h=this.editorView.nodeDOM(this.cursorPos-(d?d.nodeSize:0));if(h){let p=h.getBoundingClientRect(),m=d?p.bottom:p.top;d&&f&&(m=(m+this.editorView.nodeDOM(this.cursorPos).getBoundingClientRect().top)/2);let g=this.width/2*l;r={left:p.left,right:p.right,top:m-g,bottom:m+g}}}}if(!r){let d=this.editorView.coordsAtPos(this.cursorPos),f=this.width/2*o;r={left:d.left-f,right:d.left+f,top:d.top,bottom:d.bottom}}let a=this.editorView.dom.offsetParent;this.element||(this.element=a.appendChild(document.createElement("div")),this.class&&(this.element.className=this.class),this.element.style.cssText="position: absolute; z-index: 50; pointer-events: none;",this.color&&(this.element.style.backgroundColor=this.color)),this.element.classList.toggle("prosemirror-dropcursor-block",t),this.element.classList.toggle("prosemirror-dropcursor-inline",!t);let c,u;if(!a||a==document.body&&getComputedStyle(a).position=="static")c=-pageXOffset,u=-pageYOffset;else{let d=a.getBoundingClientRect(),f=d.width/a.offsetWidth,h=d.height/a.offsetHeight;c=d.left-a.scrollLeft*f,u=d.top-a.scrollTop*h}this.element.style.left=(r.left-c)/o+"px",this.element.style.top=(r.top-u)/l+"px",this.element.style.width=(r.right-r.left)/o+"px",this.element.style.height=(r.bottom-r.top)/l+"px"}scheduleRemoval(e){clearTimeout(this.timeout),this.timeout=setTimeout(()=>this.setCursor(null),e)}computeTarget(e){let t=this.editorView.posAtCoords({left:e.clientX,top:e.clientY}),r=t&&t.inside>=0&&this.editorView.state.doc.nodeAt(t.inside),i=r&&r.type.spec.disableDropCursor,s=typeof i=="function"?i(this.editorView,t,e):i;if(!t||s)return null;let o=t.pos;if(this.editorView.dragging&&this.editorView.dragging.slice){let l=rc(this.editorView.state.doc,o,this.editorView.dragging.slice);l!=null&&(o=l)}return o}dragover(e){if(!this.editorView.editable)return;this.lastDragEvent=e;let t=this.computeTarget(e);t!=null&&(this.setCursor(t),this.scheduleRemoval(5e3))}dragend(){this.scheduleRemoval(20)}drop(){this.scheduleRemoval(20)}dragleave(e){this.editorView.dom.contains(e.relatedTarget)||this.setCursor(null)}}class q extends N{constructor(e){super(e,e)}map(e,t){let r=e.resolve(t.map(this.head));return q.valid(r)?new q(r):N.near(r)}content(){return x.empty}eq(e){return e instanceof q&&e.head==this.head}toJSON(){return{type:"gapcursor",pos:this.head}}static fromJSON(e,t){if(typeof t.pos!="number")throw new RangeError("Invalid input for GapCursor.fromJSON");return new q(e.resolve(t.pos))}getBookmark(){return new To(this.anchor)}static valid(e){let t=e.parent;if(t.inlineContent||!Yk(e)||!Xk(e))return!1;let r=t.type.spec.allowGapCursor;if(r!=null)return r;let i=t.contentMatchAt(e.index()).defaultType;return i&&i.isTextblock}static findGapCursorFrom(e,t,r=!1){e:for(;;){if(!r&&q.valid(e))return e;let i=e.pos,s=null;for(let o=e.depth;;o--){let l=e.node(o);if(t>0?e.indexAfter(o)0){s=l.child(t>0?e.indexAfter(o):e.index(o)-1);break}else if(o==0)return null;i+=t;let a=e.doc.resolve(i);if(q.valid(a))return a}for(;;){let o=t>0?s.firstChild:s.lastChild;if(!o){if(s.isAtom&&!s.isText&&!T.isSelectable(s)){e=e.doc.resolve(i+s.nodeSize*t),r=!1;continue e}break}s=o,i+=t;let l=e.doc.resolve(i);if(q.valid(l))return l}return null}}}q.prototype.visible=!1;q.findFrom=q.findGapCursorFrom;N.jsonID("gapcursor",q);class To{constructor(e){this.pos=e}map(e){return new To(e.map(this.pos))}resolve(e){let t=e.resolve(this.pos);return q.valid(t)?new q(t):N.near(t)}}function Ld(n){return n.isAtom||n.spec.isolating||n.spec.createGapCursor}function Yk(n){for(let e=n.depth;e>=0;e--){let t=n.index(e),r=n.node(e);if(t==0){if(r.type.spec.isolating)return!0;continue}for(let i=r.child(t-1);;i=i.lastChild){if(i.childCount==0&&!i.inlineContent||Ld(i.type))return!0;if(i.inlineContent)return!1}}return!0}function Xk(n){for(let e=n.depth;e>=0;e--){let t=n.indexAfter(e),r=n.node(e);if(t==r.childCount){if(r.type.spec.isolating)return!0;continue}for(let i=r.child(t);;i=i.firstChild){if(i.childCount==0&&!i.inlineContent||Ld(i.type))return!0;if(i.inlineContent)return!1}}return!0}function Qk(){return new z({props:{decorations:nw,createSelectionBetween(n,e,t){return e.pos==t.pos&&q.valid(t)?new q(t):null},handleClick:ew,handleKeyDown:Zk,handleDOMEvents:{beforeinput:tw}}})}const Zk=lo({ArrowLeft:dr("horiz",-1),ArrowRight:dr("horiz",1),ArrowUp:dr("vert",-1),ArrowDown:dr("vert",1)});function dr(n,e){const t=n=="vert"?e>0?"down":"up":e>0?"right":"left";return function(r,i,s){let o=r.selection,l=e>0?o.$to:o.$from,a=o.empty;if(o instanceof v){if(!s.endOfTextblock(t)||l.depth==0)return!1;a=!1,l=r.doc.resolve(e>0?l.after():l.before())}let c=q.findGapCursorFrom(l,e,a);return c?(i&&i(r.tr.setSelection(new q(c))),!0):!1}}function ew(n,e,t){if(!n||!n.editable)return!1;let r=n.state.doc.resolve(e);if(!q.valid(r))return!1;let i=n.posAtCoords({left:t.clientX,top:t.clientY});return i&&i.inside>-1&&T.isSelectable(n.state.doc.nodeAt(i.inside))?!1:(n.dispatch(n.state.tr.setSelection(new q(r))),!0)}function tw(n,e){if(e.inputType!="insertCompositionText"||!(n.state.selection instanceof q))return!1;let{$from:t}=n.state.selection,r=t.parent.contentMatchAt(t.index()).findWrapping(n.state.schema.nodes.text);if(!r)return!1;let i=b.empty;for(let o=r.length-1;o>=0;o--)i=b.from(r[o].createAndFill(null,i));let s=n.state.tr.replace(t.pos,t.pos,new x(i,0,0));return s.setSelection(v.near(s.doc.resolve(t.pos+1))),n.dispatch(s),!1}function nw(n){if(!(n.selection instanceof q))return null;let e=document.createElement("div");return e.className="ProseMirror-gapcursor",I.create(n.doc,[Q.widget(n.selection.head,e,{key:"gapcursor"})])}j.create({name:"characterCount",addOptions(){return{limit:null,autoTrim:!0,mode:"textSize",textCounter:n=>n.length,wordCounter:n=>n.split(" ").filter(e=>e!=="").length}},addStorage(){return{characters:()=>0,words:()=>0}},onBeforeCreate(){this.storage.characters=n=>{const e=n?.node||this.editor.state.doc;if((n?.mode||this.options.mode)==="textSize"){const t=e.textBetween(0,e.content.size,void 0," ");return this.options.textCounter(t)}return e.nodeSize},this.storage.words=n=>{const e=n?.node||this.editor.state.doc,t=e.textBetween(0,e.content.size," "," ");return this.options.wordCounter(t)}},addProseMirrorPlugins(){let n=!1;return[new z({key:new W("characterCount"),appendTransaction:(e,t,r)=>{if(n)return;const i=this.options.limit,s=this.options.autoTrim;if(i==null||i===0||s===!1){n=!0;return}const o=this.storage.characters({node:r.doc});if(o>i){const l=o-i,a=0,c=l;console.warn(`[CharacterCount] Initial content exceeded limit of ${i} characters. Content was automatically trimmed.`);const u=r.tr.deleteRange(a,c);return n=!0,u}n=!0},filterTransaction:(e,t)=>{const r=this.options.limit;if(!e.docChanged||r===0||r===null||r===void 0)return!0;const i=this.storage.characters({node:t.doc}),s=this.storage.characters({node:e.doc});if(s<=r||i>r&&s>r&&s<=i)return!0;if(i>r&&s>r&&s>i||!e.getMeta("paste"))return!1;const o=e.selection.$head.pos,l=o-(s-r),a=o;return e.deleteRange(l,a),!(this.storage.characters({node:e.doc})>r)}})]}});const rw=j.create({name:"dropCursor",addOptions(){return{color:"currentColor",width:1,class:void 0}},addProseMirrorPlugins(){return[Jk(this.options)]}});j.create({name:"focus",addOptions(){return{className:"has-focus",mode:"all"}},addProseMirrorPlugins(){return[new z({key:new W("focus"),props:{decorations:({doc:n,selection:e})=>{const{isEditable:t,isFocused:r}=this.editor,{anchor:i}=e,s=[];if(!t||!r)return I.create(n,[]);let o=0;this.options.mode==="deepest"&&n.descendants((a,c)=>{if(!a.isText){if(!(i>=c&&i<=c+a.nodeSize-1))return!1;o+=1}});let l=0;return n.descendants((a,c)=>{if(a.isText||!(i>=c&&i<=c+a.nodeSize-1))return!1;if(l+=1,this.options.mode==="deepest"&&o-l>0||this.options.mode==="shallowest"&&l>1)return this.options.mode==="deepest";s.push(Q.node(c,c+a.nodeSize,{class:this.options.className}))}),I.create(n,s)}}})]}});const iw=j.create({name:"gapCursor",addProseMirrorPlugins(){return[Qk()]},extendNodeSchema(n){var e;const t={name:n.name,options:n.options,storage:n.storage};return{allowGapCursor:(e=L(M(n,"allowGapCursor",t)))!==null&&e!==void 0?e:null}}}),Pd="placeholder",xa=new W("tiptap__placeholder");function zd(n){const{editor:e,placeholder:t,dataAttribute:r,pos:i,node:s,isEmptyDoc:o,hasAnchor:l,classes:{emptyNode:a,emptyEditor:c}}=n,u=[a];return o&&u.push(c),Q.node(i,i+s.nodeSize,{class:u.join(" "),[r]:typeof t=="function"?t({editor:e,node:s,pos:i,hasAnchor:l}):t})}function Bd(n,e){return typeof n=="function"?n(e):n}function $d({editor:n,options:e,dataAttribute:t,doc:r,selection:i,from:s,to:o}){const{anchor:l}=i,a=[],c=n.isEmpty;return r.nodesBetween(s,o,(u,d)=>{const f=l>=d&&l<=d+u.nodeSize,h=!u.isLeaf&&Jn(u);return u.type.isTextblock&&(f||!e.showOnlyCurrent)&&h&&a.push(zd({editor:n,isEmptyDoc:c,dataAttribute:t,hasAnchor:f,placeholder:e.placeholder,classes:{emptyEditor:e.emptyEditorClass,emptyNode:Bd(e.emptyNodeClass,{editor:n,node:u,pos:d,hasAnchor:f})},node:u,pos:d})),e.includeChildren}),a}function Hd({editor:n,options:e,dataAttribute:t,doc:r,selection:i}){if(!(n.isEditable||!e.showOnlyWhenEditable))return null;const{anchor:s}=i,o=[],l=n.isEmpty;if(e.showOnlyCurrent&&!e.includeChildren){const a=r.resolve(s),c=a.depth>0?a.node(1):a.nodeAfter,u=a.depth>0?a.before(1):s;if(c&&c.type.isTextblock&&Jn(c)){const d=s>=u&&s<=u+c.nodeSize;o.push(zd({editor:n,isEmptyDoc:l,dataAttribute:t,hasAnchor:d,placeholder:e.placeholder,classes:{emptyEditor:e.emptyEditorClass,emptyNode:Bd(e.emptyNodeClass,{editor:n,node:c,pos:u,hasAnchor:d})},node:c,pos:u}))}}else o.push(...$d({editor:n,options:e,dataAttribute:t,doc:r,selection:i,from:0,to:r.content.size}));return I.create(r,o)}function An(n,e){const t=n.resolve(e);if(t.depth===0){var r;const s=(r=t.nodeAfter)!==null&&r!==void 0?r:t.nodeBefore;if(!s)return{from:e,to:e};const o=t.nodeAfter?e:e-s.nodeSize;return{from:o,to:o+s.nodeSize}}const i=t.before(1);return{from:i,to:i+t.node(1).nodeSize}}function Nn(n,e){return{from:Math.max(0,e.from-1),to:Math.min(n.content.size,e.to-1)}}function sw(n,e,t){const r=[];return n.forEach((i,s)=>{const o=s,l=o+i.nodeSize,a=o+1,c=l+1;ae&&r.push({from:o,to:l})}),r}function ow(n){if(n.length===0)return[];const e=[...n].sort((r,i)=>r.from-i.from),t=[{...e[0]}];for(let r=1;re.from?t.push(Nn(n,An(n,Math.min(e.to,n.content.size+1)-1))):e.fromh.from>=c&&h.to<=u);d.length&&(l=l.remove(d));const f=$d({editor:t,options:r,dataAttribute:i,doc:s,selection:o,from:c,to:u});f.length&&(l=l.add(s,f))}return l}function dw({editor:n,options:e,dataAttribute:t}){return{init(r,i){const s=Hd({editor:n,options:e,dataAttribute:t,doc:i.doc,selection:i.selection});return s??I.empty},apply(r,i,s,o){return!r.docChanged&&!r.selectionSet?i:uw({decorations:i.map(r.mapping,r.doc),ranges:aw(r,s,o),editor:n,options:e,dataAttribute:t,doc:o.doc,selection:o.selection})}}}function fw(n){return n.replace(/\s+/g,"-").replace(/[^a-zA-Z0-9-]/g,"").replace(/^[0-9-]+/,"").replace(/^-+/,"").toLowerCase()}function hw({editor:n,options:e}){const t=e.dataAttribute?`data-${fw(e.dataAttribute)}`:`data-${Pd}`,r=e.showOnlyCurrent&&!e.includeChildren;return new z({key:xa,...r?{}:{state:dw({editor:n,options:e,dataAttribute:t})},props:{decorations:r?({doc:i,selection:s})=>Hd({editor:n,options:e,dataAttribute:t,doc:i,selection:s}):i=>{var s;return e.showOnlyWhenEditable&&!n.isEditable?I.empty:(s=xa.getState(i))!==null&&s!==void 0?s:I.empty}}})}j.create({name:"placeholder",addOptions(){return{emptyEditorClass:"is-editor-empty",emptyNodeClass:"is-empty",dataAttribute:Pd,placeholder:"Write something …",showOnlyWhenEditable:!0,showOnlyCurrent:!0,includeChildren:!1}},addProseMirrorPlugins(){return[hw({editor:this.editor,options:this.options})]}});function Fs(n,e){return!n.selection.empty&&!Nu(n.selection)&&e.isEditable}function pw(n,e){return Fs(n,e)&&!e.isFocused&&!e.view.dragging}function mw(){var n;(n=window.getSelection())===null||n===void 0||n.removeAllRanges()}function gw(n){n.focus()}j.create({name:"selection",addOptions(){return{className:"selection"}},addProseMirrorPlugins(){const{editor:n,options:e}=this;return[new z({key:new W("selection"),props:{decorations(t){return pw(t,n)?I.create(t.doc,[Q.inline(t.selection.from,t.selection.to,{class:e.className})]):null},handleDOMEvents:{blur(t){return Fs(t.state,n)&&mw(),!1},focus(t){return Fs(t.state,n)&&requestAnimationFrame(()=>{!n.isDestroyed&&t.hasFocus()&&gw(t)}),!1}}}})]}});function va({types:n,node:e}){return e&&Array.isArray(n)&&n.includes(e.type)||e?.type===n}const yw=j.create({name:"trailingNode",addOptions(){return{node:void 0,notAfter:[]}},addProseMirrorPlugins(){var n;const e=new W(this.name),t=this.options.node||((n=this.editor.schema.topNodeType.contentMatch.defaultType)===null||n===void 0?void 0:n.name)||"paragraph",r=Object.entries(this.editor.schema.nodes).map(([,i])=>i).filter(i=>(this.options.notAfter||[]).concat(t).includes(i.name));return[new z({key:e,appendTransaction:(i,s,o)=>{const{doc:l,tr:a,schema:c}=o,u=e.getState(o),d=l.content.size,f=c.nodes[t];if(!i.some(h=>h.getMeta("skipTrailingNode"))&&u)return a.insert(d,f.create())},state:{init:(i,s)=>{const o=s.tr.doc.lastChild;return!va({node:o,types:r})},apply:(i,s)=>{if(!i.docChanged||i.getMeta("__uniqueIDTransaction"))return s;const o=i.doc.lastChild;return!va({node:o,types:r})}}})]}}),bw=j.create({name:"undoRedo",addOptions(){return{depth:100,newGroupDelay:500}},addCommands(){return{undo:()=>({state:n,dispatch:e})=>uu(n,e),redo:()=>({state:n,dispatch:e})=>du(n,e)}},addProseMirrorPlugins(){return[fm(this.options)]},addKeyboardShortcuts(){return{"Mod-z":()=>this.editor.commands.undo(),"Shift-Mod-z":()=>this.editor.commands.redo(),"Mod-y":()=>this.editor.commands.redo(),"Mod-я":()=>this.editor.commands.undo(),"Shift-Mod-я":()=>this.editor.commands.redo()}}}),kw=j.create({name:"starterKit",addExtensions(){const n=[];if(this.options.bold!==!1&&n.push(fb.configure(this.options.bold)),this.options.blockquote!==!1&&n.push(lb.configure(this.options.blockquote)),this.options.bulletList!==!1&&n.push(vd.configure(this.options.bulletList)),this.options.code!==!1&&n.push(gb.configure(this.options.code)),this.options.codeBlock!==!1&&n.push(kb.configure(this.options.codeBlock)),this.options.document!==!1&&n.push(wb.configure(this.options.document)),this.options.dropcursor!==!1&&n.push(rw.configure(this.options.dropcursor)),this.options.gapcursor!==!1&&n.push(iw.configure(this.options.gapcursor)),this.options.hardBreak!==!1&&n.push(Sb.configure(this.options.hardBreak)),this.options.heading!==!1&&n.push(Cb.configure(this.options.heading)),this.options.undoRedo!==!1&&n.push(bw.configure(this.options.undoRedo)),this.options.horizontalRule!==!1&&n.push(xb.configure(this.options.horizontalRule)),this.options.italic!==!1&&n.push(Ab.configure(this.options.italic)),this.options.listItem!==!1&&n.push(Nd.configure(this.options.listItem)),this.options.listKeymap!==!1){var e;n.push(Rd.configure((e=this.options)===null||e===void 0?void 0:e.listKeymap))}if(this.options.link!==!1){var t;n.push(ak.configure((t=this.options)===null||t===void 0?void 0:t.link))}if(this.options.orderedList!==!1&&n.push(Id.configure(this.options.orderedList)),this.options.paragraph!==!1&&n.push(Wk.configure(this.options.paragraph)),this.options.strike!==!1&&n.push(Uk.configure(this.options.strike)),this.options.text!==!1&&n.push(Kk.configure(this.options.text)),this.options.underline!==!1){var r;n.push(qk.configure((r=this.options)===null||r===void 0?void 0:r.underline))}if(this.options.trailingNode!==!1){var i;n.push(yw.configure((i=this.options)===null||i===void 0?void 0:i.trailingNode))}return n}});var ww=kw;const Fd={tabWysiwyg:"WYSIWYG",tabSource:"Source",toolbar:"Formatting",paragraph:"Paragraph",heading2:"Heading 2",heading3:"Heading 3",heading4:"Heading 4",bold:"Bold",italic:"Italic",bulletList:"Bullet list",orderedList:"Numbered list",link:"Link",blockquote:"Quote",insertTable:"Insert table",addRow:"Add row",deleteRow:"Delete row",addColumn:"Add column",deleteColumn:"Delete column",deleteTable:"Delete table",image:"Image",embed:"Embed video",rawHtml:"HTML block",undo:"Undo",redo:"Redo",linkUrl:"Link URL",linkApply:"Apply",linkRemove:"Remove link",linkInvalid:"Links must use http, https, mailto or a relative URL.",embedUrl:"YouTube URL",embedInsert:"Insert",embedInvalid:"This video URL is not supported. Paste a YouTube link.",cancel:"Cancel",uploading:"Uploading {name}…",uploadFailed:"Upload failed: {error}",uploadTimeout:"The upload of {name} took too long.",notAnImage:"Only JPEG, PNG, GIF and WebP images can be uploaded.",altText:"Alt text (required)",caption:"Caption (optional)",altRequired:"Enter the alt text.",insertImage:"Insert image",rawHtmlCard:"HTML block",editAsHtml:"Edit as HTML",embedCard:"Embedded video"},Sw={tabWysiwyg:"WYSIWYG",tabSource:"Źródło",toolbar:"Formatowanie",paragraph:"Akapit",heading2:"Nagłówek 2",heading3:"Nagłówek 3",heading4:"Nagłówek 4",bold:"Pogrubienie",italic:"Kursywa",bulletList:"Lista punktowana",orderedList:"Lista numerowana",link:"Link",blockquote:"Cytat",insertTable:"Wstaw tabelę",addRow:"Dodaj wiersz",deleteRow:"Usuń wiersz",addColumn:"Dodaj kolumnę",deleteColumn:"Usuń kolumnę",deleteTable:"Usuń tabelę",image:"Obraz",embed:"Osadź wideo",rawHtml:"Blok HTML",undo:"Cofnij",redo:"Ponów",linkUrl:"Adres linku",linkApply:"Zastosuj",linkRemove:"Usuń link",linkInvalid:"Link musi używać http, https, mailto albo adresu względnego.",embedUrl:"Adres filmu YouTube",embedInsert:"Wstaw",embedInvalid:"Ten adres filmu nie jest obsługiwany. Wklej link do YouTube.",cancel:"Anuluj",uploading:"Wysyłanie {name}…",uploadFailed:"Wysyłanie nie powiodło się: {error}",uploadTimeout:"Wysyłanie {name} trwało zbyt długo.",notAnImage:"Można wysłać tylko obrazy JPEG, PNG, GIF i WebP.",altText:"Tekst alternatywny (wymagany)",caption:"Podpis (opcjonalny)",altRequired:"Wpisz tekst alternatywny.",insertImage:"Wstaw obraz",rawHtmlCard:"Blok HTML",editAsHtml:"Edytuj jako HTML",embedCard:"Osadzone wideo"},Cw={en:Fd,pl:Sw};function jn(n){const e=(n??"").toLowerCase().split(/[-_]/)[0]??"";return Cw[e]??Fd}function es(n,e){return n.replace(/\{(\w+)\}/g,(t,r)=>e[r]??t)}const Vs="blogeditor-edit-html",xw=["footer","section","aside","header","nav","details","style","div","article","main","address","dl","iframe","video","audio","picture","object","embed","form","svg","math","script","noscript"],vw=/[\x00-\x20\x7f]+/g,Mw=/^([a-z][a-z0-9+.-]*):/i,Tw=["http","https","mailto"];function Ws(n){if(n==null)return!1;const e=Mw.exec(n.replace(vw,""));if(e&&!Tw.includes(e[1].toLowerCase()))return!1;try{return new URL(n,"https://journal.invalid/"),!0}catch{return!1}}const Ew={orderedList:["start","type"],link:["href","target","rel","class","title"],image:["src","alt","title","width","height"],figureImage:["src","alt","title","width","height"],tableCell:["colspan","rowspan","colwidth"],tableHeader:["colspan","rowspan","colwidth"]},Aw=["paragraph","heading","blockquote","bulletList","orderedList","listItem","codeBlock","horizontalRule","hardBreak","table","tableRow","tableCell","tableHeader","image","figure","figureImage","figcaption","link"];function Vd(n){return/^on/i.test(n)}function Wd(n,e){const t={};let r=!1;for(const i of Array.from(n.attributes)){const s=i.name.toLowerCase();e.includes(s)||Vd(s)||(t[i.name]=i.value,r=!0)}return r?t:null}function jd(n){if(!n||typeof n!="object")return{};const e={};for(const[t,r]of Object.entries(n))Vd(t)||typeof r!="string"||(e[t]=r);return e}const Nw=j.create({name:"htmlAttributes",addGlobalAttributes(){return Aw.map(n=>({types:[n],attributes:{htmlAttrs:{default:null,keepOnSplit:!1,parseHTML:e=>Wd(e,Ew[n]??[]),renderHTML:e=>jd(e.htmlAttrs)}}}))}}),Ow=gt.create({name:"span",priority:40,addAttributes(){return{htmlAttrs:{default:null,parseHTML:n=>Wd(n,[]),renderHTML:n=>jd(n.htmlAttrs)}}},parseHTML(){return[{tag:"span",getAttrs:n=>n.attributes.length>0?null:!1}]},renderHTML({HTMLAttributes:n}){return["span",n,0]}});let Ma;function _d(){return Ma??=document.implementation.createHTMLDocument(""),Ma}const Rw=_.create({name:"rawHtml",group:"block",atom:!0,selectable:!0,draggable:!0,priority:10,addOptions(){return{labels:jn("en")}},addAttributes(){return{html:{default:"",parseHTML:n=>n.outerHTML,renderHTML:()=>({})}}},parseHTML(){return[...xw,"figure"].map(n=>({tag:n,priority:10}))},renderHTML({node:n}){const e=_d().createElement("template");return e.innerHTML=String(n.attrs.html??""),e.content},addCommands(){return{insertRawHtml:n=>({commands:e})=>e.insertContent({type:this.name,attrs:{html:n}})}},addNodeView(){const n=this.options.labels;return({node:e})=>{const t=document.createElement("div");t.className="blogeditor__raw",t.contentEditable="false";const r=document.createElement("div");r.className="blogeditor__card-head";const i=document.createElement("span");i.textContent=n.rawHtmlCard;const s=document.createElement("button");s.type="button",s.textContent=n.editAsHtml,r.append(i,s);const o=document.createElement("pre");o.className="blogeditor__raw-source",o.textContent=String(e.attrs.html??""),t.append(r,o);let l=e;return s.addEventListener("click",a=>{a.preventDefault(),t.dispatchEvent(new CustomEvent(Vs,{bubbles:!0,detail:{html:String(l.attrs.html??"")}}))}),{dom:t,update:a=>a.type!==l.type?!1:(l=a,o.textContent=String(a.attrs.html??""),!0),stopEvent:a=>a.target===s,ignoreMutation:()=>!0}}}}),Dw=_.create({name:"embed",group:"block",atom:!0,selectable:!0,draggable:!0,priority:70,addOptions(){return{labels:jn("en")}},addAttributes(){return{provider:{default:null,parseHTML:n=>n.getAttribute("data-embed"),renderHTML:()=>({})},id:{default:null,parseHTML:n=>n.getAttribute("data-id"),renderHTML:()=>({})}}},parseHTML(){return[{tag:"figure[data-embed]",priority:70,getAttrs:n=>{const e=n,t=e.getAttribute("data-embed")??"",r=e.getAttribute("data-id")??"";return e.attributes.length!==2||e.childNodes.length!==0||!_i(t)||!Rt[t].idPattern.test(r)?!1:null}}]},renderHTML({node:n}){return["figure",{"data-embed":n.attrs.provider,"data-id":n.attrs.id}]},addCommands(){return{setEmbed:({provider:n,id:e})=>({commands:t})=>!_i(n)||!Rt[n].idPattern.test(e)?!1:t.insertContent({type:this.name,attrs:{provider:n,id:e}})}},addNodeView(){const n=this.options.labels;return({node:e})=>{const t=document.createElement("div");t.className="blogeditor__embed",t.contentEditable="false";const r=s=>{const o=String(s.attrs.provider??""),l=_i(o)?Rt[o].name:o;t.textContent=`${n.embedCard}: ${l} ${String(s.attrs.id??"")}`};r(e);let i=e;return{dom:t,update:s=>s.type!==i.type?!1:(i=s,r(s),!0),ignoreMutation:()=>!0}}}});function Iw(n){if(n.hasAttribute("data-embed"))return!1;const e=[];for(const i of Array.from(n.childNodes))if(i.nodeType===1)e.push(i);else{if(i.nodeType===3&&/[^ \t\r\n\f]/.test(i.nodeValue??""))return!1;if(i.nodeType!==3)return!1}if(e.length<1||e.length>2)return!1;const t=e[0];if(t.nodeName!=="IMG")return!1;const r=t.getAttribute("src");return!r||/^\s*data:/i.test(r)?!1:e.length===1||e[1].nodeName==="FIGCAPTION"}const Lw=_.create({name:"figure",group:"block",content:"figureImage figcaption?",draggable:!0,isolating:!0,priority:60,parseHTML(){return[{tag:"figure",priority:60,getAttrs:n=>Iw(n)?null:!1}]},renderHTML({HTMLAttributes:n}){return["figure",n,0]},addCommands(){return{setFigure:({src:n,alt:e,caption:t})=>({commands:r})=>{const i=[{type:"figureImage",attrs:{src:n,alt:e}}];return t&&i.push({type:"figcaption",content:[{type:"text",text:t}]}),r.insertContent({type:this.name,content:i})}}}}),Pw=_.create({name:"figureImage",atom:!0,selectable:!1,priority:60,addAttributes(){return{src:{default:null},alt:{default:null},title:{default:null},width:{default:null},height:{default:null}}},parseHTML(){return[{tag:'img[src]:not([src^="data:"])',context:"figure/",priority:60}]},renderHTML({HTMLAttributes:n}){return["img",n]}}),zw=_.create({name:"figcaption",content:"inline*",priority:60,parseHTML(){return[{tag:"figcaption",context:"figure/"}]},renderHTML({HTMLAttributes:n}){return["figcaption",n,0]}}),Bw=ld.extend({renderHTML({HTMLAttributes:n}){return["table",H(this.options.HTMLAttributes,n),["tbody",0]]}});function Ud(n){const{align:e,...t}=n??{};return t}const $w=rd.extend({addAttributes(){return Ud(this.parent?.())}}),Hw=id.extend({addAttributes(){return Ud(this.parent?.())}});function Fw(n=jn("en")){return[ww.configure({trailingNode:!1,link:{openOnClick:!1,HTMLAttributes:{target:null,rel:null,class:null},isAllowedUri:e=>Ws(e)}}),jy.configure({inline:!0,allowBase64:!1}),Bw,sd,Hw,$w,Lw,Pw,zw,Dw.configure({labels:n}),Rw.configure({labels:n}),Ow,Nw]}const Kd=new Set(["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"]),qd=new Set(["script","style","textarea","title","xmp","iframe","noembed","noframes"]),Jd=/^<\/?([a-zA-Z][^\s/>]*)/;function ai(n,e){let t="",r="";for(let i=e+1;i")return i+1;/\s/.test(s)||(r=s)}return-1}function Gd(n,e,t){const r=new RegExp(`])`,"ig");r.lastIndex=e;const i=r.exec(n);return i?ai(n,i.index):-1}function Vw(n,e,t){const r=[t];let i=e;for(;r.length>0;){const s=n.indexOf("<",i);if(s<0)return-1;if(n.startsWith("",s+4);if(c<0)return-1;i=c+3;continue}const o=Jd.exec(n.slice(s,s+64));if(!o){i=s+1;continue}const l=o[1].toLowerCase(),a=ai(n,s);if(a<0)return-1;if(i=a,n[s+1]==="/"){const c=r.lastIndexOf(l);c>=0&&(r.length=c);continue}if(!(Kd.has(l)||n[a-2]==="/")){if(qd.has(l)){if(i=Gd(n,a,l),i<0)return-1;continue}r.push(l)}}return i}function Ww(n){const e=[];let t=0;for(;t",t+4);if(i<0)return null;t=i+3}else if(n.startsWith("")}function Ta(n,e){const t=Ww(n);if(!t)return null;const r=xt(n).innerHTML,i=t.map(c=>xt(c).innerHTML).join("");if(r!==i)return null;const s=Ke.fromSchema(e),o=t.map(c=>{if(jw(c))return{html:c,nodes:[]};const u=[];return s.parseSlice(xt(c)).content.forEach(d=>u.push(d)),{html:c,nodes:u}}),l=[];let a="";for(const c of o){if(c.nodes.length===0){a+=c.html;continue}l.push({before:a,html:c.html,nodes:c.nodes}),a=""}return{blocks:l,trailing:a}}function _w(n){for(const e of Array.from(n.querySelectorAll("table"))){const t=Array.from(e.children).find(i=>i.nodeName==="TBODY"),r=t?.firstElementChild;if(t&&r&&r.children.length>0&&Array.from(r.children).every(i=>i.nodeName==="TH")){const i=e.ownerDocument.createElement("thead");i.append(r),e.insertBefore(i,t),t.children.length===0&&t.remove()}}for(const e of Array.from(n.querySelectorAll("td, th"))){const t=e.childNodes.length===1?e.firstChild:null;t&&t.nodeName==="P"&&t.attributes.length===0&&e.replaceChildren(...Array.from(t.childNodes))}}function Uw(n,e){if(n.type.name==="rawHtml")return String(n.attrs.html??"");const t=_d(),r=t.createElement("div");return r.appendChild(e.serializeNode(n,{document:t})),_w(r),r.innerHTML}function ts(n,e,t){if(t+n.length>e.length)return!1;for(let r=0;rr&&l-n[o-1].nodes.length>=i&&ts(n[o-1].nodes,e,l-n[o-1].nodes.length);)o--,l-=n[o].nodes.length,s.unshift({block:o,node:l});const a=o-r,c=l-i;if(a>0&&c>0){const u=c+1,d=new Int32Array((a+1)*u),f=(m,g)=>ts(n[r+m].nodes,e,i+g)&&i+g+n[r+m].nodes.length<=l;for(let m=a-1;m>=0;m--)for(let g=c-1;g>=0;g--){let y=Math.max(d[(m+1)*u+g],d[m*u+g+1]);if(f(m,g)){const k=n[r+m].nodes.length;y=Math.max(y,k+d[(m+1)*u+g+k])}d[m*u+g]=y}let h=0,p=0;for(;h=d[h*u+p+1]?h++:p++}}return t.concat(s)}function qw(n,e){const t=ht.fromSchema(n.schema),r=[];n.state.doc.forEach(u=>r.push(u));const i=e?.blocks??[],s=Kw(i,r);let o="",l=0,a=0;const c=(u,d)=>{if(d>a){u>l&&(o+=i[l].before);for(let f=a;f0||r.length===0)&&(o+=e.trailing),o}const dn=n=>n.isActive("table"),Jw=[[{command:"paragraph",glyph:"P",label:"paragraph",run:n=>n.chain().focus().setParagraph().run(),active:n=>n.isActive("paragraph")},{command:"heading2",glyph:"H2",label:"heading2",run:n=>n.chain().focus().toggleHeading({level:2}).run(),active:n=>n.isActive("heading",{level:2})},{command:"heading3",glyph:"H3",label:"heading3",run:n=>n.chain().focus().toggleHeading({level:3}).run(),active:n=>n.isActive("heading",{level:3})},{command:"heading4",glyph:"H4",label:"heading4",run:n=>n.chain().focus().toggleHeading({level:4}).run(),active:n=>n.isActive("heading",{level:4})}],[{command:"bold",glyph:"B",label:"bold",run:n=>n.chain().focus().toggleBold().run(),active:n=>n.isActive("bold")},{command:"italic",glyph:"I",label:"italic",run:n=>n.chain().focus().toggleItalic().run(),active:n=>n.isActive("italic")},{command:"link",glyph:"Link",label:"link",run:(n,e)=>e.openLink(),active:n=>n.isActive("link"),host:!0}],[{command:"bulletList",glyph:"•",label:"bulletList",run:n=>n.chain().focus().toggleBulletList().run(),active:n=>n.isActive("bulletList")},{command:"orderedList",glyph:"1.",label:"orderedList",run:n=>n.chain().focus().toggleOrderedList().run(),active:n=>n.isActive("orderedList")},{command:"blockquote",glyph:"“”",label:"blockquote",run:n=>n.chain().focus().toggleBlockquote().run(),active:n=>n.isActive("blockquote")}],[{command:"insertTable",glyph:"Table",label:"insertTable",run:n=>n.chain().focus().insertTable({rows:3,cols:3,withHeaderRow:!0}).run()},{command:"addRow",glyph:"+Row",label:"addRow",run:n=>n.chain().focus().addRowAfter().run(),enabled:dn},{command:"deleteRow",glyph:"−Row",label:"deleteRow",run:n=>n.chain().focus().deleteRow().run(),enabled:dn},{command:"addColumn",glyph:"+Col",label:"addColumn",run:n=>n.chain().focus().addColumnAfter().run(),enabled:dn},{command:"deleteColumn",glyph:"−Col",label:"deleteColumn",run:n=>n.chain().focus().deleteColumn().run(),enabled:dn},{command:"deleteTable",glyph:"×Table",label:"deleteTable",run:n=>n.chain().focus().deleteTable().run(),enabled:dn}],[{command:"image",glyph:"Image",label:"image",run:(n,e)=>e.pickImage(),host:!0},{command:"embed",glyph:"Video",label:"embed",run:(n,e)=>e.openEmbed(),host:!0},{command:"rawHtml",glyph:"HTML",label:"rawHtml",run:(n,e)=>e.insertRawHtml(),host:!0}],[{command:"undo",glyph:"Undo",label:"undo",run:n=>n.chain().focus().undo().run(),enabled:n=>n.can().undo()},{command:"redo",glyph:"Redo",label:"redo",run:n=>n.chain().focus().redo().run(),enabled:n=>n.can().redo()}]];function Gw(n){const{labels:e}=n,t=document.createElement("div");t.className="blogeditor__bar";const r=document.createElement("div");r.className="blogeditor__tools",r.setAttribute("role","toolbar"),r.setAttribute("aria-label",e.toolbar);const i=[];for(const f of Jw){const h=document.createElement("div");h.className="blogeditor__group";for(const p of f){const m=document.createElement("button");m.type="button",m.dataset.command=p.command,m.textContent=p.glyph,m.title=e[p.label],m.setAttribute("aria-label",e[p.label]),m.addEventListener("mousedown",g=>g.preventDefault()),m.addEventListener("click",()=>{const g=n.editor();g&&(!p.host&&!g.isEditable||p.run(g,n))}),h.append(m),i.push({spec:p,button:m})}r.append(h)}const s=document.createElement("div");s.className="blogeditor__tabs",s.setAttribute("role","tablist");const o=(f,h)=>{const p=document.createElement("button");return p.type="button",p.dataset.tab=f,p.setAttribute("role","tab"),p.textContent=h,p.addEventListener("click",()=>n.showSource(f==="source")),s.append(p),p},l=o("wysiwyg",e.tabWysiwyg),a=o("source",e.tabSource);t.append(r,s);let c=!1,u=!1;const d=()=>{const f=n.editor();for(const{spec:h,button:p}of i){h.active&&p.setAttribute("aria-pressed",String(!!f&&h.active(f)));const m=!!f&&!c&&!u&&(h.enabled?h.enabled(f):!0);p.disabled=!m}};return{element:t,refresh:d,selectTab:f=>{u=f,l.setAttribute("aria-selected",String(!f)),a.setAttribute("aria-selected",String(f)),d()},setDisabled:f=>{c=f,d()}}}const Ea="golem15-journal-blogeditor",Yw="summer-change",Xw="summer-upload",Aa="summer-upload-result",Yd=["image/jpeg","image/png","image/gif","image/webp"],Qw=6e4;class Zw extends HTMLElement{static observedAttributes=["disabled","invalid","locale"];#f="";#h="";#m="";#g=null;#o="clean";#e;#r=jn("en");#c;#y;#t;#b;#k;#n;#i;#l;#S=!1;#a=new Map;#u=[];constructor(){if(super(),Object.prototype.hasOwnProperty.call(this,"value")){const e=this.value;delete this.value,this.value=e}}get value(){switch(this.#o){case"source":return this.#h;case"wysiwyg":return this.#e?qw(this.#e,this.#g):this.#f;default:return this.#f}}set value(e){const t=typeof e=="string"?e:e==null?"":String(e);t!==this.value&&(this.#f=t,this.#o="clean",this.#t&&(this.#t.value=t),this.#C(t))}get editor(){return this.#e}connectedCallback(){if(this.#e)return;this.classList.add("blogeditor"),this.replaceChildren(),this.#r=jn(this.getAttribute("ui-locale"));const e=this.#r;this.#c=Gw({editor:()=>this.#e,labels:e,openLink:()=>this.#L(),openEmbed:()=>this.#z(),pickImage:()=>this.#k?.click(),insertRawHtml:()=>this.#$(),showSource:l=>this.showSource(l)}),this.#n=this.#M("link",e.linkUrl,[["apply",e.linkApply,()=>this.#P()],["remove",e.linkRemove,()=>this.#E()],["cancel",e.cancel,()=>this.#s(this.#n)]]),this.#i=this.#M("embed",e.embedUrl,[["insert",e.embedInsert,()=>this.#B()],["cancel",e.cancel,()=>this.#s(this.#i)]]),this.#l=this.#F();const t=document.createElement("div");t.className="blogeditor__content",this.#y=t;const r=document.createElement("textarea");r.className="blogeditor__source",r.spellcheck=!1,r.hidden=!0,r.setAttribute("aria-label",e.tabSource),r.value=this.value,r.addEventListener("input",()=>this.#I()),this.#t=r;const i=document.createElement("p");i.className="blogeditor__status",i.setAttribute("role","status"),i.setAttribute("aria-live","polite"),this.#b=i;const s=document.createElement("input");s.type="file",s.accept=Yd.join(","),s.multiple=!0,s.hidden=!0,s.addEventListener("change",()=>this.#H()),this.#k=s,this.append(this.#c.element,this.#n.root,this.#i.root,this.#l.root,t,r,i,s),this.addEventListener(Aa,this.#O),this.addEventListener(Vs,this.#A);const o=this.value;this.#m=o,this.#e=new zy({element:t,injectCSS:!1,editable:!this.hasAttribute("disabled"),extensions:Fw(e),content:o,editorProps:{handleDrop:(l,a,c,u)=>{if(u)return!1;const d=Array.from(a.dataTransfer?.files??[]).filter(Na);if(d.length===0)return!1;a.preventDefault();for(const f of d)this.#N(f);return!0}},onUpdate:({transaction:l,appendedTransactions:a})=>{!l.docChanged&&!a.some(c=>c.docChanged)||(this.#o="wysiwyg",this.#x())},onTransaction:()=>this.#c?.refresh()}),this.#g=Ta(o,this.#e.schema),this.#v(),this.showSource(!1)}disconnectedCallback(){this.removeEventListener(Aa,this.#O),this.removeEventListener(Vs,this.#A);for(const{timer:e}of this.#a.values())clearTimeout(e);this.#a.clear(),this.#u=[],this.#o==="wysiwyg"&&this.#e&&(this.#f=this.value,this.#o="clean"),this.#e?.destroy(),this.#e=void 0}attributeChangedCallback(){this.#v()}showSource(e){!this.#t||!this.#y||(e?this.#t.value=this.value:this.#S&&this.#o==="source"&&this.#h!==this.#m&&this.#C(this.#h),this.#S=e,this.#t.hidden=!e,this.#y.hidden=e,e&&(this.#s(this.#n),this.#s(this.#i)),this.#c?.selectTab(e))}#C(e){this.#m=e,this.#e&&(this.#e.chain().setMeta("addToHistory",!1).setContent(e,{emitUpdate:!1}).run(),this.#g=Ta(e,this.#e.schema))}#I(){this.#t&&(this.#h=this.#t.value,this.#o="source",this.#x())}#x(){this.dispatchEvent(new CustomEvent(Yw,{bubbles:!0,composed:!0,detail:{value:this.value}}))}#d(e){this.#b&&(this.#b.textContent=e)}#v(){const e=this.hasAttribute("disabled"),t=this.hasAttribute("invalid");this.#e&&this.#e.isEditable===e&&this.#e.setEditable(!e,!1),this.#c?.setDisabled(e),this.#t&&(this.#t.readOnly=e,t?this.#t.setAttribute("aria-invalid","true"):this.#t.removeAttribute("aria-invalid"));const r=this.#e?.view.dom;if(r){t?r.setAttribute("aria-invalid","true"):r.removeAttribute("aria-invalid");const i=this.getAttribute("locale");i?r.setAttribute("lang",i):r.removeAttribute("lang")}}#M(e,t,r){const i=document.createElement("div");i.className="blogeditor__form",i.dataset.form=e,i.hidden=!0;const s=document.createElement("label"),o=document.createElement("span");o.textContent=t;const l=document.createElement("input");l.type="text",l.name="url",l.autocomplete="off",l.addEventListener("keydown",u=>{u.key==="Enter"?(u.preventDefault(),r[0][2]()):u.key==="Escape"&&(u.preventDefault(),this.#s(c))}),s.append(o,l),i.append(s);for(const[u,d,f]of r)i.append(this.#w(u,d,f));const a=document.createElement("p");a.className="blogeditor__error",a.dataset.error="",a.setAttribute("aria-live","polite"),i.append(a);const c={root:i,error:a};return c}#w(e,t,r){const i=document.createElement("button");return i.type="button",i.dataset.action=e,i.textContent=t,i.addEventListener("click",r),i}#T(e,t=""){if(!e)return;for(const i of[this.#n,this.#i])i&&i!==e&&this.#s(i);e.error.textContent="",e.root.hidden=!1;const r=e.root.querySelector("input");r&&(r.value=t,r.focus())}#s(e){e&&(e.root.hidden=!0,e.error.textContent="")}#p(e,t="url"){return(e?.root.querySelector(`input[name="${t}"]`)?.value??"").trim()}#L(){if(!this.#e?.isEditable)return;const e=this.#e.getAttributes("link").href;this.#T(this.#n,typeof e=="string"?e:"")}#P(){const e=this.#e;if(!e||!this.#n)return;const t=this.#p(this.#n);if(t===""){this.#E();return}if(!Ws(t)){this.#n.error.textContent=this.#r.linkInvalid;return}const{empty:r}=e.state.selection;r&&!e.isActive("link")?e.chain().focus().insertContent({type:"text",text:t,marks:[{type:"link",attrs:{href:t}}]}).unsetMark("link").run():e.chain().focus().extendMarkRange("link").setLink({href:t}).run(),this.#s(this.#n)}#E(){this.#e?.chain().focus().extendMarkRange("link").unsetLink().run(),this.#s(this.#n)}#z(){this.#e?.isEditable&&this.#T(this.#i)}#B(){if(!this.#e||!this.#i)return;const e=Fy(this.#p(this.#i));if(!e){this.#i.error.textContent=this.#r.embedInvalid;return}this.#e.chain().focus().setEmbed(e).run(),this.#s(this.#i)}#$(){const e=this.#e;if(!e?.isEditable)return;const t=this.value,r="
";if(!e.chain().focus().insertRawHtml(r).run())return;const i=this.value;let s=0;for(;s{const t=e.detail?.html??"";this.showSource(!0);const r=this.#t;if(!r)return;r.focus();const i=t?r.value.indexOf(t):-1;i>=0&&r.setSelectionRange(i,i+t.length)};#H(){const e=this.#k;if(!e)return;const t=Array.from(e.files??[]),r=t.filter(Na);r.length{this.#a.delete(t)&&this.#d(es(this.#r.uploadTimeout,{name:r}))},Qw);this.#a.set(t,{name:r,timer:i}),this.#d(es(this.#r.uploading,{name:r})),this.dispatchEvent(new CustomEvent(Xw,{bubbles:!0,composed:!0,detail:{id:t,file:e}}))}#O=e=>{const t=e.detail??{},r=typeof t.id=="string"?t.id:"",i=this.#a.get(r);if(!i)return;clearTimeout(i.timer),this.#a.delete(r);const s=typeof t.url=="string"?t.url:"";if(typeof t.error=="string"||!s||!Ws(s)){const o=typeof t.error=="string"&&t.error?t.error:i.name;this.#d(es(this.#r.uploadFailed,{error:o}));return}this.#d(""),this.#u.push({url:s,name:i.name}),this.#R()};#F(){const e=this.#r,t=document.createElement("div");t.className="blogeditor__form",t.dataset.form="image",t.hidden=!0;const r=(s,o)=>{const l=document.createElement("label"),a=document.createElement("span");a.textContent=o;const c=document.createElement("input");return c.type="text",c.name=s,c.autocomplete="off",l.append(a,c),l};t.append(r("alt",e.altText),r("caption",e.caption)),t.append(this.#w("insert",e.insertImage,()=>this.#V())),t.append(this.#w("cancel",e.cancel,()=>this.#D()));const i=document.createElement("p");return i.className="blogeditor__error",i.dataset.error="",i.setAttribute("aria-live","polite"),t.append(i),{root:t,error:i}}#R(){const e=this.#l;if(!(!e||!e.root.hidden||this.#u.length===0)){for(const t of Array.from(e.root.querySelectorAll("input")))t.value="";e.error.textContent="",e.root.hidden=!1,e.root.querySelector('input[name="alt"]')?.focus()}}#V(){const e=this.#e,t=this.#l,r=this.#u[0];if(!e||!t||!r)return;const i=this.#p(t,"alt"),s=this.#p(t,"caption");if(!i){t.error.textContent=this.#r.altRequired;return}s?e.chain().focus().setFigure({src:r.url,alt:i,caption:s}).run():e.chain().focus().setImage({src:r.url,alt:i}).run(),this.#D()}#D(){this.#u.shift(),this.#l&&this.#s(this.#l),this.#R()}}function Na(n){return Yd.includes(n.type)}customElements.get(Ea)||customElements.define(Ea,Zw);export{Zw as BlogEditorElement,Ea as TAG}; diff --git a/assets/src/blogeditor/blogeditor.css b/assets/src/blogeditor/blogeditor.css index 383c568..72968a4 100644 --- a/assets/src/blogeditor/blogeditor.css +++ b/assets/src/blogeditor/blogeditor.css @@ -28,12 +28,90 @@ golem15-journal-blogeditor .blogeditor__bar { border-radius: 12px 12px 0 0; } +golem15-journal-blogeditor .blogeditor__tools { + display: flex; + flex-wrap: wrap; + gap: 4px 12px; +} + +golem15-journal-blogeditor .blogeditor__group { + display: flex; + flex-wrap: wrap; + gap: 2px; +} + golem15-journal-blogeditor .blogeditor__tabs { display: flex; gap: 2px; margin-left: auto; } +golem15-journal-blogeditor .blogeditor__form { + display: flex; + flex-wrap: wrap; + align-items: flex-end; + gap: 6px 8px; + padding: 8px; + border-bottom: 1px solid var(--c-border); + background: var(--c-surface); +} + +golem15-journal-blogeditor .blogeditor__form label { + display: flex; + flex: 1 1 220px; + flex-direction: column; + gap: 2px; + font-size: 12px; + color: var(--c-muted); +} + +golem15-journal-blogeditor .blogeditor__form input { + box-sizing: border-box; + width: 100%; + padding: 5px 8px; + border: 1px solid var(--c-border-strong); + border-radius: 6px; + background: var(--c-bg); + color: var(--c-text); + font: inherit; + font-size: 13px; +} + +golem15-journal-blogeditor .blogeditor__form input::placeholder { + color: var(--c-placeholder); +} + +golem15-journal-blogeditor .blogeditor__form input:focus { + outline: 2px solid var(--c-ring); + outline-offset: -1px; +} + +golem15-journal-blogeditor .blogeditor__form button[data-action="apply"], +golem15-journal-blogeditor .blogeditor__form button[data-action="insert"] { + background: var(--c-primary); + color: var(--c-on-primary); +} + +golem15-journal-blogeditor .blogeditor__error { + flex-basis: 100%; + margin: 0; + font-size: 12px; + color: var(--c-danger); +} + +golem15-journal-blogeditor .blogeditor__error:empty, +golem15-journal-blogeditor .blogeditor__status:empty { + display: none; +} + +golem15-journal-blogeditor .blogeditor__status { + margin: 0; + padding: 6px 12px; + border-top: 1px solid var(--c-border); + font-size: 12px; + color: var(--c-muted); +} + golem15-journal-blogeditor button { font: inherit; font-size: 13px; @@ -227,3 +305,80 @@ golem15-journal-blogeditor .ProseMirror img { max-width: 100%; height: auto; } + +golem15-journal-blogeditor .ProseMirror table { + border-collapse: collapse; + width: 100%; +} + +golem15-journal-blogeditor .ProseMirror :where(td, th) { + border: 1px solid var(--c-border-strong); + padding: 4px 8px; + vertical-align: top; +} + +golem15-journal-blogeditor .ProseMirror th { + background: var(--c-subtle); + font-weight: 600; + text-align: left; +} + +golem15-journal-blogeditor .ProseMirror :where(td, th) > p { + margin: 0; +} + +golem15-journal-blogeditor .ProseMirror .selectedCell { + background: var(--c-sel); +} + +golem15-journal-blogeditor .ProseMirror figure { + margin-left: 0; + margin-right: 0; +} + +golem15-journal-blogeditor .ProseMirror figcaption { + margin-top: 4px; + font-size: 13px; + color: var(--c-muted); +} + +/* Raw HTML and embed cards: never live markup. */ +golem15-journal-blogeditor .blogeditor__raw, +golem15-journal-blogeditor .blogeditor__embed { + border: 1px dashed var(--c-border-strong); + border-radius: 8px; + background: var(--c-subtle); + color: var(--c-muted); + font-size: 13px; +} + +golem15-journal-blogeditor .blogeditor__embed { + padding: 16px; + text-align: center; +} + +golem15-journal-blogeditor .blogeditor__card-head { + display: flex; + align-items: center; + justify-content: space-between; + gap: 8px; + padding: 4px 4px 4px 10px; + border-bottom: 1px dashed var(--c-border); +} + +golem15-journal-blogeditor .blogeditor__raw-source { + max-height: 160px; + margin: 0; + padding: 8px 10px; + overflow: auto; + background: transparent; + font-family: "DM Mono", ui-monospace, monospace; + font-size: 12px; + white-space: pre-wrap; +} + +golem15-journal-blogeditor .ProseMirror-selectednode.blogeditor__raw, +golem15-journal-blogeditor .ProseMirror-selectednode.blogeditor__embed, +golem15-journal-blogeditor .ProseMirror img.ProseMirror-selectednode { + outline: 2px solid var(--c-ring); +} diff --git a/assets/src/blogeditor/element.ts b/assets/src/blogeditor/element.ts index c2c95a4..3473602 100644 --- a/assets/src/blogeditor/element.ts +++ b/assets/src/blogeditor/element.ts @@ -1,12 +1,27 @@ import { Editor } from '@tiptap/core' -import StarterKit from '@tiptap/starter-kit' -import { serializeDocument } from './serializer' +import { parseEmbedUrl } from './embed' +import { EDIT_HTML_EVENT, isPolicyUrl, preservationExtensions } from './extensions' +import { format, labelsFor, type Labels } from './labels' +import { captureBlocks, serializeDocument, type Blocks } from './serializer' +import { buildToolbar, type Toolbar } from './toolbar' export const TAG = 'golem15-journal-blogeditor' export const CHANGE_EVENT = 'summer-change' +export const UPLOAD_EVENT = 'summer-upload' +export const UPLOAD_RESULT_EVENT = 'summer-upload-result' + +/** The image types the picker offers and the editor uploads (D-18). */ +export const IMAGE_TYPES = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'] +/** How long the element waits for summer-upload-result. */ +export const UPLOAD_TIMEOUT_MS = 60_000 type Mode = 'clean' | 'wysiwyg' | 'source' +interface InlineForm { + root: HTMLDivElement + error: HTMLParagraphElement +} + /** * BlogEditorElement is the Journal Blog Editor (D-01, D-03, D-13): a light-DOM * custom element with a WYSIWYG tab on TipTap and a Source tab that edits the @@ -17,7 +32,10 @@ type Mode = 'clean' | 'wysiwyg' | 'source' * invalid; a bubbling summer-change event with detail.value is dispatched on * user edits only. The element returns the exact string it was given until * the user edits, and setting value to the string it currently returns is a - * no-op. It never receives or sends credentials. + * no-op. Images are handed to the host page as summer-upload {id, file} and + * inserted when it answers summer-upload-result {id, url} (or shows + * {id, error}). It never receives or sends credentials and never sanitizes: + * the server does that on save. */ export class BlogEditorElement extends HTMLElement { static observedAttributes = ['disabled', 'invalid', 'locale'] @@ -28,12 +46,22 @@ export class BlogEditorElement extends HTMLElement { #sourceText = '' /** The string the editor content was last parsed from. */ #parsed = '' + /** That string split into top-level blocks, for block reuse. */ + #blocks: Blocks | null = null #mode: Mode = 'clean' #editor?: Editor + #labels: Labels = labelsFor('en') + #toolbar?: Toolbar #mount?: HTMLDivElement #textarea?: HTMLTextAreaElement - #tabs: { wysiwyg?: HTMLButtonElement; source?: HTMLButtonElement } = {} + #status?: HTMLParagraphElement + #fileInput?: HTMLInputElement + #linkForm?: InlineForm + #embedForm?: InlineForm + #imageForm?: InlineForm #showingSource = false + #pending = new Map }>() + #ready: { url: string; name: string }[] = [] constructor() { super() @@ -51,7 +79,7 @@ export class BlogEditorElement extends HTMLElement { case 'source': return this.#sourceText case 'wysiwyg': - return this.#editor ? serializeDocument(this.#editor) : this.#value + return this.#editor ? serializeDocument(this.#editor, this.#blocks) : this.#value default: return this.#value } @@ -62,9 +90,8 @@ export class BlogEditorElement extends HTMLElement { if (v === this.value) return // echo of our own summer-change this.#value = v this.#mode = 'clean' - this.#parsed = v if (this.#textarea) this.#textarea.value = v - this.#editor?.commands.setContent(v, { emitUpdate: false }) + this.#load(v) } /** The TipTap editor while the element is connected (toolbar and tests). */ @@ -76,16 +103,29 @@ export class BlogEditorElement extends HTMLElement { if (this.#editor) return this.classList.add('blogeditor') this.replaceChildren() + this.#labels = labelsFor(this.getAttribute('ui-locale')) + const labels = this.#labels - const bar = document.createElement('div') - bar.className = 'blogeditor__bar' - const tabs = document.createElement('div') - tabs.className = 'blogeditor__tabs' - tabs.setAttribute('role', 'tablist') - this.#tabs.wysiwyg = this.#tab('WYSIWYG', () => this.showSource(false)) - this.#tabs.source = this.#tab('Source', () => this.showSource(true)) - tabs.append(this.#tabs.wysiwyg, this.#tabs.source) - bar.append(tabs) + this.#toolbar = buildToolbar({ + editor: () => this.#editor, + labels, + openLink: () => this.#openLink(), + openEmbed: () => this.#openEmbed(), + pickImage: () => this.#fileInput?.click(), + insertRawHtml: () => this.#insertRawHtml(), + showSource: (on) => this.showSource(on), + }) + + this.#linkForm = this.#form('link', labels.linkUrl, [ + ['apply', labels.linkApply, () => this.#applyLink()], + ['remove', labels.linkRemove, () => this.#removeLink()], + ['cancel', labels.cancel, () => this.#close(this.#linkForm)], + ]) + this.#embedForm = this.#form('embed', labels.embedUrl, [ + ['insert', labels.embedInsert, () => this.#insertEmbed()], + ['cancel', labels.cancel, () => this.#close(this.#embedForm)], + ]) + this.#imageForm = this.#imageFormElement() const mount = document.createElement('div') mount.className = 'blogeditor__content' @@ -95,35 +135,80 @@ export class BlogEditorElement extends HTMLElement { textarea.className = 'blogeditor__source' textarea.spellcheck = false textarea.hidden = true + textarea.setAttribute('aria-label', labels.tabSource) textarea.value = this.value textarea.addEventListener('input', () => this.#sourceInput()) this.#textarea = textarea - this.append(bar, mount, textarea) + const status = document.createElement('p') + status.className = 'blogeditor__status' + status.setAttribute('role', 'status') + status.setAttribute('aria-live', 'polite') + this.#status = status - this.#parsed = this.value + const fileInput = document.createElement('input') + fileInput.type = 'file' + fileInput.accept = IMAGE_TYPES.join(',') + fileInput.multiple = true + fileInput.hidden = true + fileInput.addEventListener('change', () => this.#picked()) + this.#fileInput = fileInput + + this.append( + this.#toolbar.element, + this.#linkForm.root, + this.#embedForm.root, + this.#imageForm.root, + mount, + textarea, + status, + fileInput, + ) + + this.addEventListener(UPLOAD_RESULT_EVENT, this.#onUploadResult) + this.addEventListener(EDIT_HTML_EVENT, this.#onEditHtml) + + const initial = this.value + this.#parsed = initial this.#editor = new Editor({ element: mount, injectCSS: false, editable: !this.hasAttribute('disabled'), - extensions: [ - StarterKit.configure({ - trailingNode: false, - link: { openOnClick: false, HTMLAttributes: { target: null, rel: null, class: null } }, - }), - ], - content: this.#parsed, + extensions: preservationExtensions(labels), + content: initial, + editorProps: { + handleDrop: (_view, event, _slice, moved) => { + if (moved) return false + const files = Array.from((event as DragEvent).dataTransfer?.files ?? []).filter(isImage) + if (files.length === 0) return false + event.preventDefault() + for (const file of files) this.#upload(file) + return true + }, + }, onUpdate: ({ transaction, appendedTransactions }) => { if (!transaction.docChanged && !appendedTransactions.some((tr) => tr.docChanged)) return this.#mode = 'wysiwyg' this.#emitChange() }, + onTransaction: () => this.#toolbar?.refresh(), }) + this.#blocks = captureBlocks(initial, this.#editor.schema) this.#syncAttributes() this.showSource(false) } disconnectedCallback(): void { + this.removeEventListener(UPLOAD_RESULT_EVENT, this.#onUploadResult) + this.removeEventListener(EDIT_HTML_EVENT, this.#onEditHtml) + for (const { timer } of this.#pending.values()) clearTimeout(timer) + this.#pending.clear() + this.#ready = [] + // Keep an edited value readable while the element is detached. + if (this.#mode === 'wysiwyg' && this.#editor) { + this.#value = this.value + this.#mode = 'clean' + } this.#editor?.destroy() this.#editor = undefined } @@ -140,24 +225,27 @@ export class BlogEditorElement extends HTMLElement { } else if (this.#showingSource && this.#mode === 'source' && this.#sourceText !== this.#parsed) { // Re-parse only when the source text changed; the value stays the // exact text until the next WYSIWYG edit. - this.#parsed = this.#sourceText - this.#editor?.commands.setContent(this.#sourceText, { emitUpdate: false }) + this.#load(this.#sourceText) } this.#showingSource = on this.#textarea.hidden = !on this.#mount.hidden = on - this.#tabs.wysiwyg?.setAttribute('aria-selected', String(!on)) - this.#tabs.source?.setAttribute('aria-selected', String(on)) + if (on) { + this.#close(this.#linkForm) + this.#close(this.#embedForm) + } + this.#toolbar?.selectTab(on) } - #tab(label: string, onClick: () => void): HTMLButtonElement { - const button = document.createElement('button') - button.type = 'button' - button.className = 'blogeditor__tab' - button.setAttribute('role', 'tab') - button.textContent = label - button.addEventListener('click', onClick) - return button + /** + * Parses html into the editor without an update event (Pitfall 4) and + * outside the undo history, so undo never brings back a replaced value. + */ + #load(html: string): void { + this.#parsed = html + if (!this.#editor) return + this.#editor.chain().setMeta('addToHistory', false).setContent(html, { emitUpdate: false }).run() + this.#blocks = captureBlocks(html, this.#editor.schema) } #sourceInput(): void { @@ -171,10 +259,15 @@ export class BlogEditorElement extends HTMLElement { this.dispatchEvent(new CustomEvent(CHANGE_EVENT, { bubbles: true, composed: true, detail: { value: this.value } })) } + #setStatus(text: string): void { + if (this.#status) this.#status.textContent = text + } + #syncAttributes(): void { const disabled = this.hasAttribute('disabled') const invalid = this.hasAttribute('invalid') if (this.#editor && this.#editor.isEditable === disabled) this.#editor.setEditable(!disabled, false) + this.#toolbar?.setDisabled(disabled) if (this.#textarea) { this.#textarea.readOnly = disabled if (invalid) this.#textarea.setAttribute('aria-invalid', 'true') @@ -189,4 +282,264 @@ export class BlogEditorElement extends HTMLElement { else view.removeAttribute('lang') } } + + // Inline forms ----------------------------------------------------------- + + #form(kind: string, label: string, actions: [string, string, () => void][]): InlineForm { + const root = document.createElement('div') + root.className = 'blogeditor__form' + root.dataset.form = kind + root.hidden = true + const field = document.createElement('label') + const caption = document.createElement('span') + caption.textContent = label + const input = document.createElement('input') + input.type = 'text' + input.name = 'url' + input.autocomplete = 'off' + input.addEventListener('keydown', (event) => { + if (event.key === 'Enter') { + event.preventDefault() + actions[0]![2]() + } else if (event.key === 'Escape') { + event.preventDefault() + this.#close(form) + } + }) + field.append(caption, input) + root.append(field) + for (const [action, text, run] of actions) root.append(this.#action(action, text, run)) + const error = document.createElement('p') + error.className = 'blogeditor__error' + error.dataset.error = '' + error.setAttribute('aria-live', 'polite') + root.append(error) + const form = { root, error } + return form + } + + #action(action: string, text: string, run: () => void): HTMLButtonElement { + const button = document.createElement('button') + button.type = 'button' + button.dataset.action = action + button.textContent = text + button.addEventListener('click', run) + return button + } + + #open(form: InlineForm | undefined, value = ''): void { + if (!form) return + for (const other of [this.#linkForm, this.#embedForm]) if (other && other !== form) this.#close(other) + form.error.textContent = '' + form.root.hidden = false + const input = form.root.querySelector('input') + if (input) { + input.value = value + input.focus() + } + } + + #close(form: InlineForm | undefined): void { + if (!form) return + form.root.hidden = true + form.error.textContent = '' + } + + #inputOf(form: InlineForm | undefined, name = 'url'): string { + return (form?.root.querySelector(`input[name="${name}"]`)?.value ?? '').trim() + } + + // Links ---------------------------------------------------------------------- + + #openLink(): void { + if (!this.#editor?.isEditable) return + const href = this.#editor.getAttributes('link').href + this.#open(this.#linkForm, typeof href === 'string' ? href : '') + } + + #applyLink(): void { + const editor = this.#editor + if (!editor || !this.#linkForm) return + const url = this.#inputOf(this.#linkForm) + if (url === '') { + this.#removeLink() + return + } + if (!isPolicyUrl(url)) { + this.#linkForm.error.textContent = this.#labels.linkInvalid + return + } + const { empty } = editor.state.selection + if (empty && !editor.isActive('link')) { + // Nothing selected: insert the URL as the link text. + editor + .chain() + .focus() + .insertContent({ type: 'text', text: url, marks: [{ type: 'link', attrs: { href: url } }] }) + .unsetMark('link') + .run() + } else { + editor.chain().focus().extendMarkRange('link').setLink({ href: url }).run() + } + this.#close(this.#linkForm) + } + + #removeLink(): void { + this.#editor?.chain().focus().extendMarkRange('link').unsetLink().run() + this.#close(this.#linkForm) + } + + // Embeds --------------------------------------------------------------------- + + #openEmbed(): void { + if (!this.#editor?.isEditable) return + this.#open(this.#embedForm) + } + + #insertEmbed(): void { + if (!this.#editor || !this.#embedForm) return + const embed = parseEmbedUrl(this.#inputOf(this.#embedForm)) + if (!embed) { + this.#embedForm.error.textContent = this.#labels.embedInvalid + return + } + this.#editor.chain().focus().setEmbed(embed).run() + this.#close(this.#embedForm) + } + + // Raw HTML ------------------------------------------------------------------- + + #insertRawHtml(): void { + const editor = this.#editor + if (!editor?.isEditable) return + const before = this.value + const html = '
' + if (!editor.chain().focus().insertRawHtml(html).run()) return + const after = this.value + let at = 0 + while (at < before.length && at < after.length && before[at] === after[at]) at++ + this.showSource(true) + const caret = after.startsWith(html, at) ? at + '
'.length : at + this.#textarea?.focus() + this.#textarea?.setSelectionRange(caret, caret) + } + + #onEditHtml = (event: Event): void => { + const html = (event as CustomEvent<{ html?: string }>).detail?.html ?? '' + this.showSource(true) + const textarea = this.#textarea + if (!textarea) return + textarea.focus() + const at = html ? textarea.value.indexOf(html) : -1 + if (at >= 0) textarea.setSelectionRange(at, at + html.length) + } + + // Uploads (D-18) ------------------------------------------------------------- + + #picked(): void { + const input = this.#fileInput + if (!input) return + const files = Array.from(input.files ?? []) + const images = files.filter(isImage) + if (images.length < files.length) this.#setStatus(this.#labels.notAnImage) + for (const file of images) this.#upload(file) + try { + input.value = '' + } catch { + // A test double may not allow resetting the value. + } + } + + #upload(file: File): void { + const id = crypto.randomUUID() + const name = file.name + const timer = setTimeout(() => { + if (!this.#pending.delete(id)) return + this.#setStatus(format(this.#labels.uploadTimeout, { name })) + }, UPLOAD_TIMEOUT_MS) + this.#pending.set(id, { name, timer }) + this.#setStatus(format(this.#labels.uploading, { name })) + this.dispatchEvent(new CustomEvent(UPLOAD_EVENT, { bubbles: true, composed: true, detail: { id, file } })) + } + + #onUploadResult = (event: Event): void => { + const detail = (event as CustomEvent<{ id?: unknown; url?: unknown; error?: unknown }>).detail ?? {} + const id = typeof detail.id === 'string' ? detail.id : '' + const pending = this.#pending.get(id) + if (!pending) return + clearTimeout(pending.timer) + this.#pending.delete(id) + const url = typeof detail.url === 'string' ? detail.url : '' + if (typeof detail.error === 'string' || !url || !isPolicyUrl(url)) { + const error = typeof detail.error === 'string' && detail.error ? detail.error : pending.name + this.#setStatus(format(this.#labels.uploadFailed, { error })) + return + } + this.#setStatus('') + this.#ready.push({ url, name: pending.name }) + this.#showImageForm() + } + + #imageFormElement(): InlineForm { + const labels = this.#labels + const root = document.createElement('div') + root.className = 'blogeditor__form' + root.dataset.form = 'image' + root.hidden = true + const field = (name: string, text: string) => { + const label = document.createElement('label') + const caption = document.createElement('span') + caption.textContent = text + const input = document.createElement('input') + input.type = 'text' + input.name = name + input.autocomplete = 'off' + label.append(caption, input) + return label + } + root.append(field('alt', labels.altText), field('caption', labels.caption)) + root.append(this.#action('insert', labels.insertImage, () => this.#insertImage())) + root.append(this.#action('cancel', labels.cancel, () => this.#nextImage())) + const error = document.createElement('p') + error.className = 'blogeditor__error' + error.dataset.error = '' + error.setAttribute('aria-live', 'polite') + root.append(error) + return { root, error } + } + + #showImageForm(): void { + const form = this.#imageForm + if (!form || !form.root.hidden || this.#ready.length === 0) return + for (const input of Array.from(form.root.querySelectorAll('input'))) input.value = '' + form.error.textContent = '' + form.root.hidden = false + form.root.querySelector('input[name="alt"]')?.focus() + } + + #insertImage(): void { + const editor = this.#editor + const form = this.#imageForm + const ready = this.#ready[0] + if (!editor || !form || !ready) return + const alt = this.#inputOf(form, 'alt') + const caption = this.#inputOf(form, 'caption') + if (!alt) { + form.error.textContent = this.#labels.altRequired + return + } + if (caption) editor.chain().focus().setFigure({ src: ready.url, alt, caption }).run() + else editor.chain().focus().setImage({ src: ready.url, alt }).run() + this.#nextImage() + } + + #nextImage(): void { + this.#ready.shift() + if (this.#imageForm) this.#close(this.#imageForm) + this.#showImageForm() + } +} + +function isImage(file: File): boolean { + return IMAGE_TYPES.includes(file.type) } diff --git a/assets/src/blogeditor/embed.ts b/assets/src/blogeditor/embed.ts new file mode 100644 index 0000000..13bdfcb --- /dev/null +++ b/assets/src/blogeditor/embed.ts @@ -0,0 +1,59 @@ +/** + * Embed providers (D-05). Stored posts hold only the placeholder + *
; the layer turns it + * into the real iframe. Adding a provider is one entry here and one in the + * layer's table. + */ +export interface EmbedProvider { + /** The name shown on the editor card. */ + name: string + /** The id the placeholder may hold. */ + idPattern: RegExp + /** Returns the id from a provider URL, or null. */ + idFromUrl: (url: URL) => string | null +} + +const YOUTUBE_HOSTS = new Set(['youtube.com', 'www.youtube.com', 'm.youtube.com', 'music.youtube.com', 'youtube-nocookie.com', 'www.youtube-nocookie.com']) + +export const EMBED_PROVIDERS = { + youtube: { + name: 'YouTube', + idPattern: /^[A-Za-z0-9_-]{11}$/, + idFromUrl(url: URL): string | null { + const host = url.hostname.toLowerCase() + if (host === 'youtu.be') { + return url.pathname.split('/')[1] ?? null + } + if (!YOUTUBE_HOSTS.has(host)) return null + if (url.pathname === '/watch') return url.searchParams.get('v') + const match = /^\/(?:shorts|embed)\/([^/]+)\/?$/.exec(url.pathname) + return match ? match[1]! : null + }, + }, +} as const satisfies Record + +export type EmbedProviderName = keyof typeof EMBED_PROVIDERS + +export function isEmbedProvider(name: string): name is EmbedProviderName { + return Object.prototype.hasOwnProperty.call(EMBED_PROVIDERS, name) +} + +/** + * parseEmbedUrl returns the provider and id for a supported video URL + * (youtube.com/watch?v=, youtu.be/, youtube.com/shorts/ and + * youtube.com/embed/ for YouTube), or null for anything else. + */ +export function parseEmbedUrl(input: string): { provider: EmbedProviderName; id: string } | null { + let url: URL + try { + url = new URL(input.trim()) + } catch { + return null + } + if (url.protocol !== 'https:' && url.protocol !== 'http:') return null + for (const provider of Object.keys(EMBED_PROVIDERS) as EmbedProviderName[]) { + const id = EMBED_PROVIDERS[provider].idFromUrl(url) + if (id && EMBED_PROVIDERS[provider].idPattern.test(id)) return { provider, id } + } + return null +} diff --git a/assets/src/blogeditor/extensions.ts b/assets/src/blogeditor/extensions.ts new file mode 100644 index 0000000..4f3d4cb --- /dev/null +++ b/assets/src/blogeditor/extensions.ts @@ -0,0 +1,535 @@ +import { Extension, Mark, Node, mergeAttributes, type AnyExtension } from '@tiptap/core' +import type { DOMOutputSpec } from '@tiptap/pm/model' +import Image from '@tiptap/extension-image' +import { Table, TableCell, TableHeader, TableRow } from '@tiptap/extension-table' +import StarterKit from '@tiptap/starter-kit' +import { EMBED_PROVIDERS, isEmbedProvider } from './embed' +import { labelsFor, type Labels } from './labels' + +/** The event a raw HTML card dispatches to open its source in the Source tab. */ +export const EDIT_HTML_EVENT = 'blogeditor-edit-html' + +/** + * Block elements the schema does not model. Each becomes one atomic rawHtml + * node holding its outer HTML, shown in the editor as text (D-04). + */ +export const RAW_HTML_TAGS = [ + 'footer', + 'section', + 'aside', + 'header', + 'nav', + 'details', + 'style', + 'div', + 'article', + 'main', + 'address', + 'dl', + 'iframe', + 'video', + 'audio', + 'picture', + 'object', + 'embed', + 'form', + 'svg', + 'math', + 'script', + 'noscript', +] as const + +const URL_IGNORED = /[\x00-\x20\x7f]+/g +const URL_SCHEME = /^([a-z][a-z0-9+.-]*):/i +const POLICY_SCHEMES = ['http', 'https', 'mailto'] + +/** + * isPolicyUrl reports whether url is one the server and layer sanitizer + * policies keep (D-05, D-10 amended): a relative URL (including # and ?) or + * an http, https or mailto URL. The scheme is read after removing ASCII + * control characters, spaces and DEL, as browsers do, so "java\tscript:" is + * refused. It mirrors allowedUrl in the layer's htmlGate.ts. + */ +export function isPolicyUrl(url: string | null | undefined): boolean { + if (url == null) return false + const scheme = URL_SCHEME.exec(url.replace(URL_IGNORED, '')) + if (scheme && !POLICY_SCHEMES.includes(scheme[1]!.toLowerCase())) return false + try { + new URL(url, 'https://journal.invalid/') + return true + } catch { + return false + } +} + +/** + * The attributes each node or mark models itself; htmlAttrs captures every + * other attribute. Event handler attributes (on*) are never captured, so + * they never reach the live admin DOM. + */ +const MODELLED: Record = { + orderedList: ['start', 'type'], + link: ['href', 'target', 'rel', 'class', 'title'], + image: ['src', 'alt', 'title', 'width', 'height'], + figureImage: ['src', 'alt', 'title', 'width', 'height'], + tableCell: ['colspan', 'rowspan', 'colwidth'], + tableHeader: ['colspan', 'rowspan', 'colwidth'], +} + +const HTML_ATTRIBUTE_TYPES = [ + 'paragraph', + 'heading', + 'blockquote', + 'bulletList', + 'orderedList', + 'listItem', + 'codeBlock', + 'horizontalRule', + 'hardBreak', + 'table', + 'tableRow', + 'tableCell', + 'tableHeader', + 'image', + 'figure', + 'figureImage', + 'figcaption', + 'link', +] + +function isHandlerName(name: string): boolean { + return /^on/i.test(name) +} + +/** captureAttributes returns the element's attributes outside skip, in order. */ +function captureAttributes(element: HTMLElement, skip: readonly string[]): Record | null { + const out: Record = {} + let any = false + for (const attr of Array.from(element.attributes)) { + const name = attr.name.toLowerCase() + if (skip.includes(name) || isHandlerName(name)) continue + out[attr.name] = attr.value + any = true + } + return any ? out : null +} + +function renderCaptured(captured: unknown): Record { + if (!captured || typeof captured !== 'object') return {} + const out: Record = {} + for (const [name, value] of Object.entries(captured as Record)) { + if (isHandlerName(name) || typeof value !== 'string') continue + out[name] = value + } + return out +} + +/** + * HtmlAttributes keeps the attributes the schema does not model (class, + * data-*, itemprop, style and others) on paragraphs, headings, lists, list + * items, blockquotes, tables, cells, images and links, so they survive an + * edit elsewhere in the document (D-03). + */ +export const HtmlAttributes = Extension.create({ + name: 'htmlAttributes', + + addGlobalAttributes() { + return HTML_ATTRIBUTE_TYPES.map((type) => ({ + types: [type], + attributes: { + htmlAttrs: { + default: null, + keepOnSplit: false, + parseHTML: (element: HTMLElement) => captureAttributes(element, MODELLED[type] ?? []), + renderHTML: (attributes: Record) => renderCaptured(attributes.htmlAttrs), + }, + }, + })) + }, +}) + +/** Span keeps inline spans with their attributes (style, class) as a mark. */ +export const Span = Mark.create({ + name: 'span', + priority: 40, + + addAttributes() { + return { + htmlAttrs: { + default: null, + parseHTML: (element: HTMLElement) => captureAttributes(element, []), + renderHTML: (attributes: Record) => renderCaptured(attributes.htmlAttrs), + }, + } + }, + + parseHTML() { + return [{ tag: 'span', getAttrs: (element) => ((element as HTMLElement).attributes.length > 0 ? null : false) }] + }, + + renderHTML({ HTMLAttributes }) { + return ['span', HTMLAttributes, 0] + }, +}) + +let inertDocument: Document | undefined + +/** + * inert returns a document without a browsing context: markup parsed into + * it loads no image and runs no handler, so stored HTML never reaches the + * live admin DOM. + */ +export function inert(): Document { + inertDocument ??= document.implementation.createHTMLDocument('') + return inertDocument +} + +declare module '@tiptap/core' { + interface Commands { + rawHtml: { + /** Inserts an atomic raw HTML block. */ + insertRawHtml: (html: string) => ReturnType + } + embed: { + /** Inserts an embed placeholder for an allowlisted provider. */ + setEmbed: (attributes: { provider: string; id: string }) => ReturnType + } + figure: { + /** Inserts an image with a caption as figure, img and figcaption. */ + setFigure: (attributes: { src: string; alt: string; caption: string }) => ReturnType + } + } +} + +export interface RawHtmlOptions { + labels: Labels +} + +/** + * RawHtml is an atomic block holding the outer HTML of markup the schema + * does not model (D-04). Its card renders the source with textContent, + * never as live DOM. + */ +export const RawHtml = Node.create({ + name: 'rawHtml', + group: 'block', + atom: true, + selectable: true, + draggable: true, + priority: 10, + + addOptions() { + return { labels: labelsFor('en') } + }, + + addAttributes() { + return { + html: { + default: '', + parseHTML: (element: HTMLElement) => element.outerHTML, + renderHTML: () => ({}), + }, + } + }, + + parseHTML() { + // The last rule takes a figure that is not exactly img plus an optional + // figcaption. + return [...RAW_HTML_TAGS, 'figure'].map((tag) => ({ tag, priority: 10 })) + }, + + renderHTML({ node }) { + // Serializers only (the editor shows the card): parsed in the inert + // document and returned whole. + const template = inert().createElement('template') + template.innerHTML = String(node.attrs.html ?? '') + // ProseMirror accepts any DOM node here; the typing names only elements. + return template.content as unknown as DOMOutputSpec + }, + + addCommands() { + return { + insertRawHtml: + (html) => + ({ commands }) => + commands.insertContent({ type: this.name, attrs: { html } }), + } + }, + + addNodeView() { + const labels = this.options.labels + return ({ node }) => { + const dom = document.createElement('div') + dom.className = 'blogeditor__raw' + dom.contentEditable = 'false' + const head = document.createElement('div') + head.className = 'blogeditor__card-head' + const title = document.createElement('span') + title.textContent = labels.rawHtmlCard + const edit = document.createElement('button') + edit.type = 'button' + edit.textContent = labels.editAsHtml + head.append(title, edit) + const source = document.createElement('pre') + source.className = 'blogeditor__raw-source' + source.textContent = String(node.attrs.html ?? '') + dom.append(head, source) + let current = node + edit.addEventListener('click', (event) => { + event.preventDefault() + dom.dispatchEvent( + new CustomEvent(EDIT_HTML_EVENT, { bubbles: true, detail: { html: String(current.attrs.html ?? '') } }), + ) + }) + return { + dom, + update: (next) => { + if (next.type !== current.type) return false + current = next + source.textContent = String(next.attrs.html ?? '') + return true + }, + stopEvent: (event) => event.target === edit, + ignoreMutation: () => true, + } + } + }, +}) + +export interface EmbedOptions { + labels: Labels +} + +/** + * Embed is the allowlisted video placeholder (D-05). It renders exactly + *
; the editor shows a + * card and never an iframe. The layer expands the placeholder on the site. + */ +export const Embed = Node.create({ + name: 'embed', + group: 'block', + atom: true, + selectable: true, + draggable: true, + priority: 70, + + addOptions() { + return { labels: labelsFor('en') } + }, + + addAttributes() { + return { + provider: { default: null, parseHTML: (element: HTMLElement) => element.getAttribute('data-embed'), renderHTML: () => ({}) }, + id: { default: null, parseHTML: (element: HTMLElement) => element.getAttribute('data-id'), renderHTML: () => ({}) }, + } + }, + + parseHTML() { + return [ + { + tag: 'figure[data-embed]', + priority: 70, + getAttrs: (element) => { + const el = element as HTMLElement + const provider = el.getAttribute('data-embed') ?? '' + const id = el.getAttribute('data-id') ?? '' + // Exactly the placeholder: two attributes and no content. + if (el.attributes.length !== 2 || el.childNodes.length !== 0) return false + if (!isEmbedProvider(provider) || !EMBED_PROVIDERS[provider].idPattern.test(id)) return false + return null + }, + }, + ] + }, + + renderHTML({ node }) { + return ['figure', { 'data-embed': node.attrs.provider, 'data-id': node.attrs.id }] + }, + + addCommands() { + return { + setEmbed: + ({ provider, id }) => + ({ commands }) => { + if (!isEmbedProvider(provider) || !EMBED_PROVIDERS[provider].idPattern.test(id)) return false + return commands.insertContent({ type: this.name, attrs: { provider, id } }) + }, + } + }, + + addNodeView() { + const labels = this.options.labels + return ({ node }) => { + const dom = document.createElement('div') + dom.className = 'blogeditor__embed' + dom.contentEditable = 'false' + const render = (n: typeof node) => { + const provider = String(n.attrs.provider ?? '') + const name = isEmbedProvider(provider) ? EMBED_PROVIDERS[provider].name : provider + dom.textContent = `${labels.embedCard}: ${name} ${String(n.attrs.id ?? '')}` + } + render(node) + let current = node + return { + dom, + update: (next) => { + if (next.type !== current.type) return false + current = next + render(next) + return true + }, + ignoreMutation: () => true, + } + } + }, +}) + +function isFigureShape(element: HTMLElement): boolean { + if (element.hasAttribute('data-embed')) return false + const children: Element[] = [] + for (const child of Array.from(element.childNodes)) { + if (child.nodeType === 1) children.push(child as Element) + else if (child.nodeType === 3 && /[^ \t\r\n\f]/.test(child.nodeValue ?? '')) return false + else if (child.nodeType !== 3) return false + } + if (children.length < 1 || children.length > 2) return false + const img = children[0]! + if (img.nodeName !== 'IMG') return false + const src = img.getAttribute('src') + if (!src || /^\s*data:/i.test(src)) return false + return children.length === 1 || children[1]!.nodeName === 'FIGCAPTION' +} + +/** Figure holds an image and an optional caption (D-18). */ +export const Figure = Node.create({ + name: 'figure', + group: 'block', + content: 'figureImage figcaption?', + draggable: true, + isolating: true, + priority: 60, + + parseHTML() { + return [ + { + tag: 'figure', + priority: 60, + getAttrs: (element) => (isFigureShape(element as HTMLElement) ? null : false), + }, + ] + }, + + renderHTML({ HTMLAttributes }) { + return ['figure', HTMLAttributes, 0] + }, + + addCommands() { + return { + setFigure: + ({ src, alt, caption }) => + ({ commands }) => { + const content: Record[] = [{ type: 'figureImage', attrs: { src, alt } }] + if (caption) content.push({ type: 'figcaption', content: [{ type: 'text', text: caption }] }) + return commands.insertContent({ type: this.name, content }) + }, + } + }, +}) + +/** FigureImage is the img inside a figure. */ +export const FigureImage = Node.create({ + name: 'figureImage', + atom: true, + selectable: false, + priority: 60, + + addAttributes() { + return { + src: { default: null }, + alt: { default: null }, + title: { default: null }, + width: { default: null }, + height: { default: null }, + } + }, + + parseHTML() { + return [{ tag: 'img[src]:not([src^="data:"])', context: 'figure/', priority: 60 }] + }, + + renderHTML({ HTMLAttributes }) { + return ['img', HTMLAttributes] + }, +}) + +/** Figcaption is the editable caption of a figure. */ +export const Figcaption = Node.create({ + name: 'figcaption', + content: 'inline*', + priority: 60, + + parseHTML() { + return [{ tag: 'figcaption', context: 'figure/' }] + }, + + renderHTML({ HTMLAttributes }) { + return ['figcaption', HTMLAttributes, 0] + }, +}) + +/** Tables render without TipTap's colgroup and min-width style. */ +export const PlainTable = Table.extend({ + renderHTML({ HTMLAttributes }) { + return ['table', mergeAttributes(this.options.HTMLAttributes, HTMLAttributes), ['tbody', 0]] + }, +}) + +// Cell alignment is kept through htmlAttrs (style or align, as stored) +// instead of TipTap's align attribute, which rewrites it as a style. +function withoutAlign>(attributes: T | undefined): Omit { + const { align: _align, ...rest } = attributes ?? ({} as T) + return rest +} + +export const PlainTableCell = TableCell.extend({ + addAttributes() { + return withoutAlign(this.parent?.()) + }, +}) + +export const PlainTableHeader = TableHeader.extend({ + addAttributes() { + return withoutAlign(this.parent?.()) + }, +}) + +/** + * preservationExtensions is the editor schema (D-03, D-04): StarterKit + * without the trailing node and with links that gain no target, rel or class + * and accept only policy URLs; inline images without base64; tables; and + * the preservation nodes and marks. + */ +export function preservationExtensions(labels: Labels = labelsFor('en')): AnyExtension[] { + return [ + StarterKit.configure({ + trailingNode: false, + link: { + openOnClick: false, + HTMLAttributes: { target: null, rel: null, class: null }, + isAllowedUri: (url) => isPolicyUrl(url), + }, + }), + Image.configure({ inline: true, allowBase64: false }), + PlainTable, + TableRow, + PlainTableHeader, + PlainTableCell, + Figure, + FigureImage, + Figcaption, + Embed.configure({ labels }), + RawHtml.configure({ labels }), + Span, + HtmlAttributes, + ] +} diff --git a/assets/src/blogeditor/labels.ts b/assets/src/blogeditor/labels.ts new file mode 100644 index 0000000..b01e8a3 --- /dev/null +++ b/assets/src/blogeditor/labels.ts @@ -0,0 +1,154 @@ +/** Every label, prompt and error the Blog Editor shows. */ +export interface Labels { + tabWysiwyg: string + tabSource: string + toolbar: string + paragraph: string + heading2: string + heading3: string + heading4: string + bold: string + italic: string + bulletList: string + orderedList: string + link: string + blockquote: string + insertTable: string + addRow: string + deleteRow: string + addColumn: string + deleteColumn: string + deleteTable: string + image: string + embed: string + rawHtml: string + undo: string + redo: string + linkUrl: string + linkApply: string + linkRemove: string + linkInvalid: string + embedUrl: string + embedInsert: string + embedInvalid: string + cancel: string + uploading: string + uploadFailed: string + uploadTimeout: string + notAnImage: string + altText: string + caption: string + altRequired: string + insertImage: string + rawHtmlCard: string + editAsHtml: string + embedCard: string +} + +const en: Labels = { + tabWysiwyg: 'WYSIWYG', + tabSource: 'Source', + toolbar: 'Formatting', + paragraph: 'Paragraph', + heading2: 'Heading 2', + heading3: 'Heading 3', + heading4: 'Heading 4', + bold: 'Bold', + italic: 'Italic', + bulletList: 'Bullet list', + orderedList: 'Numbered list', + link: 'Link', + blockquote: 'Quote', + insertTable: 'Insert table', + addRow: 'Add row', + deleteRow: 'Delete row', + addColumn: 'Add column', + deleteColumn: 'Delete column', + deleteTable: 'Delete table', + image: 'Image', + embed: 'Embed video', + rawHtml: 'HTML block', + undo: 'Undo', + redo: 'Redo', + linkUrl: 'Link URL', + linkApply: 'Apply', + linkRemove: 'Remove link', + linkInvalid: 'Links must use http, https, mailto or a relative URL.', + embedUrl: 'YouTube URL', + embedInsert: 'Insert', + embedInvalid: 'This video URL is not supported. Paste a YouTube link.', + cancel: 'Cancel', + uploading: 'Uploading {name}…', + uploadFailed: 'Upload failed: {error}', + uploadTimeout: 'The upload of {name} took too long.', + notAnImage: 'Only JPEG, PNG, GIF and WebP images can be uploaded.', + altText: 'Alt text (required)', + caption: 'Caption (optional)', + altRequired: 'Enter the alt text.', + insertImage: 'Insert image', + rawHtmlCard: 'HTML block', + editAsHtml: 'Edit as HTML', + embedCard: 'Embedded video', +} + +const pl: Labels = { + tabWysiwyg: 'WYSIWYG', + tabSource: 'Źródło', + toolbar: 'Formatowanie', + paragraph: 'Akapit', + heading2: 'Nagłówek 2', + heading3: 'Nagłówek 3', + heading4: 'Nagłówek 4', + bold: 'Pogrubienie', + italic: 'Kursywa', + bulletList: 'Lista punktowana', + orderedList: 'Lista numerowana', + link: 'Link', + blockquote: 'Cytat', + insertTable: 'Wstaw tabelę', + addRow: 'Dodaj wiersz', + deleteRow: 'Usuń wiersz', + addColumn: 'Dodaj kolumnę', + deleteColumn: 'Usuń kolumnę', + deleteTable: 'Usuń tabelę', + image: 'Obraz', + embed: 'Osadź wideo', + rawHtml: 'Blok HTML', + undo: 'Cofnij', + redo: 'Ponów', + linkUrl: 'Adres linku', + linkApply: 'Zastosuj', + linkRemove: 'Usuń link', + linkInvalid: 'Link musi używać http, https, mailto albo adresu względnego.', + embedUrl: 'Adres filmu YouTube', + embedInsert: 'Wstaw', + embedInvalid: 'Ten adres filmu nie jest obsługiwany. Wklej link do YouTube.', + cancel: 'Anuluj', + uploading: 'Wysyłanie {name}…', + uploadFailed: 'Wysyłanie nie powiodło się: {error}', + uploadTimeout: 'Wysyłanie {name} trwało zbyt długo.', + notAnImage: 'Można wysłać tylko obrazy JPEG, PNG, GIF i WebP.', + altText: 'Tekst alternatywny (wymagany)', + caption: 'Podpis (opcjonalny)', + altRequired: 'Wpisz tekst alternatywny.', + insertImage: 'Wstaw obraz', + rawHtmlCard: 'Blok HTML', + editAsHtml: 'Edytuj jako HTML', + embedCard: 'Osadzone wideo', +} + +const TABLES: Record = { en, pl } + +/** + * labelsFor returns the labels for the admin UI locale (the element's + * ui-locale attribute): the table for its language subtag, else English. + */ +export function labelsFor(uiLocale: string | null | undefined): Labels { + const language = (uiLocale ?? '').toLowerCase().split(/[-_]/)[0] ?? '' + return TABLES[language] ?? en +} + +/** format replaces {name} placeholders in a label. */ +export function format(label: string, values: Record): string { + return label.replace(/\{(\w+)\}/g, (match, key: string) => values[key] ?? match) +} diff --git a/assets/src/blogeditor/serializer.ts b/assets/src/blogeditor/serializer.ts index d5cd6c8..21e0c5f 100644 --- a/assets/src/blogeditor/serializer.ts +++ b/assets/src/blogeditor/serializer.ts @@ -1,14 +1,305 @@ -import type { Editor } from '@tiptap/core' -import { DOMSerializer } from '@tiptap/pm/model' +import { elementFromString, type Editor } from '@tiptap/core' +import { DOMParser as PMDOMParser, DOMSerializer, type Node as PMNode, type Schema } from '@tiptap/pm/model' +import { inert } from './extensions' /** - * serializeDocument returns the HTML of the editor document. It is the only - * source of the element's value after a user edit; editor.getHTML() is never - * the stored value. + * One top-level piece of the original HTML: its exact source text and the + * nodes it parses to on its own. Whitespace and comments parse to no node. */ -export function serializeDocument(editor: Editor): string { - const serializer = DOMSerializer.fromSchema(editor.schema) - const host = document.createElement('div') - host.appendChild(serializer.serializeFragment(editor.state.doc.content, { document })) +interface Segment { + html: string + nodes: PMNode[] +} + +/** + * Blocks is the original HTML split into top-level blocks (RESEARCH A3). + * Each block keeps its exact source and the text between it and the + * previous block, so unedited blocks keep their bytes after an edit. + */ +export interface Blocks { + blocks: { before: string; html: string; nodes: PMNode[] }[] + trailing: string +} + +const VOID_TAGS = new Set(['area', 'base', 'br', 'col', 'embed', 'hr', 'img', 'input', 'link', 'meta', 'param', 'source', 'track', 'wbr']) +const RAW_TEXT_TAGS = new Set(['script', 'style', 'textarea', 'title', 'xmp', 'iframe', 'noembed', 'noframes']) +const TAG_NAME = /^<\/?([a-zA-Z][^\s/>]*)/ + +/** tagEnd returns the index after the '>' closing the tag at start, or -1. */ +function tagEnd(html: string, start: number): number { + let quote = '' + let prev = '' + for (let i = start + 1; i < html.length; i++) { + const c = html[i]! + if (quote) { + if (c === quote) quote = '' + continue + } + if ((c === '"' || c === "'") && prev === '=') { + quote = c + continue + } + if (c === '>') return i + 1 + if (!/\s/.test(c)) prev = c + } + return -1 +} + +/** rawTextEnd returns the index after the end tag of a raw text element, or -1. */ +function rawTextEnd(html: string, from: number, name: string): number { + const close = new RegExp(`])`, 'ig') + close.lastIndex = from + const match = close.exec(html) + return match ? tagEnd(html, match.index) : -1 +} + +/** elementEnd returns the index after the element whose start tag ends at from. */ +function elementEnd(html: string, from: number, name: string): number { + const stack = [name] + let i = from + while (stack.length > 0) { + const lt = html.indexOf('<', i) + if (lt < 0) return -1 + if (html.startsWith('', lt + 4) + if (end < 0) return -1 + i = end + 3 + continue + } + const match = TAG_NAME.exec(html.slice(lt, lt + 64)) + if (!match) { + i = lt + 1 + continue + } + const tag = match[1]!.toLowerCase() + const end = tagEnd(html, lt) + if (end < 0) return -1 + i = end + if (html[lt + 1] === '/') { + const at = stack.lastIndexOf(tag) + if (at >= 0) stack.length = at + continue + } + if (VOID_TAGS.has(tag) || html[end - 2] === '/') continue + if (RAW_TEXT_TAGS.has(tag)) { + i = rawTextEnd(html, end, tag) + if (i < 0) return -1 + continue + } + stack.push(tag) + } + return i +} + +/** + * splitTopLevel splits html into its top-level pieces (elements, text runs, + * comments) by source position, or returns null when it cannot. + */ +function splitTopLevel(html: string): string[] | null { + const pieces: string[] = [] + let i = 0 + while (i < html.length) { + const start = i + if (html[i] !== '<') { + const lt = html.indexOf('<', i) + i = lt < 0 ? html.length : lt + } else if (html.startsWith('', i + 4) + if (end < 0) return null + i = end + 3 + } else if (html.startsWith('')) +} + +/** + * captureBlocks splits the original HTML into top-level blocks and parses + * each alone, recording its nodes, its exact outer HTML and the text + * between blocks. It returns null when the pieces do not parse to the same + * DOM as the whole (then every edited document is serialized whole). + */ +export function captureBlocks(html: string, schema: Schema): Blocks | null { + const pieces = splitTopLevel(html) + if (!pieces) return null + const whole = elementFromString(html).innerHTML + const joined = pieces.map((piece) => elementFromString(piece).innerHTML).join('') + if (whole !== joined) return null + + const parser = PMDOMParser.fromSchema(schema) + const segments: Segment[] = pieces.map((piece) => { + if (isGap(piece)) return { html: piece, nodes: [] } + const nodes: PMNode[] = [] + parser.parseSlice(elementFromString(piece)).content.forEach((node) => nodes.push(node)) + return { html: piece, nodes } + }) + + const blocks: Blocks['blocks'] = [] + let pending = '' + for (const segment of segments) { + if (segment.nodes.length === 0) { + pending += segment.html + continue + } + blocks.push({ before: pending, html: segment.html, nodes: segment.nodes }) + pending = '' + } + return { blocks, trailing: pending } +} + +/** tidyTables applies the stored table form to serialized tables. */ +function tidyTables(root: Element): void { + for (const table of Array.from(root.querySelectorAll('table'))) { + const tbody = Array.from(table.children).find((child) => child.nodeName === 'TBODY') + const first = tbody?.firstElementChild + // A leading row of header cells goes into thead. + if (tbody && first && first.children.length > 0 && Array.from(first.children).every((cell) => cell.nodeName === 'TH')) { + const thead = table.ownerDocument.createElement('thead') + thead.append(first) + table.insertBefore(thead, tbody) + if (tbody.children.length === 0) tbody.remove() + } + } + // A cell holding one plain paragraph holds its text directly. + for (const cell of Array.from(root.querySelectorAll('td, th'))) { + const only = cell.childNodes.length === 1 ? cell.firstChild : null + if (only && only.nodeName === 'P' && (only as Element).attributes.length === 0) { + cell.replaceChildren(...Array.from(only.childNodes)) + } + } +} + +/** serializeNode returns the HTML of one top-level node. */ +function serializeNode(node: PMNode, serializer: DOMSerializer): string { + if (node.type.name === 'rawHtml') return String(node.attrs.html ?? '') + const doc = inert() + const host = doc.createElement('div') + host.appendChild(serializer.serializeNode(node, { document: doc })) + tidyTables(host) return host.innerHTML } + +function sameNodes(a: readonly PMNode[], b: readonly PMNode[], from: number): boolean { + if (from + a.length > b.length) return false + for (let i = 0; i < a.length; i++) { + if (!a[i]!.eq(b[from + i]!)) return false + } + return true +} + +/** + * align matches captured blocks to the document's top-level nodes in order + * (longest common subsequence by node count) and returns the pairs. + */ +function align(blocks: Blocks['blocks'], nodes: readonly PMNode[]): { block: number; node: number }[] { + const pairs: { block: number; node: number }[] = [] + // Unchanged prefix and suffix first, so a single edit costs no table. + let lo = 0 + let at = 0 + while (lo < blocks.length && sameNodes(blocks[lo]!.nodes, nodes, at)) { + pairs.push({ block: lo, node: at }) + at += blocks[lo]!.nodes.length + lo++ + } + const tail: { block: number; node: number }[] = [] + let hi = blocks.length + let end = nodes.length + while (hi > lo && end - blocks[hi - 1]!.nodes.length >= at && sameNodes(blocks[hi - 1]!.nodes, nodes, end - blocks[hi - 1]!.nodes.length)) { + hi-- + end -= blocks[hi]!.nodes.length + tail.unshift({ block: hi, node: end }) + } + + const rows = hi - lo + const cols = end - at + if (rows > 0 && cols > 0) { + const width = cols + 1 + const score = new Int32Array((rows + 1) * width) + const matches = (b: number, n: number) => sameNodes(blocks[lo + b]!.nodes, nodes, at + n) && at + n + blocks[lo + b]!.nodes.length <= end + for (let b = rows - 1; b >= 0; b--) { + for (let n = cols - 1; n >= 0; n--) { + let best = Math.max(score[(b + 1) * width + n]!, score[b * width + n + 1]!) + if (matches(b, n)) { + const size = blocks[lo + b]!.nodes.length + best = Math.max(best, size + score[(b + 1) * width + n + size]!) + } + score[b * width + n] = best + } + } + let b = 0 + let n = 0 + while (b < rows && n < cols) { + const size = blocks[lo + b]!.nodes.length + if (matches(b, n) && score[b * width + n] === size + score[(b + 1) * width + n + size]) { + pairs.push({ block: lo + b, node: at + n }) + b++ + n += size + } else if (score[(b + 1) * width + n]! >= score[b * width + n + 1]!) { + b++ + } else { + n++ + } + } + } + return pairs.concat(tail) +} + +/** + * serializeDocument returns the HTML of the edited document (D-03). Runs of + * top-level nodes still equal (Node.eq) to the captured blocks are emitted + * as their original source; raw HTML blocks are emitted verbatim; the rest + * is serialized with the schema, tables in their stored form. It is the + * element's value after a user edit; editor.getHTML() never is. + */ +export function serializeDocument(editor: Editor, blocks: Blocks | null): string { + const serializer = DOMSerializer.fromSchema(editor.schema) + const nodes: PMNode[] = [] + editor.state.doc.forEach((node) => nodes.push(node)) + const captured = blocks?.blocks ?? [] + const pairs = align(captured, nodes) + + let out = '' + let nextBlock = 0 + let nextNode = 0 + const emitGap = (block: number, node: number) => { + if (node > nextNode) { + // Replaced or inserted nodes keep the separator of the first block + // they replace. + if (block > nextBlock) out += captured[nextBlock]!.before + for (let i = nextNode; i < node; i++) out += serializeNode(nodes[i]!, serializer) + } + } + for (const pair of pairs) { + emitGap(pair.block, pair.node) + const block = captured[pair.block]! + out += block.before + block.html + nextBlock = pair.block + 1 + nextNode = pair.node + block.nodes.length + } + emitGap(captured.length, nodes.length) + if (blocks && (pairs.length > 0 || nodes.length === 0)) out += blocks.trailing + return out +} diff --git a/assets/src/blogeditor/toolbar.ts b/assets/src/blogeditor/toolbar.ts new file mode 100644 index 0000000..c384ce8 --- /dev/null +++ b/assets/src/blogeditor/toolbar.ts @@ -0,0 +1,157 @@ +import type { Editor } from '@tiptap/core' +import type { Labels } from './labels' + +/** What the toolbar needs from the element. */ +export interface ToolbarHost { + editor: () => Editor | undefined + labels: Labels + openLink: () => void + openEmbed: () => void + pickImage: () => void + insertRawHtml: () => void + showSource: (on: boolean) => void +} + +export interface Toolbar { + element: HTMLDivElement + /** Updates pressed and enabled states from the editor. */ + refresh: () => void + /** Marks the selected tab. */ + selectTab: (source: boolean) => void + /** Disables every control (the element's disabled attribute). */ + setDisabled: (disabled: boolean) => void +} + +interface ButtonSpec { + command: string + glyph: string + label: keyof Labels + run: (editor: Editor, host: ToolbarHost) => void + active?: (editor: Editor) => boolean + enabled?: (editor: Editor) => boolean + /** Runs without the editor (opens a form or the file picker). */ + host?: boolean +} + +const inTable = (editor: Editor) => editor.isActive('table') + +const GROUPS: ButtonSpec[][] = [ + [ + { command: 'paragraph', glyph: 'P', label: 'paragraph', run: (e) => e.chain().focus().setParagraph().run(), active: (e) => e.isActive('paragraph') }, + { command: 'heading2', glyph: 'H2', label: 'heading2', run: (e) => e.chain().focus().toggleHeading({ level: 2 }).run(), active: (e) => e.isActive('heading', { level: 2 }) }, + { command: 'heading3', glyph: 'H3', label: 'heading3', run: (e) => e.chain().focus().toggleHeading({ level: 3 }).run(), active: (e) => e.isActive('heading', { level: 3 }) }, + { command: 'heading4', glyph: 'H4', label: 'heading4', run: (e) => e.chain().focus().toggleHeading({ level: 4 }).run(), active: (e) => e.isActive('heading', { level: 4 }) }, + ], + [ + { command: 'bold', glyph: 'B', label: 'bold', run: (e) => e.chain().focus().toggleBold().run(), active: (e) => e.isActive('bold') }, + { command: 'italic', glyph: 'I', label: 'italic', run: (e) => e.chain().focus().toggleItalic().run(), active: (e) => e.isActive('italic') }, + { command: 'link', glyph: 'Link', label: 'link', run: (_e, h) => h.openLink(), active: (e) => e.isActive('link'), host: true }, + ], + [ + { command: 'bulletList', glyph: '•', label: 'bulletList', run: (e) => e.chain().focus().toggleBulletList().run(), active: (e) => e.isActive('bulletList') }, + { command: 'orderedList', glyph: '1.', label: 'orderedList', run: (e) => e.chain().focus().toggleOrderedList().run(), active: (e) => e.isActive('orderedList') }, + { command: 'blockquote', glyph: '“”', label: 'blockquote', run: (e) => e.chain().focus().toggleBlockquote().run(), active: (e) => e.isActive('blockquote') }, + ], + [ + { command: 'insertTable', glyph: 'Table', label: 'insertTable', run: (e) => e.chain().focus().insertTable({ rows: 3, cols: 3, withHeaderRow: true }).run() }, + { command: 'addRow', glyph: '+Row', label: 'addRow', run: (e) => e.chain().focus().addRowAfter().run(), enabled: inTable }, + { command: 'deleteRow', glyph: '−Row', label: 'deleteRow', run: (e) => e.chain().focus().deleteRow().run(), enabled: inTable }, + { command: 'addColumn', glyph: '+Col', label: 'addColumn', run: (e) => e.chain().focus().addColumnAfter().run(), enabled: inTable }, + { command: 'deleteColumn', glyph: '−Col', label: 'deleteColumn', run: (e) => e.chain().focus().deleteColumn().run(), enabled: inTable }, + { command: 'deleteTable', glyph: '×Table', label: 'deleteTable', run: (e) => e.chain().focus().deleteTable().run(), enabled: inTable }, + ], + [ + { command: 'image', glyph: 'Image', label: 'image', run: (_e, h) => h.pickImage(), host: true }, + { command: 'embed', glyph: 'Video', label: 'embed', run: (_e, h) => h.openEmbed(), host: true }, + { command: 'rawHtml', glyph: 'HTML', label: 'rawHtml', run: (_e, h) => h.insertRawHtml(), host: true }, + ], + [ + { command: 'undo', glyph: 'Undo', label: 'undo', run: (e) => e.chain().focus().undo().run(), enabled: (e) => e.can().undo() }, + { command: 'redo', glyph: 'Redo', label: 'redo', run: (e) => e.chain().focus().redo().run(), enabled: (e) => e.can().redo() }, + ], +] + +/** + * buildToolbar builds the formatting toolbar and the WYSIWYG/Source tabs + * (D-04): paragraph and headings 2 to 4, bold, italic, link, lists, + * blockquote, tables, image, embed, raw HTML block, undo and redo. + */ +export function buildToolbar(host: ToolbarHost): Toolbar { + const { labels } = host + const element = document.createElement('div') + element.className = 'blogeditor__bar' + + const tools = document.createElement('div') + tools.className = 'blogeditor__tools' + tools.setAttribute('role', 'toolbar') + tools.setAttribute('aria-label', labels.toolbar) + + const buttons: { spec: ButtonSpec; button: HTMLButtonElement }[] = [] + for (const group of GROUPS) { + const wrap = document.createElement('div') + wrap.className = 'blogeditor__group' + for (const spec of group) { + const button = document.createElement('button') + button.type = 'button' + button.dataset.command = spec.command + button.textContent = spec.glyph + button.title = labels[spec.label] + button.setAttribute('aria-label', labels[spec.label]) + // Keep the editor selection when a button is pressed. + button.addEventListener('mousedown', (event) => event.preventDefault()) + button.addEventListener('click', () => { + const editor = host.editor() + if (!editor) return + if (!spec.host && !editor.isEditable) return + spec.run(editor, host) + }) + wrap.append(button) + buttons.push({ spec, button }) + } + tools.append(wrap) + } + + const tabs = document.createElement('div') + tabs.className = 'blogeditor__tabs' + tabs.setAttribute('role', 'tablist') + const tab = (name: 'wysiwyg' | 'source', label: string) => { + const button = document.createElement('button') + button.type = 'button' + button.dataset.tab = name + button.setAttribute('role', 'tab') + button.textContent = label + button.addEventListener('click', () => host.showSource(name === 'source')) + tabs.append(button) + return button + } + const wysiwygTab = tab('wysiwyg', labels.tabWysiwyg) + const sourceTab = tab('source', labels.tabSource) + + element.append(tools, tabs) + + let disabled = false + let source = false + const refresh = () => { + const editor = host.editor() + for (const { spec, button } of buttons) { + if (spec.active) button.setAttribute('aria-pressed', String(!!editor && spec.active(editor))) + const enabled = !!editor && !disabled && !source && (spec.enabled ? spec.enabled(editor) : true) + button.disabled = !enabled + } + } + + return { + element, + refresh, + selectTab: (on) => { + source = on + wysiwygTab.setAttribute('aria-selected', String(!on)) + sourceTab.setAttribute('aria-selected', String(on)) + refresh() + }, + setDisabled: (on) => { + disabled = on + refresh() + }, + } +} diff --git a/tests/blogeditor/corpus.test.ts b/tests/blogeditor/corpus.test.ts new file mode 100644 index 0000000..7a673e6 --- /dev/null +++ b/tests/blogeditor/corpus.test.ts @@ -0,0 +1,210 @@ +import { readFileSync, writeFileSync } from 'node:fs' +import { dirname, join } from 'node:path' +import { fileURLToPath } from 'node:url' +import type { Editor } from '@tiptap/core' +import { afterAll, describe, expect, it } from 'vitest' +import { parseEmbedUrl } from '../../assets/src/blogeditor/embed' +import { isPolicyUrl } from '../../assets/src/blogeditor/extensions' +import { mount, type } from './helpers' + +// The editor's own output (D-05, D-10 amended). Every entry is built through +// editor commands and typing only, never by inserting HTML, so it is what +// the toolbar and input rules produce. The committed file is read in place +// by the Go policy test (classes/editor_policy_test.go) and copied into the +// layer, so both sanitizer policies are tested against the real output. +// Entry names are stable once committed. UPDATE_CORPUS=1 rewrites the file. +const CORPUS = join(dirname(fileURLToPath(import.meta.url)), 'fixtures', 'editor-corpus.json') + +interface Entry { + name: string + html: string +} + +/** startBlock puts the cursor in an empty paragraph at the end of the document. */ +function startBlock(editor: Editor): void { + const { doc } = editor.state + const last = doc.lastChild + if (last && last.type.name === 'paragraph' && last.content.size === 0) { + editor.commands.setTextSelection(doc.content.size - 1) + return + } + editor.commands.insertContentAt(doc.content.size, { type: 'paragraph' }) + editor.commands.setTextSelection(editor.state.doc.content.size - 1) +} + +/** link types text and links it through setLink, then leaves the link. */ +function link(editor: Editor, text: string, href: string): void { + const from = editor.state.selection.from + type(editor, text) + const to = editor.state.selection.from + expect(editor.chain().setTextSelection({ from, to }).setLink({ href }).run(), href).toBe(true) + editor.chain().setTextSelection(to).unsetMark('link').run() +} + +function mark(editor: Editor, toggle: () => boolean, text: string): void { + expect(toggle()).toBe(true) + type(editor, text) + expect(toggle()).toBe(true) +} + +const IMAGE_SRC = '/storage/app/uploads/public/journal/2026/10/turkey-tail.jpg' + +const builders: Record void> = { + 'embed-youtube': (editor) => { + startBlock(editor) + const embed = parseEmbedUrl('https://www.youtube.com/watch?v=dQw4w9WgXcQ')! + expect(editor.commands.setEmbed(embed)).toBe(true) + }, + 'image-without-caption': (editor) => { + startBlock(editor) + expect(editor.commands.setImage({ src: IMAGE_SRC, alt: 'Turkey Tail: czy to "grzyb odporności"?' })).toBe(true) + }, + 'image-with-caption': (editor) => { + startBlock(editor) + expect( + editor.commands.setFigure({ src: IMAGE_SRC, alt: 'Owocniki wrośniaka', caption: 'Owocniki wrośniaka różnobarwnego.' }), + ).toBe(true) + }, + 'table-header-row': (editor) => { + startBlock(editor) + expect(editor.commands.insertTable({ rows: 3, cols: 3, withHeaderRow: true })).toBe(true) + const cells = ['Forma', 'Dawka', 'Uwagi', 'Proszek', '1-2 g', 'z posiłkiem', 'Kapsułki', '2 x 500 mg', 'rano'] + cells.forEach((text, i) => { + if (i > 0) expect(editor.commands.goToNextCell()).toBe(true) + type(editor, text) + }) + }, + links: (editor) => { + startBlock(editor) + type(editor, 'Źródła: ') + link(editor, 'strona', 'http://example.test/') + type(editor, ', ') + link(editor, 'badania', 'https://example.test/badania?rok=2026#wyniki') + type(editor, ', ') + link(editor, 'redakcja', 'mailto:redakcja@example.test') + type(editor, ' i ') + link(editor, 'inny wpis', '/blog/beta-glukany') + type(editor, '.') + }, + headings: (editor) => { + for (const level of [2, 3, 4] as const) { + startBlock(editor) + expect(editor.commands.setHeading({ level })).toBe(true) + type(editor, `Nagłówek ${level}`) + } + }, + 'bullet-list': (editor) => { + startBlock(editor) + expect(editor.commands.toggleBulletList()).toBe(true) + type(editor, 'Beta-glukany') + expect(editor.commands.splitListItem('listItem')).toBe(true) + type(editor, 'Antyoksydanty') + }, + 'ordered-list': (editor) => { + startBlock(editor) + expect(editor.commands.toggleOrderedList()).toBe(true) + type(editor, 'Pierwszy krok') + expect(editor.commands.splitListItem('listItem')).toBe(true) + type(editor, 'Drugi krok') + }, + // The blockquote sits between the two ordered lists, so the combined + // document keeps them as two lists instead of joining them. + blockquote: (editor) => { + startBlock(editor) + expect(editor.commands.toggleBlockquote()).toBe(true) + type(editor, 'Grzyby funkcjonalne wspierają organizm.') + }, + 'ordered-list-start-3': (editor) => { + startBlock(editor) + expect(editor.commands.toggleOrderedList()).toBe(true) + expect(editor.commands.updateAttributes('orderedList', { start: 3 })).toBe(true) + type(editor, 'Trzeci krok') + expect(editor.commands.splitListItem('listItem')).toBe(true) + type(editor, 'Czwarty krok') + }, + 'inline-marks': (editor) => { + startBlock(editor) + type(editor, 'Tekst ') + mark(editor, () => editor.commands.toggleBold(), 'pogrubiony') + type(editor, ', ') + mark(editor, () => editor.commands.toggleItalic(), 'kursywa') + type(editor, ', ') + mark(editor, () => editor.commands.toggleStrike(), 'przekreślony') + type(editor, ', ') + mark(editor, () => editor.commands.toggleUnderline(), 'podkreślony') + type(editor, ' i ') + mark(editor, () => editor.commands.toggleCode(), 'kod') + type(editor, '.') + }, + 'code-block': (editor) => { + startBlock(editor) + expect(editor.commands.toggleCodeBlock()).toBe(true) + type(editor, 'dawka = 2 * 500 // mg') + }, + 'horizontal-rule': (editor) => { + startBlock(editor) + type(editor, 'Przed linią') + expect(editor.commands.setHorizontalRule()).toBe(true) + type(editor, 'Po linii') + }, + 'hard-break': (editor) => { + startBlock(editor) + type(editor, 'Pierwsza linia') + expect(editor.commands.setHardBreak()).toBe(true) + type(editor, 'Druga linia') + }, +} + +function build(steps: ((editor: Editor) => void)[]): string { + const { el, editor } = mount('') + for (const step of steps) step(editor) + const html = el.value + el.remove() + return html +} + +function corpus(): Entry[] { + const entries: Entry[] = Object.entries(builders).map(([name, step]) => ({ name, html: build([step]) })) + entries.push({ name: 'combined', html: build(Object.values(builders)) }) + return entries +} + +describe('editor corpus (D-05)', () => { + const entries = corpus() + + afterAll(() => { + document.body.replaceChildren() + }) + + it('matches the committed editor-corpus.json', () => { + const text = `${JSON.stringify(entries, null, 2)}\n` + if (process.env.UPDATE_CORPUS === '1') { + writeFileSync(CORPUS, text) + } + expect(readFileSync(CORPUS, 'utf8')).toBe(text) + }) + + it('holds no iframe, handler, target, rel or style and only policy URLs', () => { + expect(entries.length).toBeGreaterThanOrEqual(15) + const doc = document.implementation.createHTMLDocument('') + for (const { name, html } of entries) { + expect(html, name).not.toMatch(/<\/p>$/) + const host = doc.createElement('div') + host.innerHTML = html + for (const el of Array.from(host.querySelectorAll('[href], [src]'))) { + const url = el.getAttribute('href') ?? el.getAttribute('src') ?? '' + expect(isPolicyUrl(url), `${name}: ${url}`).toBe(true) + } + for (const a of Array.from(host.querySelectorAll('a'))) { + expect(a.getAttributeNames(), name).toEqual(['href']) + } + } + const html = entries.map((e) => e.html).join('\n') + expect(html).toContain('
') + expect(html).toContain('
') + expect(html).toContain('') + expect(html).toContain('start="3"') + }) +}) diff --git a/tests/blogeditor/fixtures/editor-corpus.json b/tests/blogeditor/fixtures/editor-corpus.json new file mode 100644 index 0000000..681ce3b --- /dev/null +++ b/tests/blogeditor/fixtures/editor-corpus.json @@ -0,0 +1,62 @@ +[ + { + "name": "embed-youtube", + "html": "
" + }, + { + "name": "image-without-caption", + "html": "

\"Turkey

" + }, + { + "name": "image-with-caption", + "html": "
\"Owocniki
Owocniki wrośniaka różnobarwnego.
" + }, + { + "name": "table-header-row", + "html": "
FormaDawkaUwagi
Proszek1-2 gz posiłkiem
Kapsułki2 x 500 mgrano
" + }, + { + "name": "links", + "html": "

Źródła: strona, badania, redakcja i inny wpis.

" + }, + { + "name": "headings", + "html": "

Nagłówek 2

Nagłówek 3

Nagłówek 4

" + }, + { + "name": "bullet-list", + "html": "
  • Beta-glukany

  • Antyoksydanty

" + }, + { + "name": "ordered-list", + "html": "
  1. Pierwszy krok

  2. Drugi krok

" + }, + { + "name": "blockquote", + "html": "

Grzyby funkcjonalne wspierają organizm.

" + }, + { + "name": "ordered-list-start-3", + "html": "
  1. Trzeci krok

  2. Czwarty krok

" + }, + { + "name": "inline-marks", + "html": "

Tekst pogrubiony, kursywa, przekreślony, podkreślony i kod.

" + }, + { + "name": "code-block", + "html": "
dawka = 2 * 500 // mg
" + }, + { + "name": "horizontal-rule", + "html": "

Przed linią


Po linii

" + }, + { + "name": "hard-break", + "html": "

Pierwsza linia
Druga linia

" + }, + { + "name": "combined", + "html": "

\"Turkey

\"Owocniki
Owocniki wrośniaka różnobarwnego.
FormaDawkaUwagi
Proszek1-2 gz posiłkiem
Kapsułki2 x 500 mgrano

Źródła: strona, badania, redakcja i inny wpis.

Nagłówek 2

Nagłówek 3

Nagłówek 4

  • Beta-glukany

  • Antyoksydanty

  1. Pierwszy krok

  2. Drugi krok

Grzyby funkcjonalne wspierają organizm.

  1. Trzeci krok

  2. Czwarty krok

Tekst pogrubiony, kursywa, przekreślony, podkreślony i kod.

dawka = 2 * 500 // mg

Przed linią


Po linii

Pierwsza linia
Druga linia

" + } +] diff --git a/tests/blogeditor/helpers.ts b/tests/blogeditor/helpers.ts new file mode 100644 index 0000000..000452b --- /dev/null +++ b/tests/blogeditor/helpers.ts @@ -0,0 +1,78 @@ +import type { Editor } from '@tiptap/core' +import '../../assets/src/blogeditor/index' +import { BlogEditorElement, TAG } from '../../assets/src/blogeditor/index' + +export interface Mounted { + el: BlogEditorElement + editor: Editor + changes: string[] + uploads: { id: string; file: File }[] +} + +/** mount creates a connected editor element, optionally with a value. */ +export function mount(value?: string, attributes: Record = {}): Mounted { + const el = document.createElement(TAG) as BlogEditorElement + for (const [name, val] of Object.entries(attributes)) el.setAttribute(name, val) + const changes: string[] = [] + const uploads: { id: string; file: File }[] = [] + el.addEventListener('summer-change', (e) => changes.push((e as CustomEvent<{ value: string }>).detail.value)) + el.addEventListener('summer-upload', (e) => uploads.push((e as CustomEvent<{ id: string; file: File }>).detail)) + if (value !== undefined) el.value = value + document.body.append(el) + return { el, editor: el.editor!, changes, uploads } +} + +/** type inserts text at the selection, as typing does. */ +export function type(editor: Editor, text: string): void { + editor.view.dispatch(editor.state.tr.insertText(text)) +} + +/** insertAtBlock types text at the start of the top-level textblock index. */ +export function insertAtBlock(editor: Editor, index: number, text: string): void { + let pos = -1 + editor.state.doc.forEach((node, offset, i) => { + if (i === index) pos = node.isTextblock ? offset + 1 : -1 + }) + if (pos < 0) throw new Error(`block ${index} is not a textblock`) + editor.view.dispatch(editor.state.tr.insertText(text, pos)) +} + +/** insertAtEveryTextblock types text at the start of every textblock. */ +export function insertAtEveryTextblock(editor: Editor, text: string): void { + const positions: number[] = [] + editor.state.doc.descendants((node, pos) => { + if (node.isTextblock) positions.push(pos + 1) + return true + }) + let tr = editor.state.tr + for (const pos of positions.reverse()) tr = tr.insertText(text, pos) + editor.view.dispatch(tr) +} + +/** button returns the toolbar button for a command. */ +export function button(el: HTMLElement, command: string): HTMLButtonElement { + const found = el.querySelector(`button[data-command="${command}"]`) + if (!found) throw new Error(`no toolbar button ${command}`) + return found +} + +/** form returns the inline form of a kind, or null when it is closed. */ +export function form(el: HTMLElement, kind: string): HTMLElement | null { + const found = el.querySelector(`[data-form="${kind}"]`) + return found && !found.hidden ? found : null +} + +export function click(el: Element | null | undefined): void { + if (!el) throw new Error('nothing to click') + ;(el as HTMLElement).click() +} + +export function fill(input: Element | null | undefined, value: string): void { + if (!input) throw new Error('no input') + ;(input as HTMLInputElement).value = value + input.dispatchEvent(new Event('input', { bubbles: true })) +} + +export function status(el: HTMLElement): string { + return el.querySelector('[role="status"]')?.textContent ?? '' +} diff --git a/tests/blogeditor/smoke.test.ts b/tests/blogeditor/smoke.test.ts index f93c104..6658511 100644 --- a/tests/blogeditor/smoke.test.ts +++ b/tests/blogeditor/smoke.test.ts @@ -1,18 +1,12 @@ -import { afterEach, describe, expect, it } from 'vitest' +import { afterEach, describe, expect, it, vi } from 'vitest' import fixture from './fixtures/imported-post.html?raw' -import '../../assets/src/blogeditor/index' import { BlogEditorElement, TAG } from '../../assets/src/blogeditor/index' - -function mount(value?: string): { el: BlogEditorElement; changes: string[] } { - const el = document.createElement(TAG) as BlogEditorElement - const changes: string[] = [] - el.addEventListener('summer-change', (e) => changes.push((e as CustomEvent<{ value: string }>).detail.value)) - if (value !== undefined) el.value = value - document.body.append(el) - return { el, changes } -} +import { parseEmbedUrl } from '../../assets/src/blogeditor/embed' +import { isPolicyUrl } from '../../assets/src/blogeditor/extensions' +import { button, click, fill, form, insertAtBlock, insertAtEveryTextblock, mount, status } from './helpers' afterEach(() => { + vi.useRealTimers() document.body.replaceChildren() }) @@ -44,8 +38,7 @@ describe('blog editor element (tracer)', () => { }) it('emits exactly one summer-change per user edit with the element value', () => { - const { el, changes } = mount('

Hello

') - const editor = el.editor! + const { el, editor, changes } = mount('

Hello

') editor.view.dispatch(editor.state.tr.insertText('X', 1)) expect(changes).toHaveLength(1) expect(changes[0]).toBe(el.value) @@ -75,12 +68,25 @@ describe('blog editor element (tracer)', () => { expect(changes).toHaveLength(1) }) + it('keeps an edited value after it is detached and attached again', () => { + const { el, editor, changes } = mount('

a

') + editor.view.dispatch(editor.state.tr.insertText('X', 1)) + el.remove() + expect(el.value).toBe('

Xa

') + document.body.append(el) + expect(el.value).toBe('

Xa

') + expect(el.editor!.state.doc.textContent).toBe('Xa') + expect(changes).toEqual(['

Xa

']) + }) + it('a new external value replaces the content without an event', () => { const { el, changes } = mount('

One

') el.value = '

Two

' expect(el.value).toBe('

Two

') expect(el.editor!.state.doc.textContent).toBe('Two') expect(changes).toEqual([]) + // The replaced value is not in the undo history. + expect(el.editor!.can().undo()).toBe(false) }) it('disabled makes the editor and the source read-only; invalid sets aria-invalid', () => { @@ -96,3 +102,400 @@ describe('blog editor element (tracer)', () => { expect(el.editor!.view.dom.hasAttribute('aria-invalid')).toBe(false) }) }) + +describe('preservation schema', () => { + const rawBlocks = [ + '

Autor

', + '

Sekcja

', + '', + '

Nagłówek

', + '', + '
WięcejTreść
', + '', + '
Pudełko
', + '
Cytat
Autor
', + ] + + it('turns unknown block markup into raw HTML cards that keep it through an edit', () => { + const html = `

Start

\n${rawBlocks.join('\n')}\n` + const { el, editor } = mount(html) + const types: string[] = [] + editor.state.doc.forEach((node) => types.push(node.type.name)) + expect(types).toEqual(['paragraph', ...rawBlocks.map(() => 'rawHtml')]) + + const cards = Array.from(el.querySelectorAll('.blogeditor__raw-source')).map((n) => n.textContent) + expect(cards).toEqual(rawBlocks) + + insertAtBlock(editor, 0, 'X') + expect(el.value).toBe(`

XStart

\n${rawBlocks.join('\n')}\n`) + }) + + it('renders a raw HTML card as text, never as live markup', () => { + const payload = '
' + const { el, editor } = mount(`

a

${payload}`) + expect(editor.state.doc.child(1).type.name).toBe('rawHtml') + expect(el.querySelector('.ProseMirror img')).toBeNull() + expect(el.querySelector('.ProseMirror script')).toBeNull() + expect(el.querySelector('.blogeditor__raw-source')!.textContent).toBe(payload) + expect((window as unknown as { __blogeditorPwned?: number }).__blogeditorPwned).toBeUndefined() + + // Handler attributes on modelled nodes never reach the editor DOM. + const inline = mount('

a

') + const img = inline.el.querySelector('.ProseMirror img:not(.ProseMirror-separator)')! + expect(img.getAttribute('src')).toBe('/a.png') + expect(img.getAttributeNames().filter((name) => name.startsWith('on'))).toEqual([]) + }) + + it('keeps unmodelled attributes on edited blocks and spans as marks', () => { + const html = + '

Tekst czerwony

' + + '

Tytuł

' + + '
  • Punkt

' + + '
  1. Trzy

' + + '

Cytat

' + + '

link A

' + + '
1
' + const { el, editor } = mount(html) + insertAtEveryTextblock(editor, 'X') + expect(el.value).toBe( + '

XTekst czerwony

' + + '

XTytuł

' + + '
  • XPunkt

' + + '
  1. XTrzy

' + + '

XCytat

' + + '

Xlink A

' + + '
X1
', + ) + }) + + it('leaves every other top-level block byte-identical after editing one paragraph', () => { + const { el, editor, changes } = mount(fixture) + insertAtBlock(editor, 1, 'X') + const expected = fixture.replace('

Turkey Tail', '

XTurkey Tail') + expect(expected).not.toBe(fixture) + expect(el.value).toBe(expected) + expect(changes).toEqual([expected]) + + // Undoing the edit gives back the exact original bytes. + expect(editor.commands.undo()).toBe(true) + expect(el.value).toBe(fixture) + }) + + it('serializes tables without colgroup or min-width, with thead and bare cell text', () => { + const html = '
AB
12
' + const { el, editor } = mount(html) + insertAtEveryTextblock(editor, 'X') + expect(el.value).toBe( + '
XAXB
X1X2
', + ) + + const fresh = mount('

t

') + fresh.editor.commands.setTextSelection(1) + expect(fresh.editor.commands.insertTable({ rows: 2, cols: 2, withHeaderRow: true })).toBe(true) + expect(fresh.el.value).not.toMatch(/colgroup|min-width|style=/) + expect(fresh.el.value).toContain('') + expect(fresh.el.value).not.toMatch(/

<\/p>$/) + }) + + it('keeps stored link target and rel, adds none and leaves no trailing paragraph', () => { + // Text typed at the start of a link joins the link (links are inclusive). + // Edited links keep their attributes; their order may change. + const { el, editor } = mount('

x y


') + insertAtBlock(editor, 0, 'Z') + expect(el.value).toBe('

Zx y


') + + const fresh = mount('

link

') + fresh.editor.commands.setTextSelection({ from: 1, to: 5 }) + expect(fresh.editor.commands.setLink({ href: 'https://example.test/' })).toBe(true) + expect(fresh.el.value).toBe('

link

') + }) +}) + +describe('embeds', () => { + it('parses supported YouTube URLs to the 11-character id', () => { + const id = 'dQw4w9WgXcQ' + for (const url of [ + `https://www.youtube.com/watch?v=${id}`, + `https://youtube.com/watch?v=${id}&t=42s`, + `https://m.youtube.com/watch?feature=share&v=${id}`, + `https://youtu.be/${id}`, + `https://youtu.be/${id}?si=abc`, + `https://www.youtube.com/shorts/${id}`, + `https://www.youtube.com/embed/${id}`, + ` https://www.youtube-nocookie.com/embed/${id} `, + ]) { + expect(parseEmbedUrl(url), url).toEqual({ provider: 'youtube', id }) + } + for (const url of [ + 'https://vimeo.com/123456', + 'https://www.youtube.com/watch?v=short', + 'https://www.youtube.com/watch?v=dQw4w9WgXcQQ', + 'https://youtu.be/dQw4w9WgXc!', + 'https://evil.test/embed/dQw4w9WgXcQ', + 'javascript:alert(1)//youtu.be/dQw4w9WgXcQ', + 'ftp://youtu.be/dQw4w9WgXcQ', + 'not a url', + '', + ]) { + expect(parseEmbedUrl(url), url).toBeNull() + } + }) + + it('round-trips the exact placeholder and shows a card, never an iframe', () => { + const placeholder = '
' + const { el, editor } = mount(`

a

${placeholder}`) + expect(editor.state.doc.child(1).type.name).toBe('embed') + expect(el.querySelector('iframe')).toBeNull() + expect(el.querySelector('.blogeditor__embed')!.textContent).toContain('YouTube') + insertAtBlock(editor, 0, 'X') + expect(el.value).toBe(`

Xa

${placeholder}`) + + const fresh = mount('') + expect(fresh.editor.commands.setEmbed({ provider: 'youtube', id: 'dQw4w9WgXcQ' })).toBe(true) + expect(fresh.el.value).toBe(placeholder) + expect(fresh.editor.commands.setEmbed({ provider: 'youtube', id: 'bad' })).toBe(false) + expect(fresh.editor.commands.setEmbed({ provider: 'vimeo', id: 'dQw4w9WgXcQ' })).toBe(false) + }) + + it('keeps a malformed placeholder as raw HTML', () => { + const { editor } = mount('
') + expect(editor.state.doc.child(0).type.name).toBe('rawHtml') + }) + + it('inserts an embed from the toolbar URL input and refuses unsupported URLs', () => { + const { el } = mount('') + click(button(el, 'embed')) + const embedForm = form(el, 'embed')! + fill(embedForm.querySelector('input'), 'https://vimeo.com/1') + click(embedForm.querySelector('[data-action="insert"]')) + expect(form(el, 'embed')).not.toBeNull() + expect(embedForm.querySelector('[data-error]')!.textContent).toBe('This video URL is not supported. Paste a YouTube link.') + expect(el.value).toBe('') + + fill(embedForm.querySelector('input'), 'https://youtu.be/dQw4w9WgXcQ') + click(embedForm.querySelector('[data-action="insert"]')) + expect(form(el, 'embed')).toBeNull() + expect(el.value).toBe('
') + }) +}) + +describe('image uploads', () => { + function pick(el: HTMLElement, files: File[]): void { + const input = el.querySelector('input[type="file"]')! + expect(input.accept).toBe('image/jpeg,image/png,image/gif,image/webp') + Object.defineProperty(input, 'files', { value: files, configurable: true }) + input.dispatchEvent(new Event('change')) + } + + function answer(el: HTMLElement, detail: Record): void { + el.dispatchEvent(new CustomEvent('summer-upload-result', { detail })) + } + + const png = () => new File([new Uint8Array([137, 80, 78, 71])], 'grzyb.png', { type: 'image/png' }) + + it('sends a picked image as summer-upload and inserts img with alt text', () => { + const { el, uploads } = mount('') + click(button(el, 'image')) + pick(el, [png()]) + expect(uploads).toHaveLength(1) + expect(uploads[0]!.file.name).toBe('grzyb.png') + expect(uploads[0]!.id).toMatch(/[0-9a-f-]{36}/) + expect(status(el)).toBe('Uploading grzyb.png…') + + answer(el, { id: 'someone-else', url: '/x.png' }) + expect(form(el, 'image')).toBeNull() + + answer(el, { id: uploads[0]!.id, url: '/storage/app/uploads/public/journal/grzyb.png' }) + const imageForm = form(el, 'image')! + click(imageForm.querySelector('[data-action="insert"]')) + expect(imageForm.querySelector('[data-error]')!.textContent).toBe('Enter the alt text.') + expect(el.value).toBe('') + + fill(imageForm.querySelector('input[name="alt"]'), 'Grzyb: czy to "Turkey Tail"?') + click(imageForm.querySelector('[data-action="insert"]')) + expect(form(el, 'image')).toBeNull() + expect(el.value).toBe('

Grzyb: czy to "Turkey Tail"?

') + }) + + it('inserts figure with figcaption when a caption is given', () => { + const { el, uploads } = mount('') + pick(el, [png()]) + answer(el, { id: uploads[0]!.id, url: '/a.png' }) + const imageForm = form(el, 'image')! + fill(imageForm.querySelector('input[name="alt"]'), 'Owocniki') + fill(imageForm.querySelector('input[name="caption"]'), 'Owocniki na pniu.') + click(imageForm.querySelector('[data-action="insert"]')) + expect(el.value).toBe('
Owocniki
Owocniki na pniu.
') + }) + + it('shows an upload error and inserts nothing', () => { + const { el, uploads, changes } = mount('

a

') + pick(el, [png()]) + answer(el, { id: uploads[0]!.id, error: 'File too large' }) + expect(form(el, 'image')).toBeNull() + expect(status(el)).toBe('Upload failed: File too large') + expect(el.value).toBe('

a

') + expect(changes).toEqual([]) + }) + + it('ends a pending upload after 60 seconds', () => { + vi.useFakeTimers() + const { el, uploads } = mount('') + pick(el, [png()]) + vi.advanceTimersByTime(60_000) + expect(status(el)).toBe('The upload of grzyb.png took too long.') + answer(el, { id: uploads[0]!.id, url: '/late.png' }) + expect(form(el, 'image')).toBeNull() + }) + + it('uploads image files dropped on the editor', () => { + const { el, editor, uploads } = mount('

a

') + let prevented = false + const event = { + dataTransfer: { files: [png(), new File(['x'], 'notes.txt', { type: 'text/plain' })] }, + preventDefault: () => { + prevented = true + }, + } as unknown as DragEvent + const handled = editor.view.someProp('handleDrop', (f) => f(editor.view, event, editor.state.doc.slice(0, 0), false)) + expect(handled).toBe(true) + expect(prevented).toBe(true) + expect(uploads.map((u) => u.file.name)).toEqual(['grzyb.png']) + expect(el.value).toBe('

a

') + }) +}) + +describe('links and the URL rule', () => { + it('accepts only http, https, mailto and relative URLs', () => { + for (const url of ['http://a.test', 'https://a.test/x?y#z', 'HTTPS://A.TEST', 'mailto:a@b.test', '/rel', 'rel/path', '#frag', '?q=1', '']) { + expect(isPolicyUrl(url), url).toBe(true) + } + for (const url of [ + 'javascript:alert(1)', + 'JavaScript:alert(1)', + ' javascript:alert(1)', + 'java\tscript:alert(1)', + 'java\nscript:alert(1)', + 'vbscript:msgbox(1)', + 'data:text/html,x', + 'tel:+48123', + 'ftp://a.test/', + ]) { + expect(isPolicyUrl(url), JSON.stringify(url)).toBe(false) + } + }) + + it('refuses links outside the rule in commands and in stored HTML', () => { + const { el, editor } = mount('

text

bad

') + expect(el.querySelector('.ProseMirror a')).toBeNull() + editor.commands.setTextSelection({ from: 1, to: 5 }) + expect(editor.commands.setLink({ href: 'javascript:alert(1)' })).toBe(false) + expect(editor.commands.setLink({ href: 'tel:+48123' })).toBe(false) + expect(editor.commands.setLink({ href: 'java\tscript:alert(1)' })).toBe(false) + }) + + it('creates, refuses and removes links through the toolbar input', () => { + const { el, editor } = mount('

link

') + editor.commands.setTextSelection({ from: 1, to: 5 }) + click(button(el, 'link')) + const linkForm = form(el, 'link')! + fill(linkForm.querySelector('input'), 'data:text/html,x') + click(linkForm.querySelector('[data-action="apply"]')) + expect(linkForm.querySelector('[data-error]')!.textContent).toBe('Links must use http, https, mailto or a relative URL.') + expect(el.value).toBe('

link

') + + fill(linkForm.querySelector('input'), 'mailto:redakcja@example.test') + click(linkForm.querySelector('[data-action="apply"]')) + expect(el.value).toBe('

link

') + + editor.commands.setTextSelection(2) + click(button(el, 'link')) + const again = form(el, 'link')! + expect((again.querySelector('input') as HTMLInputElement).value).toBe('mailto:redakcja@example.test') + fill(again.querySelector('input'), '') + click(again.querySelector('[data-action="apply"]')) + expect(el.value).toBe('

link

') + }) +}) + +describe('toolbar', () => { + it('offers every D-04 feature and the tabs', () => { + const { el } = mount('') + for (const command of [ + 'paragraph', + 'heading2', + 'heading3', + 'heading4', + 'bold', + 'italic', + 'bulletList', + 'orderedList', + 'link', + 'blockquote', + 'insertTable', + 'addRow', + 'deleteRow', + 'addColumn', + 'deleteColumn', + 'deleteTable', + 'image', + 'embed', + 'rawHtml', + 'undo', + 'redo', + ]) { + expect(button(el, command).getAttribute('aria-label'), command).toBeTruthy() + } + expect(el.querySelector('[data-tab="wysiwyg"]')!.textContent).toBe('WYSIWYG') + expect(el.querySelector('[data-tab="source"]')!.textContent).toBe('Source') + }) + + it('uses the Polish labels for ui-locale pl', () => { + const { el } = mount('', { 'ui-locale': 'pl' }) + expect(el.querySelector('[data-tab="source"]')!.textContent).toBe('Źródło') + expect(button(el, 'bold').getAttribute('aria-label')).toBe('Pogrubienie') + }) + + it('formats text and edits tables from the toolbar', () => { + const { el, editor } = mount('

abc

') + editor.commands.setTextSelection({ from: 1, to: 4 }) + click(button(el, 'bold')) + expect(el.value).toBe('

abc

') + expect(button(el, 'bold').getAttribute('aria-pressed')).toBe('true') + click(button(el, 'undo')) + expect(el.value).toBe('

abc

') + click(button(el, 'redo')) + expect(el.value).toBe('

abc

') + click(button(el, 'heading3')) + expect(el.value).toBe('

abc

') + + editor.commands.setTextSelection(4) + click(button(el, 'insertTable')) + expect(el.value).toContain('') + click(button(el, 'addRow')) + click(button(el, 'deleteColumn')) + expect(el.value.match(//g)).toHaveLength(4) + expect(el.value).toContain('') + click(button(el, 'deleteTable')) + expect(el.value).not.toContain(' { + const { el, editor } = mount('

a

') + editor.commands.setTextSelection(2) + click(button(el, 'rawHtml')) + const textarea = el.querySelector('textarea')! + expect(textarea.hidden).toBe(false) + expect(el.value).toBe('

a

') + expect(textarea.value).toBe('

a

') + expect(textarea.selectionStart).toBe('

a

'.length) + }) + + it('edits a raw HTML card in the source tab', () => { + const { el } = mount('

a

\n
f
') + click(el.querySelector('.blogeditor__raw button')) + const textarea = el.querySelector('textarea')! + expect(textarea.hidden).toBe(false) + expect(textarea.value.slice(textarea.selectionStart, textarea.selectionEnd)).toBe('
f
') + }) +})