kritzel-stencil 0.4.0 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (81) hide show
  1. package/dist/cjs/index.cjs.js +2 -1
  2. package/dist/cjs/kritzel-active-users_47.cjs.entry.js +249 -68
  3. package/dist/cjs/loader.cjs.js +1 -1
  4. package/dist/cjs/{schema.constants-fuAsi56H.js → schema.constants-IAt9YXDZ.js} +273 -32
  5. package/dist/cjs/stencil.cjs.js +1 -1
  6. package/dist/collection/classes/handlers/context-menu.handler.js +2 -3
  7. package/dist/collection/classes/managers/clipboard.manager.js +9 -3
  8. package/dist/collection/classes/objects/base-object.class.js +0 -1
  9. package/dist/collection/classes/objects/text.class.js +2 -1
  10. package/dist/collection/classes/registries/font-registry.class.js +161 -0
  11. package/dist/collection/classes/structures/object-map.structure.js +9 -0
  12. package/dist/collection/classes/tools/image-tool.class.js +19 -3
  13. package/dist/collection/classes/tools/text-tool.class.js +2 -0
  14. package/dist/collection/components/core/kritzel-awareness-cursors/kritzel-awareness-cursors.js +22 -7
  15. package/dist/collection/components/core/kritzel-editor/kritzel-editor.js +138 -9
  16. package/dist/collection/components/core/kritzel-engine/kritzel-engine.js +58 -13
  17. package/dist/collection/components/shared/kritzel-font-family/kritzel-font-family.js +31 -22
  18. package/dist/collection/components/ui/kritzel-controls/kritzel-controls.js +10 -11
  19. package/dist/collection/components/ui/kritzel-tool-config/kritzel-tool-config.js +40 -5
  20. package/dist/collection/configs/default-text-tool.config.js +2 -0
  21. package/dist/collection/constants/text-tool-fonts.constants.js +18 -0
  22. package/dist/collection/constants/version.js +1 -1
  23. package/dist/collection/helpers/image-file.helper.js +6 -0
  24. package/dist/collection/index.js +2 -0
  25. package/dist/collection/interfaces/font.interface.js +1 -0
  26. package/dist/components/index.js +1 -1
  27. package/dist/components/kritzel-awareness-cursors.js +1 -1
  28. package/dist/components/kritzel-controls.js +1 -1
  29. package/dist/components/kritzel-cursor-trail.js +1 -1
  30. package/dist/components/kritzel-editor.js +1 -1
  31. package/dist/components/kritzel-engine.js +1 -1
  32. package/dist/components/kritzel-font-family.js +1 -1
  33. package/dist/components/kritzel-settings.js +1 -1
  34. package/dist/components/kritzel-tool-config.js +1 -1
  35. package/dist/components/p-BH4oJ7yX.js +9 -0
  36. package/dist/components/p-C38P-Vd0.js +1 -0
  37. package/dist/components/p-Cm33td2O.js +1 -0
  38. package/dist/components/{p-zhjb97WN.js → p-Co165PAZ.js} +1 -1
  39. package/dist/components/p-DJkKlUyZ.js +1 -0
  40. package/dist/components/p-JYj3Facr.js +1 -0
  41. package/dist/components/p-Ka7OWbnk.js +1 -0
  42. package/dist/components/p-djJSnjAX.js +1 -0
  43. package/dist/esm/index.js +2 -2
  44. package/dist/esm/kritzel-active-users_47.entry.js +249 -68
  45. package/dist/esm/loader.js +1 -1
  46. package/dist/esm/{schema.constants-Cv5-yM39.js → schema.constants-rIkxAcpB.js} +271 -33
  47. package/dist/esm/stencil.js +1 -1
  48. package/dist/stencil/index.esm.js +1 -1
  49. package/dist/stencil/p-966ca4b5.entry.js +9 -0
  50. package/dist/stencil/p-rIkxAcpB.js +1 -0
  51. package/dist/stencil/stencil.esm.js +1 -1
  52. package/dist/types/classes/managers/clipboard.manager.d.ts +1 -0
  53. package/dist/types/classes/objects/base-object.class.d.ts +0 -1
  54. package/dist/types/classes/registries/font-registry.class.d.ts +19 -0
  55. package/dist/types/classes/structures/object-map.structure.d.ts +2 -2
  56. package/dist/types/classes/tools/image-tool.class.d.ts +9 -2
  57. package/dist/types/classes/tools/text-tool.class.d.ts +3 -0
  58. package/dist/types/components/core/kritzel-awareness-cursors/kritzel-awareness-cursors.d.ts +2 -0
  59. package/dist/types/components/core/kritzel-editor/kritzel-editor.d.ts +22 -0
  60. package/dist/types/components/core/kritzel-engine/kritzel-engine.d.ts +10 -0
  61. package/dist/types/components/shared/kritzel-font-family/kritzel-font-family.d.ts +4 -0
  62. package/dist/types/components/ui/kritzel-tool-config/kritzel-tool-config.d.ts +1 -0
  63. package/dist/types/components.d.ts +20 -2
  64. package/dist/types/constants/text-tool-fonts.constants.d.ts +3 -0
  65. package/dist/types/constants/version.d.ts +1 -1
  66. package/dist/types/helpers/image-file.helper.d.ts +3 -0
  67. package/dist/types/index.d.ts +2 -0
  68. package/dist/types/interfaces/font.interface.d.ts +15 -0
  69. package/dist/types/interfaces/toolbar-control.interface.d.ts +2 -0
  70. package/package.json +1 -1
  71. package/dist/components/p-B4b6TDxp.js +0 -1
  72. package/dist/components/p-C2ocjA6D.js +0 -1
  73. package/dist/components/p-CwbZCXKh.js +0 -1
  74. package/dist/components/p-D2q_wTyG.js +0 -1
  75. package/dist/components/p-D8NvNMcU.js +0 -1
  76. package/dist/components/p-D8W6LE-c.js +0 -1
  77. package/dist/components/p-G9G9y5VE.js +0 -9
  78. package/dist/components/p-JhOYwUOj.js +0 -1
  79. package/dist/components/p-UEf2EN23.js +0 -1
  80. package/dist/stencil/p-2c489187.entry.js +0 -9
  81. package/dist/stencil/p-Cv5-yM39.js +0 -1
@@ -0,0 +1,9 @@
1
+ import{p as t,H as e,c as i,h as n,d as r,t as s}from"./p-B43upypT.js";import{a as o,d as h}from"./p-Cm33td2O.js";import{K as a,e as l,f as u,a as c,b as f,d}from"./p-Ka7OWbnk.js";import{c as p}from"./p-BFTU3MAI.js";import{a as g,D as m,K as w}from"./p-BmyTdQGy.js";import{K as v}from"./p-jGOpkGDl.js";import{K as y,r as b}from"./p-DJkKlUyZ.js";import{A as k,a as M,d as S}from"./p-PSFAfAyd.js";import{K as x,W as A}from"./p-DhMlShij.js";import{K as $}from"./p-WUdQqYnu.js";import{K as z,d as C}from"./p-BxpKq94F.js";import{O as T}from"./p-Dd-pMvlr.js";import*as E from"yjs";import{a as O,C as I}from"./p-CW-VyJgK.js";import{K as j,d as P}from"./p-CdR76C4L.js";import{d as R}from"./p-DgJ0ufzr.js";import{d as D}from"./p-894OnDQV.js";class _{static forceHideKeyboard(){document.activeElement instanceof HTMLElement&&document.activeElement.blur()}static enableInteractiveWidget(){const t=document.querySelector('meta[name="viewport"][content*="interactive-widget=resizes-content"]');if(t){let e=t.getAttribute("content");e?.includes("interactive-widget=resizes-content")||(e+=", interactive-widget=resizes-content"),e&&t.setAttribute("content",e)}}static disableInteractiveWidget(){const t=document.querySelector('meta[name="viewport"][content*="interactive-widget=resizes-content"]');if(t){let e=t.getAttribute("content"),i=e?.replace(/\s*interactive-widget=resizes-content\s*[,;]?/g,"");void 0!==i&&(i=i.replace(/,(\s*,)+/g,",").replace(/^,/,"").replace(/,$/,"").trim(),t.setAttribute("content",i))}}static onKeyboardVisibleChanged(t){if("visualViewport"in window){const e=.75,i=i=>{const n=i.target,r=v.isMobile(),s=n.height*n.scale/window.screen.height<e;t(r&&s)};return window.visualViewport?.addEventListener("resize",i),()=>window.visualViewport?.removeEventListener("resize",i)}return console.warn("Listening for keyboard visibility changes is not reliably supported in this browser."),()=>{}}}function L(t){this.content=t}function B(t,e,i){for(let n=0;;n++){if(n==t.childCount||n==e.childCount)return t.childCount==e.childCount?null:i;let r=t.child(n),s=e.child(n);if(r!=s){if(!r.sameMarkup(s))return i;if(r.isText&&r.text!=s.text){let t=r.text,e=s.text,n=0;for(;t[n]==e[n];n++)i++;return n&&n<t.length&&n<e.length&&W(t.charCodeAt(n-1))&&N(t.charCodeAt(n))&&i--,i}if(r.content.size||s.content.size){let t=B(r.content,s.content,i+1);if(null!=t)return t}i+=r.nodeSize}else i+=r.nodeSize}}function F(t,e,i,n){for(let r=t.childCount,s=e.childCount;;){if(0==r||0==s)return r==s?null:{a:i,b:n};let o=t.child(--r),h=e.child(--s),a=o.nodeSize;if(o!=h){if(!o.sameMarkup(h))return{a:i,b:n};if(o.isText&&o.text!=h.text){let t=o.text,e=h.text,r=t.length,s=e.length;for(;r>0&&s>0&&t[r-1]==e[s-1];)r--,s--,i--,n--;return r&&s&&r<t.length&&W(t.charCodeAt(r-1))&&N(t.charCodeAt(r))&&(i++,n++),{a:i,b:n}}if(o.content.size||h.content.size){let t=F(o.content,h.content,i-1,n-1);if(t)return t}i-=a,n-=a}else i-=a,n-=a}}function N(t){return t>=56320&&t<57344}function W(t){return t>=55296&&t<56320}L.prototype={constructor:L,find:function(t){for(var e=0;e<this.content.length;e+=2)if(this.content[e]===t)return e;return-1},get:function(t){var e=this.find(t);return-1==e?void 0:this.content[e+1]},update:function(t,e,i){var n=i&&i!=t?this.remove(i):this,r=n.find(t),s=n.content.slice();return-1==r?s.push(i||t,e):(s[r+1]=e,i&&(s[r]=i)),new L(s)},remove:function(t){var e=this.find(t);if(-1==e)return this;var i=this.content.slice();return i.splice(e,2),new L(i)},addToStart:function(t,e){return new L([t,e].concat(this.remove(t).content))},addToEnd:function(t,e){var i=this.remove(t).content.slice();return i.push(t,e),new L(i)},addBefore:function(t,e,i){var n=this.remove(e),r=n.content.slice(),s=n.find(t);return r.splice(-1==s?r.length:s,0,e,i),new L(r)},forEach:function(t){for(var e=0;e<this.content.length;e+=2)t(this.content[e],this.content[e+1])},prepend:function(t){return(t=L.from(t)).size?new L(t.content.concat(this.subtract(t).content)):this},append:function(t){return(t=L.from(t)).size?new L(this.subtract(t).content.concat(t.content)):this},subtract:function(t){var e=this;t=L.from(t);for(var i=0;i<t.content.length;i+=2)e=e.remove(t.content[i]);return e},toObject:function(){var t={};return this.forEach((function(e,i){t[e]=i})),t},get size(){return this.content.length>>1}},L.from=function(t){if(t instanceof L)return t;var e=[];if(t)for(var i in t)e.push(i,t[i]);return new L(e)};class U{constructor(t,e){if(this.content=t,this.size=e||0,null==e)for(let e=0;e<t.length;e++)this.size+=t[e].nodeSize}nodesBetween(t,e,i,n=0,r){for(let s=0,o=0;o<e;s++){let h=this.content[s],a=o+h.nodeSize;if(a>t&&!1!==i(h,n+o,r||null,s)&&h.content.size){let r=o+1;h.nodesBetween(Math.max(0,t-r),Math.min(h.content.size,e-r),i,n+r)}o=a}}descendants(t){this.nodesBetween(0,this.size,t)}textBetween(t,e,i,n){let r="",s=!0;return this.nodesBetween(t,e,((o,h)=>{let a=o.isText?o.text.slice(Math.max(t,h)-h,e-h):o.isLeaf?n?"function"==typeof n?n(o):n:o.type.spec.leafText?o.type.spec.leafText(o):"":"";o.isBlock&&(o.isLeaf&&a||o.isTextblock)&&i&&(s?s=!1:r+=i),r+=a}),0),r}append(t){if(!t.size)return this;if(!this.size)return t;let e=this.lastChild,i=t.firstChild,n=this.content.slice(),r=0;for(e.isText&&e.sameMarkup(i)&&(n[n.length-1]=e.withText(e.text+i.text),r=1);r<t.content.length;r++)n.push(t.content[r]);return new U(n,this.size+t.size)}cut(t,e=this.size){if(0==t&&e==this.size)return this;let i=[],n=0;if(e>t)for(let r=0,s=0;s<e;r++){let o=this.content[r],h=s+o.nodeSize;h>t&&((s<t||h>e)&&(o=o.isText?o.cut(Math.max(0,t-s),Math.min(o.text.length,e-s)):o.cut(Math.max(0,t-s-1),Math.min(o.content.size,e-s-1))),i.push(o),n+=o.nodeSize),s=h}return new U(i,n)}cutByIndex(t,e){return t==e?U.empty:0==t&&e==this.content.length?this:new U(this.content.slice(t,e))}replaceChild(t,e){let i=this.content[t];if(i==e)return this;let n=this.content.slice(),r=this.size+e.nodeSize-i.nodeSize;return n[t]=e,new U(n,r)}addToStart(t){return new U([t].concat(this.content),this.size+t.nodeSize)}addToEnd(t){return new U(this.content.concat(t),this.size+t.nodeSize)}eq(t){if(this.content.length!=t.content.length)return!1;for(let e=0;e<this.content.length;e++)if(!this.content[e].eq(t.content[e]))return!1;return!0}get firstChild(){return this.content.length?this.content[0]:null}get lastChild(){return this.content.length?this.content[this.content.length-1]:null}get childCount(){return this.content.length}child(t){let e=this.content[t];if(!e)throw new RangeError("Index "+t+" out of range for "+this);return e}maybeChild(t){return this.content[t]||null}forEach(t){for(let e=0,i=0;e<this.content.length;e++){let n=this.content[e];t(n,i,e),i+=n.nodeSize}}findDiffStart(t,e=0){return B(this,t,e)}findDiffEnd(t,e=this.size,i=t.size){return F(this,t,e,i)}findIndex(t){if(0==t)return H(0,t);if(t==this.size)return H(this.content.length,t);if(t>this.size||t<0)throw new RangeError(`Position ${t} outside of fragment (${this})`);for(let e=0,i=0;;e++){let n=i+this.child(e).nodeSize;if(n>=t)return n==t?H(e+1,n):H(e,i);i=n}}toString(){return"<"+this.toStringInner()+">"}toStringInner(){return this.content.join(", ")}toJSON(){return this.content.length?this.content.map((t=>t.toJSON())):null}static fromJSON(t,e){if(!e)return U.empty;if(!Array.isArray(e))throw new RangeError("Invalid input for Fragment.fromJSON");return U.fromArray(e.map(t.nodeFromJSON))}static fromArray(t){if(!t.length)return U.empty;let e,i=0;for(let n=0;n<t.length;n++){let r=t[n];i+=r.nodeSize,n&&r.isText&&t[n-1].sameMarkup(r)?(e||(e=t.slice(0,n)),e[e.length-1]=r.withText(e[e.length-1].text+r.text)):e&&e.push(r)}return new U(e||t,i)}static from(t){if(!t)return U.empty;if(t instanceof U)return t;if(Array.isArray(t))return this.fromArray(t);if(t.attrs)return new U([t],t.nodeSize);throw new RangeError("Can not convert "+t+" to a Fragment"+(t.nodesBetween?" (looks like multiple versions of prosemirror-model were loaded)":""))}}U.empty=new U([],0);const K={index:0,offset:0};function H(t,e){return K.index=t,K.offset=e,K}function V(t,e){if(t===e)return!0;if(!t||"object"!=typeof t||!e||"object"!=typeof e)return!1;let i=Array.isArray(t);if(Array.isArray(e)!=i)return!1;if(i){if(t.length!=e.length)return!1;for(let i=0;i<t.length;i++)if(!V(t[i],e[i]))return!1}else{for(let i in t)if(!(i in e)||!V(t[i],e[i]))return!1;for(let i in e)if(!(i in t))return!1}return!0}class G{constructor(t,e){this.type=t,this.attrs=e}addToSet(t){let e,i=!1;for(let n=0;n<t.length;n++){let r=t[n];if(this.eq(r))return t;if(this.type.excludes(r.type))e||(e=t.slice(0,n));else{if(r.type.excludes(this.type))return t;!i&&r.type.rank>this.type.rank&&(e||(e=t.slice(0,n)),e.push(this),i=!0),e&&e.push(r)}}return e||(e=t.slice()),i||e.push(this),e}removeFromSet(t){for(let e=0;e<t.length;e++)if(this.eq(t[e]))return t.slice(0,e).concat(t.slice(e+1));return t}isInSet(t){for(let e=0;e<t.length;e++)if(this.eq(t[e]))return!0;return!1}eq(t){return this==t||this.type==t.type&&V(this.attrs,t.attrs)}toJSON(){let t={type:this.type.name};for(let e in this.attrs){t.attrs=this.attrs;break}return t}static fromJSON(t,e){if(!e)throw new RangeError("Invalid input for Mark.fromJSON");let i=t.marks[e.type];if(!i)throw new RangeError(`There is no mark type ${e.type} in this schema`);let n=i.create(e.attrs);return i.checkAttrs(n.attrs),n}static sameSet(t,e){if(t==e)return!0;if(t.length!=e.length)return!1;for(let i=0;i<t.length;i++)if(!t[i].eq(e[i]))return!1;return!0}static setFrom(t){if(!t||Array.isArray(t)&&0==t.length)return G.none;if(t instanceof G)return[t];let e=t.slice();return e.sort(((t,e)=>t.type.rank-e.type.rank)),e}}G.none=[];class X extends Error{}class Y{constructor(t,e,i){this.content=t,this.openStart=e,this.openEnd=i}get size(){return this.content.size-this.openStart-this.openEnd}insertAt(t,e){let i=J(this.content,t+this.openStart,e,this.openStart+1,this.openEnd+1);return i&&new Y(i,this.openStart,this.openEnd)}removeBetween(t,e){return new Y(q(this.content,t+this.openStart,e+this.openStart),this.openStart,this.openEnd)}eq(t){return this.content.eq(t.content)&&this.openStart==t.openStart&&this.openEnd==t.openEnd}toString(){return this.content+"("+this.openStart+","+this.openEnd+")"}toJSON(){if(!this.content.size)return null;let t={content:this.content.toJSON()};return this.openStart>0&&(t.openStart=this.openStart),this.openEnd>0&&(t.openEnd=this.openEnd),t}static fromJSON(t,e){if(!e)return Y.empty;let i=e.openStart||0,n=e.openEnd||0;if("number"!=typeof i||"number"!=typeof n)throw new RangeError("Invalid input for Slice.fromJSON");return new Y(U.fromJSON(t,e.content),i,n)}static maxOpen(t,e=!0){let i=0,n=0;for(let n=t.firstChild;n&&!n.isLeaf&&(e||!n.type.spec.isolating);n=n.firstChild)i++;for(let i=t.lastChild;i&&!i.isLeaf&&(e||!i.type.spec.isolating);i=i.lastChild)n++;return new Y(t,i,n)}}function q(t,e,i){let{index:n,offset:r}=t.findIndex(e),s=t.maybeChild(n),{index:o,offset:h}=t.findIndex(i);if(r==e||s.isText){if(h!=i&&!t.child(o).isText)throw new RangeError("Removing non-flat range");return t.cut(0,e).append(t.cut(i))}if(n!=o)throw new RangeError("Removing non-flat range");return t.replaceChild(n,s.copy(q(s.content,e-r-1,i-r-1)))}function J(t,e,i,n,r,s){let{index:o,offset:h}=t.findIndex(e),a=t.maybeChild(o);if(h==e||a.isText)return s&&n<=0&&r<=0&&!s.canReplace(o,o,i)?null:t.cut(0,e).append(i).append(t.cut(e));let l=J(a.content,e-h-1,i,0==o?n-1:0,o==t.childCount-1?r-1:0,a);return l&&t.replaceChild(o,a.copy(l))}function Q(t,e,i){if(i.openStart>t.depth)throw new X("Inserted content deeper than insertion position");if(t.depth-i.openStart!=e.depth-i.openEnd)throw new X("Inconsistent open depths");return Z(t,e,i,0)}function Z(t,e,i,n){let r=t.index(n),s=t.node(n);if(r==e.index(n)&&n<t.depth-i.openStart){let o=Z(t,e,i,n+1);return s.copy(s.content.replaceChild(r,o))}if(i.content.size){if(i.openStart||i.openEnd||t.depth!=n||e.depth!=n){let{start:r,end:o}=function(t,e){let i=e.depth-t.openStart,n=e.node(i).copy(t.content);for(let t=i-1;t>=0;t--)n=e.node(t).copy(U.from(n));return{start:n.resolveNoCache(t.openStart+i),end:n.resolveNoCache(n.content.size-t.openEnd-i)}}(i,t);return rt(s,st(t,r,o,e,n))}{let n=t.parent,r=n.content;return rt(n,r.cut(0,t.parentOffset).append(i.content).append(r.cut(e.parentOffset)))}}return rt(s,ot(t,e,n))}function tt(t,e){if(!e.type.compatibleContent(t.type))throw new X("Cannot join "+e.type.name+" onto "+t.type.name)}function et(t,e,i){let n=t.node(i);return tt(n,e.node(i)),n}function it(t,e){let i=e.length-1;i>=0&&t.isText&&t.sameMarkup(e[i])?e[i]=t.withText(e[i].text+t.text):e.push(t)}function nt(t,e,i,n){let r=(e||t).node(i),s=0,o=e?e.index(i):r.childCount;t&&(s=t.index(i),t.depth>i?s++:t.textOffset&&(it(t.nodeAfter,n),s++));for(let t=s;t<o;t++)it(r.child(t),n);e&&e.depth==i&&e.textOffset&&it(e.nodeBefore,n)}function rt(t,e){if(!t.type.validContent(e))throw new X("Invalid content for node "+t.type.name);return t.copy(e)}function st(t,e,i,n,r){let s=t.depth>r&&et(t,e,r+1),o=n.depth>r&&et(i,n,r+1),h=[];return nt(null,t,r,h),s&&o&&e.index(r)==i.index(r)?(tt(s,o),it(rt(s,st(t,e,i,n,r+1)),h)):(s&&it(rt(s,ot(t,e,r+1)),h),nt(e,i,r,h),o&&it(rt(o,ot(i,n,r+1)),h)),nt(n,null,r,h),new U(h)}function ot(t,e,i){let n=[];return nt(null,t,i,n),t.depth>i&&it(rt(et(t,e,i+1),ot(t,e,i+1)),n),nt(e,null,i,n),new U(n)}Y.empty=new Y(U.empty,0,0);class ht{constructor(t,e,i){this.pos=t,this.path=e,this.parentOffset=i,this.depth=e.length/3-1}resolveDepth(t){return null==t?this.depth:t<0?this.depth+t:t}get parent(){return this.node(this.depth)}get doc(){return this.node(0)}node(t){return this.path[3*this.resolveDepth(t)]}index(t){return this.path[3*this.resolveDepth(t)+1]}indexAfter(t){return t=this.resolveDepth(t),this.index(t)+(t!=this.depth||this.textOffset?1:0)}start(t){return 0==(t=this.resolveDepth(t))?0:this.path[3*t-1]+1}end(t){return t=this.resolveDepth(t),this.start(t)+this.node(t).content.size}before(t){if(!(t=this.resolveDepth(t)))throw new RangeError("There is no position before the top-level node");return t==this.depth+1?this.pos:this.path[3*t-1]}after(t){if(!(t=this.resolveDepth(t)))throw new RangeError("There is no position after the top-level node");return t==this.depth+1?this.pos:this.path[3*t-1]+this.path[3*t].nodeSize}get textOffset(){return this.pos-this.path[this.path.length-1]}get nodeAfter(){let t=this.parent,e=this.index(this.depth);if(e==t.childCount)return null;let i=this.pos-this.path[this.path.length-1],n=t.child(e);return i?t.child(e).cut(i):n}get nodeBefore(){let t=this.index(this.depth),e=this.pos-this.path[this.path.length-1];return e?this.parent.child(t).cut(0,e):0==t?null:this.parent.child(t-1)}posAtIndex(t,e){e=this.resolveDepth(e);let i=this.path[3*e],n=0==e?0:this.path[3*e-1]+1;for(let e=0;e<t;e++)n+=i.child(e).nodeSize;return n}marks(){let t=this.parent,e=this.index();if(0==t.content.size)return G.none;if(this.textOffset)return t.child(e).marks;let i=t.maybeChild(e-1),n=t.maybeChild(e);if(!i){let t=i;i=n,n=t}let r=i.marks;for(var s=0;s<r.length;s++)!1!==r[s].type.spec.inclusive||n&&r[s].isInSet(n.marks)||(r=r[s--].removeFromSet(r));return r}marksAcross(t){let e=this.parent.maybeChild(this.index());if(!e||!e.isInline)return null;let i=e.marks,n=t.parent.maybeChild(t.index());for(var r=0;r<i.length;r++)!1!==i[r].type.spec.inclusive||n&&i[r].isInSet(n.marks)||(i=i[r--].removeFromSet(i));return i}sharedDepth(t){for(let e=this.depth;e>0;e--)if(this.start(e)<=t&&this.end(e)>=t)return e;return 0}blockRange(t=this,e){if(t.pos<this.pos)return t.blockRange(this);for(let i=this.depth-(this.parent.inlineContent||this.pos==t.pos?1:0);i>=0;i--)if(t.pos<=this.end(i)&&(!e||e(this.node(i))))return new ct(this,t,i);return null}sameParent(t){return this.pos-this.parentOffset==t.pos-t.parentOffset}max(t){return t.pos>this.pos?t:this}min(t){return t.pos<this.pos?t:this}toString(){let t="";for(let e=1;e<=this.depth;e++)t+=(t?"/":"")+this.node(e).type.name+"_"+this.index(e-1);return t+":"+this.parentOffset}static resolve(t,e){if(!(e>=0&&e<=t.content.size))throw new RangeError("Position "+e+" out of range");let i=[],n=0,r=e;for(let e=t;;){let{index:t,offset:s}=e.content.findIndex(r),o=r-s;if(i.push(e,t,n+s),!o)break;if(e=e.child(t),e.isText)break;r=o-1,n+=s+1}return new ht(e,i,r)}static resolveCached(t,e){let i=ut.get(t);if(i)for(let t=0;t<i.elts.length;t++){let n=i.elts[t];if(n.pos==e)return n}else ut.set(t,i=new at);let n=i.elts[i.i]=ht.resolve(t,e);return i.i=(i.i+1)%lt,n}}class at{constructor(){this.elts=[],this.i=0}}const lt=12,ut=new WeakMap;class ct{constructor(t,e,i){this.$from=t,this.$to=e,this.depth=i}get start(){return this.$from.before(this.depth+1)}get end(){return this.$to.after(this.depth+1)}get parent(){return this.$from.node(this.depth)}get startIndex(){return this.$from.index(this.depth)}get endIndex(){return this.$to.indexAfter(this.depth)}}const ft=Object.create(null);class dt{constructor(t,e,i,n=G.none){this.type=t,this.attrs=e,this.marks=n,this.content=i||U.empty}get children(){return this.content.content}get nodeSize(){return this.isLeaf?1:2+this.content.size}get childCount(){return this.content.childCount}child(t){return this.content.child(t)}maybeChild(t){return this.content.maybeChild(t)}forEach(t){this.content.forEach(t)}nodesBetween(t,e,i,n=0){this.content.nodesBetween(t,e,i,n,this)}descendants(t){this.nodesBetween(0,this.content.size,t)}get textContent(){return this.isLeaf&&this.type.spec.leafText?this.type.spec.leafText(this):this.textBetween(0,this.content.size,"")}textBetween(t,e,i,n){return this.content.textBetween(t,e,i,n)}get firstChild(){return this.content.firstChild}get lastChild(){return this.content.lastChild}eq(t){return this==t||this.sameMarkup(t)&&this.content.eq(t.content)}sameMarkup(t){return this.hasMarkup(t.type,t.attrs,t.marks)}hasMarkup(t,e,i){return this.type==t&&V(this.attrs,e||t.defaultAttrs||ft)&&G.sameSet(this.marks,i||G.none)}copy(t=null){return t==this.content?this:new dt(this.type,this.attrs,t,this.marks)}mark(t){return t==this.marks?this:new dt(this.type,this.attrs,this.content,t)}cut(t,e=this.content.size){return 0==t&&e==this.content.size?this:this.copy(this.content.cut(t,e))}slice(t,e=this.content.size,i=!1){if(t==e)return Y.empty;let n=this.resolve(t),r=this.resolve(e),s=i?0:n.sharedDepth(e),o=n.start(s),h=n.node(s).content.cut(n.pos-o,r.pos-o);return new Y(h,n.depth-s,r.depth-s)}replace(t,e,i){return Q(this.resolve(t),this.resolve(e),i)}nodeAt(t){for(let e=this;;){let{index:i,offset:n}=e.content.findIndex(t);if(e=e.maybeChild(i),!e)return null;if(n==t||e.isText)return e;t-=n+1}}childAfter(t){let{index:e,offset:i}=this.content.findIndex(t);return{node:this.content.maybeChild(e),index:e,offset:i}}childBefore(t){if(0==t)return{node:null,index:0,offset:0};let{index:e,offset:i}=this.content.findIndex(t);if(i<t)return{node:this.content.child(e),index:e,offset:i};let n=this.content.child(e-1);return{node:n,index:e-1,offset:i-n.nodeSize}}resolve(t){return ht.resolveCached(this,t)}resolveNoCache(t){return ht.resolve(this,t)}rangeHasMark(t,e,i){let n=!1;return e>t&&this.nodesBetween(t,e,(t=>(i.isInSet(t.marks)&&(n=!0),!n))),n}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 t=this.type.name;return this.content.size&&(t+="("+this.content.toStringInner()+")"),gt(this.marks,t)}contentMatchAt(t){let e=this.type.contentMatch.matchFragment(this.content,0,t);if(!e)throw new Error("Called contentMatchAt on a node with invalid content");return e}canReplace(t,e,i=U.empty,n=0,r=i.childCount){let s=this.contentMatchAt(t).matchFragment(i,n,r),o=s&&s.matchFragment(this.content,e);if(!o||!o.validEnd)return!1;for(let t=n;t<r;t++)if(!this.type.allowsMarks(i.child(t).marks))return!1;return!0}canReplaceWith(t,e,i,n){if(n&&!this.type.allowsMarks(n))return!1;let r=this.contentMatchAt(t).matchType(i),s=r&&r.matchFragment(this.content,e);return!!s&&s.validEnd}canAppend(t){return t.content.size?this.canReplace(this.childCount,this.childCount,t.content):this.type.compatibleContent(t.type)}check(){this.type.checkContent(this.content),this.type.checkAttrs(this.attrs);let t=G.none;for(let e=0;e<this.marks.length;e++){let i=this.marks[e];i.type.checkAttrs(i.attrs),t=i.addToSet(t)}if(!G.sameSet(t,this.marks))throw new RangeError(`Invalid collection of marks for node ${this.type.name}: ${this.marks.map((t=>t.type.name))}`);this.content.forEach((t=>t.check()))}toJSON(){let t={type:this.type.name};for(let e in this.attrs){t.attrs=this.attrs;break}return this.content.size&&(t.content=this.content.toJSON()),this.marks.length&&(t.marks=this.marks.map((t=>t.toJSON()))),t}static fromJSON(t,e){if(!e)throw new RangeError("Invalid input for Node.fromJSON");let i;if(e.marks){if(!Array.isArray(e.marks))throw new RangeError("Invalid mark data for Node.fromJSON");i=e.marks.map(t.markFromJSON)}if("text"==e.type){if("string"!=typeof e.text)throw new RangeError("Invalid text node in JSON");return t.text(e.text,i)}let n=U.fromJSON(t,e.content),r=t.nodeType(e.type).create(e.attrs,n,i);return r.type.checkAttrs(r.attrs),r}}dt.prototype.text=void 0;class pt extends dt{constructor(t,e,i,n){if(super(t,e,null,n),!i)throw new RangeError("Empty text nodes are not allowed");this.text=i}toString(){return this.type.spec.toDebugString?this.type.spec.toDebugString(this):gt(this.marks,JSON.stringify(this.text))}get textContent(){return this.text}textBetween(t,e){return this.text.slice(t,e)}get nodeSize(){return this.text.length}mark(t){return t==this.marks?this:new pt(this.type,this.attrs,this.text,t)}withText(t){return t==this.text?this:new pt(this.type,this.attrs,t,this.marks)}cut(t=0,e=this.text.length){return 0==t&&e==this.text.length?this:this.withText(this.text.slice(t,e))}eq(t){return this.sameMarkup(t)&&this.text==t.text}toJSON(){let t=super.toJSON();return t.text=this.text,t}}function gt(t,e){for(let i=t.length-1;i>=0;i--)e=t[i].type.name+"("+e+")";return e}class mt{constructor(t){this.validEnd=t,this.next=[],this.wrapCache=[]}static parse(t,e){let i=new wt(t,e);if(null==i.next)return mt.empty;let n=vt(i);i.next&&i.err("Unexpected trailing text");let r=function(t){let e=Object.create(null);return function i(n){let r=[];n.forEach((e=>{t[e].forEach((({term:e,to:i})=>{if(!e)return;let n;for(let t=0;t<r.length;t++)r[t][0]==e&&(n=r[t][1]);xt(t,i).forEach((t=>{n||r.push([e,n=[]]),-1==n.indexOf(t)&&n.push(t)}))}))}));let s=e[n.join(",")]=new mt(n.indexOf(t.length-1)>-1);for(let t=0;t<r.length;t++){let n=r[t][1].sort(St);s.next.push({type:r[t][0],next:e[n.join(",")]||i(n)})}return s}(xt(t,0))}(function(t){let e=[[]];return r(function t(e,s){if("choice"==e.type)return e.exprs.reduce(((e,i)=>e.concat(t(i,s))),[]);if("seq"!=e.type){if("star"==e.type){let o=i();return n(s,o),r(t(e.expr,o),o),[n(o)]}if("plus"==e.type){let o=i();return r(t(e.expr,s),o),r(t(e.expr,o),o),[n(o)]}if("opt"==e.type)return[n(s)].concat(t(e.expr,s));if("range"==e.type){let o=s;for(let n=0;n<e.min;n++){let n=i();r(t(e.expr,o),n),o=n}if(-1==e.max)r(t(e.expr,o),o);else for(let s=e.min;s<e.max;s++){let s=i();n(o,s),r(t(e.expr,o),s),o=s}return[n(o)]}if("name"==e.type)return[n(s,void 0,e.value)];throw new Error("Unknown expr type")}for(let n=0;;n++){let o=t(e.exprs[n],s);if(n==e.exprs.length-1)return o;r(o,s=i())}}(t,0),i()),e;function i(){return e.push([])-1}function n(t,i,n){let r={term:n,to:i};return e[t].push(r),r}function r(t,e){t.forEach((t=>t.to=e))}}(n));return function(t,e){for(let i=0,n=[t];i<n.length;i++){let t=n[i],r=!t.validEnd,s=[];for(let e=0;e<t.next.length;e++){let{type:i,next:o}=t.next[e];s.push(i.name),!r||i.isText||i.hasRequiredAttrs()||(r=!1),-1==n.indexOf(o)&&n.push(o)}r&&e.err("Only non-generatable nodes ("+s.join(", ")+") in a required position (see https://prosemirror.net/docs/guide/#generatable)")}}(r,i),r}matchType(t){for(let e=0;e<this.next.length;e++)if(this.next[e].type==t)return this.next[e].next;return null}matchFragment(t,e=0,i=t.childCount){let n=this;for(let r=e;n&&r<i;r++)n=n.matchType(t.child(r).type);return n}get inlineContent(){return 0!=this.next.length&&this.next[0].type.isInline}get defaultType(){for(let t=0;t<this.next.length;t++){let{type:e}=this.next[t];if(!e.isText&&!e.hasRequiredAttrs())return e}return null}compatible(t){for(let e=0;e<this.next.length;e++)for(let i=0;i<t.next.length;i++)if(this.next[e].type==t.next[i].type)return!0;return!1}fillBefore(t,e=!1,i=0){let n=[this];return function r(s,o){let h=s.matchFragment(t,i);if(h&&(!e||h.validEnd))return U.from(o.map((t=>t.createAndFill())));for(let t=0;t<s.next.length;t++){let{type:e,next:i}=s.next[t];if(!e.isText&&!e.hasRequiredAttrs()&&-1==n.indexOf(i)){n.push(i);let t=r(i,o.concat(e));if(t)return t}}return null}(this,[])}findWrapping(t){for(let e=0;e<this.wrapCache.length;e+=2)if(this.wrapCache[e]==t)return this.wrapCache[e+1];let e=this.computeWrapping(t);return this.wrapCache.push(t,e),e}computeWrapping(t){let e=Object.create(null),i=[{match:this,type:null,via:null}];for(;i.length;){let n=i.shift(),r=n.match;if(r.matchType(t)){let t=[];for(let e=n;e.type;e=e.via)t.push(e.type);return t.reverse()}for(let t=0;t<r.next.length;t++){let{type:s,next:o}=r.next[t];s.isLeaf||s.hasRequiredAttrs()||s.name in e||n.type&&!o.validEnd||(i.push({match:s.contentMatch,type:s,via:n}),e[s.name]=!0)}}return null}get edgeCount(){return this.next.length}edge(t){if(t>=this.next.length)throw new RangeError(`There's no ${t}th edge in this content match`);return this.next[t]}toString(){let t=[];return function e(i){t.push(i);for(let n=0;n<i.next.length;n++)-1==t.indexOf(i.next[n].next)&&e(i.next[n].next)}(this),t.map(((e,i)=>{let n=i+(e.validEnd?"*":" ")+" ";for(let i=0;i<e.next.length;i++)n+=(i?", ":"")+e.next[i].type.name+"->"+t.indexOf(e.next[i].next);return n})).join("\n")}}mt.empty=new mt(!0);class wt{constructor(t,e){this.string=t,this.nodeTypes=e,this.inline=null,this.pos=0,this.tokens=t.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(t){return this.next==t&&(this.pos++||!0)}err(t){throw new SyntaxError(t+" (in content expression '"+this.string+"')")}}function vt(t){let e=[];do{e.push(yt(t))}while(t.eat("|"));return 1==e.length?e[0]:{type:"choice",exprs:e}}function yt(t){let e=[];do{e.push(bt(t))}while(t.next&&")"!=t.next&&"|"!=t.next);return 1==e.length?e[0]:{type:"seq",exprs:e}}function bt(t){let e=function(t){if(t.eat("(")){let e=vt(t);return t.eat(")")||t.err("Missing closing paren"),e}if(!/\W/.test(t.next)){let e=function(t,e){let i=t.nodeTypes,n=i[e];if(n)return[n];let r=[];for(let t in i){let n=i[t];n.isInGroup(e)&&r.push(n)}return 0==r.length&&t.err("No node type or group '"+e+"' found"),r}(t,t.next).map((e=>(null==t.inline?t.inline=e.isInline:t.inline!=e.isInline&&t.err("Mixing inline and block content"),{type:"name",value:e})));return t.pos++,1==e.length?e[0]:{type:"choice",exprs:e}}t.err("Unexpected token '"+t.next+"'")}(t);for(;;)if(t.eat("+"))e={type:"plus",expr:e};else if(t.eat("*"))e={type:"star",expr:e};else if(t.eat("?"))e={type:"opt",expr:e};else{if(!t.eat("{"))break;e=Mt(t,e)}return e}function kt(t){/\D/.test(t.next)&&t.err("Expected number, got '"+t.next+"'");let e=Number(t.next);return t.pos++,e}function Mt(t,e){let i=kt(t),n=i;return t.eat(",")&&(n="}"!=t.next?kt(t):-1),t.eat("}")||t.err("Unclosed braced range"),{type:"range",min:i,max:n,expr:e}}function St(t,e){return e-t}function xt(t,e){let i=[];return function e(n){let r=t[n];if(1==r.length&&!r[0].term)return e(r[0].to);i.push(n);for(let t=0;t<r.length;t++){let{term:n,to:s}=r[t];n||-1!=i.indexOf(s)||e(s)}}(e),i.sort(St)}function At(t){let e=Object.create(null);for(let i in t){let n=t[i];if(!n.hasDefault)return null;e[i]=n.default}return e}function $t(t,e){let i=Object.create(null);for(let n in t){let r=e&&e[n];if(void 0===r){let e=t[n];if(!e.hasDefault)throw new RangeError("No value supplied for attribute "+n);r=e.default}i[n]=r}return i}function zt(t,e,i,n){for(let r in e)if(!(r in t))throw new RangeError(`Unsupported attribute ${r} for ${i} of type ${n}`);for(let i in t)t[i].validate&&t[i].validate(e[i])}function Ct(t,e){let i=Object.create(null);if(e)for(let n in e)i[n]=new Et(t,n,e[n]);return i}let Tt=class t{constructor(t,e,i){this.name=t,this.schema=e,this.spec=i,this.markSet=null,this.groups=i.group?i.group.split(" "):[],this.attrs=Ct(t,i.attrs),this.defaultAttrs=At(this.attrs),this.contentMatch=null,this.inlineContent=null,this.isBlock=!(i.inline||"text"==t),this.isText="text"==t}get isInline(){return!this.isBlock}get isTextblock(){return this.isBlock&&this.inlineContent}get isLeaf(){return this.contentMatch==mt.empty}get isAtom(){return this.isLeaf||!!this.spec.atom}isInGroup(t){return this.groups.indexOf(t)>-1}get whitespace(){return this.spec.whitespace||(this.spec.code?"pre":"normal")}hasRequiredAttrs(){for(let t in this.attrs)if(this.attrs[t].isRequired)return!0;return!1}compatibleContent(t){return this==t||this.contentMatch.compatible(t.contentMatch)}computeAttrs(t){return!t&&this.defaultAttrs?this.defaultAttrs:$t(this.attrs,t)}create(t=null,e,i){if(this.isText)throw new Error("NodeType.create can't construct text nodes");return new dt(this,this.computeAttrs(t),U.from(e),G.setFrom(i))}createChecked(t=null,e,i){return e=U.from(e),this.checkContent(e),new dt(this,this.computeAttrs(t),e,G.setFrom(i))}createAndFill(t=null,e,i){if(t=this.computeAttrs(t),(e=U.from(e)).size){let t=this.contentMatch.fillBefore(e);if(!t)return null;e=t.append(e)}let n=this.contentMatch.matchFragment(e),r=n&&n.fillBefore(U.empty,!0);return r?new dt(this,t,e.append(r),G.setFrom(i)):null}validContent(t){let e=this.contentMatch.matchFragment(t);if(!e||!e.validEnd)return!1;for(let e=0;e<t.childCount;e++)if(!this.allowsMarks(t.child(e).marks))return!1;return!0}checkContent(t){if(!this.validContent(t))throw new RangeError(`Invalid content for node ${this.name}: ${t.toString().slice(0,50)}`)}checkAttrs(t){zt(this.attrs,t,"node",this.name)}allowsMarkType(t){return null==this.markSet||this.markSet.indexOf(t)>-1}allowsMarks(t){if(null==this.markSet)return!0;for(let e=0;e<t.length;e++)if(!this.allowsMarkType(t[e].type))return!1;return!0}allowedMarks(t){if(null==this.markSet)return t;let e;for(let i=0;i<t.length;i++)this.allowsMarkType(t[i].type)?e&&e.push(t[i]):e||(e=t.slice(0,i));return e?e.length?e:G.none:t}static compile(e,i){let n=Object.create(null);e.forEach(((e,r)=>n[e]=new t(e,i,r)));let r=i.spec.topNode||"doc";if(!n[r])throw new RangeError("Schema is missing its top node type ('"+r+"')");if(!n.text)throw new RangeError("Every schema needs a 'text' type");for(let t in n.text.attrs)throw new RangeError("The text node type should not have attributes");return n}};class Et{constructor(t,e,i){this.hasDefault=Object.prototype.hasOwnProperty.call(i,"default"),this.default=i.default,this.validate="string"==typeof i.validate?function(t,e,i){let n=i.split("|");return i=>{let r=null===i?"null":typeof i;if(n.indexOf(r)<0)throw new RangeError(`Expected value of type ${n} for attribute ${e} on type ${t}, got ${r}`)}}(t,e,i.validate):i.validate}get isRequired(){return!this.hasDefault}}class Ot{constructor(t,e,i,n){this.name=t,this.rank=e,this.schema=i,this.spec=n,this.attrs=Ct(t,n.attrs),this.excluded=null;let r=At(this.attrs);this.instance=r?new G(this,r):null}create(t=null){return!t&&this.instance?this.instance:new G(this,$t(this.attrs,t))}static compile(t,e){let i=Object.create(null),n=0;return t.forEach(((t,r)=>i[t]=new Ot(t,n++,e,r))),i}removeFromSet(t){for(var e=0;e<t.length;e++)t[e].type==this&&(t=t.slice(0,e).concat(t.slice(e+1)),e--);return t}isInSet(t){for(let e=0;e<t.length;e++)if(t[e].type==this)return t[e]}checkAttrs(t){zt(this.attrs,t,"mark",this.name)}excludes(t){return this.excluded.indexOf(t)>-1}}class It{constructor(t){this.linebreakReplacement=null,this.cached=Object.create(null);let e=this.spec={};for(let i in t)e[i]=t[i];e.nodes=L.from(t.nodes),e.marks=L.from(t.marks||{}),this.nodes=Tt.compile(this.spec.nodes,this),this.marks=Ot.compile(this.spec.marks,this);let i=Object.create(null);for(let t in this.nodes){if(t in this.marks)throw new RangeError(t+" can not be both a node and a mark");let e=this.nodes[t],n=e.spec.content||"",r=e.spec.marks;if(e.contentMatch=i[n]||(i[n]=mt.parse(n,this.nodes)),e.inlineContent=e.contentMatch.inlineContent,e.spec.linebreakReplacement){if(this.linebreakReplacement)throw new RangeError("Multiple linebreak nodes defined");if(!e.isInline||!e.isLeaf)throw new RangeError("Linebreak replacement nodes must be inline leaf nodes");this.linebreakReplacement=e}e.markSet="_"==r?null:r?jt(this,r.split(" ")):""!=r&&e.inlineContent?null:[]}for(let t in this.marks){let e=this.marks[t],i=e.spec.excludes;e.excluded=null==i?[e]:""==i?[]:jt(this,i.split(" "))}this.nodeFromJSON=t=>dt.fromJSON(this,t),this.markFromJSON=t=>G.fromJSON(this,t),this.topNodeType=this.nodes[this.spec.topNode||"doc"],this.cached.wrappings=Object.create(null)}node(t,e=null,i,n){if("string"==typeof t)t=this.nodeType(t);else{if(!(t instanceof Tt))throw new RangeError("Invalid node type: "+t);if(t.schema!=this)throw new RangeError("Node type from different schema used ("+t.name+")")}return t.createChecked(e,i,n)}text(t,e){let i=this.nodes.text;return new pt(i,i.defaultAttrs,t,G.setFrom(e))}mark(t,e){return"string"==typeof t&&(t=this.marks[t]),t.create(e)}nodeType(t){let e=this.nodes[t];if(!e)throw new RangeError("Unknown node type: "+t);return e}}function jt(t,e){let i=[];for(let n=0;n<e.length;n++){let r=e[n],s=t.marks[r],o=s;if(s)i.push(s);else for(let e in t.marks){let n=t.marks[e];("_"==r||n.spec.group&&n.spec.group.split(" ").indexOf(r)>-1)&&i.push(o=n)}if(!o)throw new SyntaxError("Unknown mark type: '"+e[n]+"'")}return i}class Pt{constructor(t,e){this.schema=t,this.rules=e,this.tags=[],this.styles=[];let i=this.matchedStyles=[];e.forEach((t=>{if(function(t){return null!=t.tag}(t))this.tags.push(t);else if(function(t){return null!=t.style}(t)){let e=/[^=]*/.exec(t.style)[0];i.indexOf(e)<0&&i.push(e),this.styles.push(t)}})),this.normalizeLists=!this.tags.some((e=>{if(!/^(ul|ol)\b/.test(e.tag)||!e.node)return!1;let i=t.nodes[e.node];return i.contentMatch.matchType(i)}))}parse(t,e={}){let i=new Ft(this,e,!1);return i.addAll(t,G.none,e.from,e.to),i.finish()}parseSlice(t,e={}){let i=new Ft(this,e,!0);return i.addAll(t,G.none,e.from,e.to),Y.maxOpen(i.finish())}matchTag(t,e,i){for(let n=i?this.tags.indexOf(i)+1:0;n<this.tags.length;n++){let i=this.tags[n];if(Nt(t,i.tag)&&(void 0===i.namespace||t.namespaceURI==i.namespace)&&(!i.context||e.matchesContext(i.context))){if(i.getAttrs){let e=i.getAttrs(t);if(!1===e)continue;i.attrs=e||void 0}return i}}}matchStyle(t,e,i,n){for(let r=n?this.styles.indexOf(n)+1:0;r<this.styles.length;r++){let n=this.styles[r],s=n.style;if(!(0!=s.indexOf(t)||n.context&&!i.matchesContext(n.context)||s.length>t.length&&(61!=s.charCodeAt(t.length)||s.slice(t.length+1)!=e))){if(n.getAttrs){let t=n.getAttrs(e);if(!1===t)continue;n.attrs=t||void 0}return n}}}static schemaRules(t){let e=[];function i(t){let i=null==t.priority?50:t.priority,n=0;for(;n<e.length;n++){let t=e[n];if((null==t.priority?50:t.priority)<i)break}e.splice(n,0,t)}for(let e in t.marks){let n=t.marks[e].spec.parseDOM;n&&n.forEach((t=>{i(t=Wt(t)),t.mark||t.ignore||t.clearMark||(t.mark=e)}))}for(let e in t.nodes){let n=t.nodes[e].spec.parseDOM;n&&n.forEach((t=>{i(t=Wt(t)),t.node||t.ignore||t.mark||(t.node=e)}))}return e}static fromSchema(t){return t.cached.domParser||(t.cached.domParser=new Pt(t,Pt.schemaRules(t)))}}const Rt={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},Dt={head:!0,noscript:!0,object:!0,script:!0,style:!0,title:!0},_t={ol:!0,ul:!0};function Lt(t,e,i){return null!=e?(e?1:0)|("full"===e?2:0):t&&"pre"==t.whitespace?3:-5&i}class Bt{constructor(t,e,i,n,r,s){this.type=t,this.attrs=e,this.marks=i,this.solid=n,this.options=s,this.content=[],this.activeMarks=G.none,this.match=r||(4&s?null:t.contentMatch)}findWrapping(t){if(!this.match){if(!this.type)return[];let e=this.type.contentMatch.fillBefore(U.from(t));if(!e){let e,i=this.type.contentMatch;return(e=i.findWrapping(t.type))?(this.match=i,e):null}this.match=this.type.contentMatch.matchFragment(e)}return this.match.findWrapping(t.type)}finish(t){if(!(1&this.options)){let t,e=this.content[this.content.length-1];if(e&&e.isText&&(t=/[ \t\r\n\u000c]+$/.exec(e.text))){let i=e;e.text.length==t[0].length?this.content.pop():this.content[this.content.length-1]=i.withText(i.text.slice(0,i.text.length-t[0].length))}}let e=U.from(this.content);return!t&&this.match&&(e=e.append(this.match.fillBefore(U.empty,!0))),this.type?this.type.create(this.attrs,e,this.marks):e}inlineContext(t){return this.type?this.type.inlineContent:this.content.length?this.content[0].isInline:t.parentNode&&!Rt.hasOwnProperty(t.parentNode.nodeName.toLowerCase())}}class Ft{constructor(t,e,i){this.parser=t,this.options=e,this.isOpen=i,this.open=0,this.localPreserveWS=!1;let n,r=e.topNode,s=Lt(null,e.preserveWhitespace,0)|(i?4:0);n=r?new Bt(r.type,r.attrs,G.none,!0,e.topMatch||r.type.contentMatch,s):new Bt(i?null:t.schema.topNodeType,null,G.none,!0,null,s),this.nodes=[n],this.find=e.findPositions,this.needsBlock=!1}get top(){return this.nodes[this.open]}addDOM(t,e){3==t.nodeType?this.addTextNode(t,e):1==t.nodeType&&this.addElement(t,e)}addTextNode(t,e){let i=t.nodeValue,n=this.top,r=2&n.options?"full":this.localPreserveWS||(1&n.options)>0,{schema:s}=this.parser;if("full"===r||n.inlineContext(t)||/[^ \t\r\n\u000c]/.test(i)){if(r)if("full"===r)i=i.replace(/\r\n?/g,"\n");else if(s.linebreakReplacement&&/[\r\n]/.test(i)&&this.top.findWrapping(s.linebreakReplacement.create())){let t=i.split(/\r?\n|\r/);for(let i=0;i<t.length;i++)i&&this.insertNode(s.linebreakReplacement.create(),e,!0),t[i]&&this.insertNode(s.text(t[i]),e,!/\S/.test(t[i]));i=""}else i=i.replace(/\r?\n|\r/g," ");else if(i=i.replace(/[ \t\r\n\u000c]+/g," "),/^[ \t\r\n\u000c]/.test(i)&&this.open==this.nodes.length-1){let e=n.content[n.content.length-1],r=t.previousSibling;(!e||r&&"BR"==r.nodeName||e.isText&&/[ \t\r\n\u000c]$/.test(e.text))&&(i=i.slice(1))}i&&this.insertNode(s.text(i),e,!/\S/.test(i)),this.findInText(t)}else this.findInside(t)}addElement(t,e,i){let n=this.localPreserveWS,r=this.top;("PRE"==t.tagName||/pre/.test(t.style&&t.style.whiteSpace))&&(this.localPreserveWS=!0);let s,o=t.nodeName.toLowerCase();_t.hasOwnProperty(o)&&this.parser.normalizeLists&&function(t){for(let e=t.firstChild,i=null;e;e=e.nextSibling){let t=1==e.nodeType?e.nodeName.toLowerCase():null;t&&_t.hasOwnProperty(t)&&i?(i.appendChild(e),e=i):"li"==t?i=e:t&&(i=null)}}(t);let h=this.options.ruleFromNode&&this.options.ruleFromNode(t)||(s=this.parser.matchTag(t,this,i));t:if(h?h.ignore:Dt.hasOwnProperty(o))this.findInside(t),this.ignoreFallback(t,e);else if(!h||h.skip||h.closeParent){h&&h.closeParent?this.open=Math.max(0,this.open-1):h&&h.skip.nodeType&&(t=h.skip);let i,n=this.needsBlock;if(Rt.hasOwnProperty(o))r.content.length&&r.content[0].isInline&&this.open&&(this.open--,r=this.top),i=!0,r.type||(this.needsBlock=!0);else if(!t.firstChild){this.leafFallback(t,e);break t}let s=h&&h.skip?e:this.readStyles(t,e);s&&this.addAll(t,s),i&&this.sync(r),this.needsBlock=n}else{let i=this.readStyles(t,e);i&&this.addElementByRule(t,h,i,!1===h.consuming?s:void 0)}this.localPreserveWS=n}leafFallback(t,e){"BR"==t.nodeName&&this.top.type&&this.top.type.inlineContent&&this.addTextNode(t.ownerDocument.createTextNode("\n"),e)}ignoreFallback(t,e){"BR"!=t.nodeName||this.top.type&&this.top.type.inlineContent||this.findPlace(this.parser.schema.text("-"),e,!0)}readStyles(t,e){let i=t.style;if(i&&i.length)for(let t=0;t<this.parser.matchedStyles.length;t++){let n=this.parser.matchedStyles[t],r=i.getPropertyValue(n);if(r)for(let t;;){let i=this.parser.matchStyle(n,r,this,t);if(!i)break;if(i.ignore)return null;if(e=i.clearMark?e.filter((t=>!i.clearMark(t))):e.concat(this.parser.schema.marks[i.mark].create(i.attrs)),!1!==i.consuming)break;t=i}}return e}addElementByRule(t,e,i,n){let r,s;if(e.node)if(s=this.parser.schema.nodes[e.node],s.isLeaf)this.insertNode(s.create(e.attrs),i,"BR"==t.nodeName)||this.leafFallback(t,i);else{let t=this.enter(s,e.attrs||null,i,e.preserveWhitespace);t&&(r=!0,i=t)}else i=i.concat(this.parser.schema.marks[e.mark].create(e.attrs));let o=this.top;if(s&&s.isLeaf)this.findInside(t);else if(n)this.addElement(t,i,n);else if(e.getContent)this.findInside(t),e.getContent(t,this.parser.schema).forEach((t=>this.insertNode(t,i,!1)));else{let n=t;"string"==typeof e.contentElement?n=t.querySelector(e.contentElement):"function"==typeof e.contentElement?n=e.contentElement(t):e.contentElement&&(n=e.contentElement),this.findAround(t,n,!0),this.addAll(n,i),this.findAround(t,n,!1)}r&&this.sync(o)&&this.open--}addAll(t,e,i,n){let r=i||0;for(let s=i?t.childNodes[i]:t.firstChild,o=null==n?null:t.childNodes[n];s!=o;s=s.nextSibling,++r)this.findAtPoint(t,r),this.addDOM(s,e);this.findAtPoint(t,r)}findPlace(t,e,i){let n,r;for(let e=this.open,s=0;e>=0;e--){let o=this.nodes[e],h=o.findWrapping(t);if(h&&(!n||n.length>h.length+s)&&(n=h,r=o,!h.length))break;if(o.solid){if(i)break;s+=2}}if(!n)return null;this.sync(r);for(let t=0;t<n.length;t++)e=this.enterInner(n[t],null,e,!1);return e}insertNode(t,e,i){if(t.isInline&&this.needsBlock&&!this.top.type){let t=this.textblockFromContext();t&&(e=this.enterInner(t,null,e))}let n=this.findPlace(t,e,i);if(n){this.closeExtra();let e=this.top;e.match&&(e.match=e.match.matchType(t.type));let i=G.none;for(let r of n.concat(t.marks))(e.type?e.type.allowsMarkType(r.type):Ut(r.type,t.type))&&(i=r.addToSet(i));return e.content.push(t.mark(i)),!0}return!1}enter(t,e,i,n){let r=this.findPlace(t.create(e),i,!1);return r&&(r=this.enterInner(t,e,i,!0,n)),r}enterInner(t,e,i,n=!1,r){this.closeExtra();let s=this.top;s.match=s.match&&s.match.matchType(t);let o=Lt(t,r,s.options);4&s.options&&0==s.content.length&&(o|=4);let h=G.none;return i=i.filter((e=>!(s.type?s.type.allowsMarkType(e.type):Ut(e.type,t))||(h=e.addToSet(h),!1))),this.nodes.push(new Bt(t,e,h,n,null,o)),this.open++,i}closeExtra(t=!1){let e=this.nodes.length-1;if(e>this.open){for(;e>this.open;e--)this.nodes[e-1].content.push(this.nodes[e].finish(t));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(t){for(let e=this.open;e>=0;e--){if(this.nodes[e]==t)return this.open=e,!0;this.localPreserveWS&&(this.nodes[e].options|=1)}return!1}get currentPos(){this.closeExtra();let t=0;for(let e=this.open;e>=0;e--){let i=this.nodes[e].content;for(let e=i.length-1;e>=0;e--)t+=i[e].nodeSize;e&&t++}return t}findAtPoint(t,e){if(this.find)for(let i=0;i<this.find.length;i++)this.find[i].node==t&&this.find[i].offset==e&&(this.find[i].pos=this.currentPos)}findInside(t){if(this.find)for(let e=0;e<this.find.length;e++)null==this.find[e].pos&&1==t.nodeType&&t.contains(this.find[e].node)&&(this.find[e].pos=this.currentPos)}findAround(t,e,i){if(t!=e&&this.find)for(let n=0;n<this.find.length;n++)null==this.find[n].pos&&1==t.nodeType&&t.contains(this.find[n].node)&&e.compareDocumentPosition(this.find[n].node)&(i?2:4)&&(this.find[n].pos=this.currentPos)}findInText(t){if(this.find)for(let e=0;e<this.find.length;e++)this.find[e].node==t&&(this.find[e].pos=this.currentPos-(t.nodeValue.length-this.find[e].offset))}matchesContext(t){if(t.indexOf("|")>-1)return t.split(/\s*\|\s*/).some(this.matchesContext,this);let e=t.split("/"),i=this.options.context,n=!(this.isOpen||i&&i.parent.type!=this.nodes[0].type),r=(n?0:1)-(i?i.depth+1:0),s=(t,o)=>{for(;t>=0;t--){let h=e[t];if(""==h){if(t==e.length-1||0==t)continue;for(;o>=r;o--)if(s(t-1,o))return!0;return!1}{let t=o>0||0==o&&n?this.nodes[o].type:i&&o>=r?i.node(o-r).type:null;if(!t||t.name!=h&&!t.isInGroup(h))return!1;o--}}return!0};return s(e.length-1,this.open)}textblockFromContext(){let t=this.options.context;if(t)for(let e=t.depth;e>=0;e--){let i=t.node(e).contentMatchAt(t.indexAfter(e)).defaultType;if(i&&i.isTextblock&&i.defaultAttrs)return i}for(let t in this.parser.schema.nodes){let e=this.parser.schema.nodes[t];if(e.isTextblock&&e.defaultAttrs)return e}}}function Nt(t,e){return(t.matches||t.msMatchesSelector||t.webkitMatchesSelector||t.mozMatchesSelector).call(t,e)}function Wt(t){let e={};for(let i in t)e[i]=t[i];return e}function Ut(t,e){let i=e.schema.nodes;for(let n in i){let r=i[n];if(!r.allowsMarkType(t))continue;let s=[],o=t=>{s.push(t);for(let i=0;i<t.edgeCount;i++){let{type:n,next:r}=t.edge(i);if(n==e)return!0;if(s.indexOf(r)<0&&o(r))return!0}};if(o(r.contentMatch))return!0}}class Kt{constructor(t,e){this.nodes=t,this.marks=e}serializeFragment(t,e={},i){i||(i=Vt(e).createDocumentFragment());let n=i,r=[];return t.forEach((t=>{if(r.length||t.marks.length){let i=0,s=0;for(;i<r.length&&s<t.marks.length;){let e=t.marks[s];if(this.marks[e.type.name]){if(!e.eq(r[i][0])||!1===e.type.spec.spanning)break;i++,s++}else s++}for(;i<r.length;)n=r.pop()[1];for(;s<t.marks.length;){let i=t.marks[s++],o=this.serializeMark(i,t.isInline,e);o&&(r.push([i,n]),n.appendChild(o.dom),n=o.contentDOM||o.dom)}}n.appendChild(this.serializeNodeInner(t,e))})),i}serializeNodeInner(t,e){if(t.isText)return Vt(e).createTextNode(t.text);let{dom:i,contentDOM:n}=Xt(Vt(e),this.nodes[t.type.name](t),null,t.attrs);if(n){if(t.isLeaf)throw new RangeError("Content hole not allowed in a leaf node spec");this.serializeFragment(t.content,e,n)}return i}serializeNode(t,e={}){let i=this.serializeNodeInner(t,e);for(let n=t.marks.length-1;n>=0;n--){let r=this.serializeMark(t.marks[n],t.isInline,e);r&&((r.contentDOM||r.dom).appendChild(i),i=r.dom)}return i}serializeMark(t,e,i={}){let n=this.marks[t.type.name];return n&&Xt(Vt(i),n(t,e),null,t.attrs)}static renderSpec(t,e,i=null,n){return"string"==typeof e?{dom:t.createTextNode(e)}:Xt(t,e,i,n)}static fromSchema(t){return t.cached.domSerializer||(t.cached.domSerializer=new Kt(this.nodesFromSchema(t),this.marksFromSchema(t)))}static nodesFromSchema(t){let e=Ht(t.nodes);return e.text||(e.text=t=>t.text),e}static marksFromSchema(t){return Ht(t.marks)}}function Ht(t){let e={};for(let i in t){let n=t[i].spec.toDOM;n&&(e[i]=n)}return e}function Vt(t){return t.document||window.document}const Gt=new WeakMap;function Xt(t,e,i,n){if(1==e.nodeType)return{dom:e};if(e.dom&&1==e.dom.nodeType)return e;let r,s=e[0];if("string"!=typeof s)throw new RangeError("Invalid array passed to renderSpec");if(n&&(r=function(t){let e=Gt.get(t);return void 0===e&&Gt.set(t,e=function(t){let e=null;return function t(i){if(i&&"object"==typeof i)if(Array.isArray(i))if("string"==typeof i[0])e||(e=[]),e.push(i);else for(let e=0;e<i.length;e++)t(i[e]);else for(let e in i)t(i[e])}(t),e}(t)),e}(n))&&r.indexOf(e)>-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,h=s.indexOf(" ");h>0&&(i=s.slice(0,h),s=s.slice(h+1));let a=i?t.createElementNS(i,s):t.createElement(s),l=e[1],u=1;if(l&&"object"==typeof l&&null==l.nodeType&&!Array.isArray(l)){u=2;for(let t in l)if(null!=l[t]){let e=t.indexOf(" ");e>0?a.setAttributeNS(t.slice(0,e),t.slice(e+1),l[t]):"style"==t&&a.style?a.style.cssText=l[t]:a.setAttribute(t,l[t])}}for(let r=u;r<e.length;r++){let s=e[r];if(0===s){if(r<e.length-1||r>u)throw new RangeError("Content hole must be the only child of its parent node");return{dom:a,contentDOM:a}}if("string"==typeof s)a.appendChild(t.createTextNode(s));else{let{dom:e,contentDOM:r}=Xt(t,s,i,n);if(a.appendChild(e),r){if(o)throw new RangeError("Multiple content holes");o=r}}}return{dom:a,contentDOM:o}}const Yt=Math.pow(2,16);function qt(t){return 65535&t}class Jt{constructor(t,e,i){this.pos=t,this.delInfo=e,this.recover=i}get deleted(){return(8&this.delInfo)>0}get deletedBefore(){return(5&this.delInfo)>0}get deletedAfter(){return(6&this.delInfo)>0}get deletedAcross(){return(4&this.delInfo)>0}}class Qt{constructor(t,e=!1){if(this.ranges=t,this.inverted=e,!t.length&&Qt.empty)return Qt.empty}recover(t){let e=0,i=qt(t);if(!this.inverted)for(let t=0;t<i;t++)e+=this.ranges[3*t+2]-this.ranges[3*t+1];return this.ranges[3*i]+e+function(t){return(t-(65535&t))/Yt}(t)}mapResult(t,e=1){return this._map(t,e,!1)}map(t,e=1){return this._map(t,e,!0)}_map(t,e,i){let n=0,r=this.inverted?2:1,s=this.inverted?1:2;for(let o=0;o<this.ranges.length;o+=3){let h=this.ranges[o]-(this.inverted?n:0);if(h>t)break;let a=this.ranges[o+r],l=this.ranges[o+s],u=h+a;if(t<=u){let r=h+n+((a?t==h?-1:t==u?1:e:e)<0?0:l);if(i)return r;let s=t==h?2:t==u?1:4;return(e<0?t!=h:t!=u)&&(s|=8),new Jt(r,s,t==(e<0?h:u)?null:o/3+(t-h)*Yt)}n+=l-a}return i?t+n:new Jt(t+n,0,null)}touches(t,e){let i=0,n=qt(e),r=this.inverted?2:1,s=this.inverted?1:2;for(let e=0;e<this.ranges.length;e+=3){let o=this.ranges[e]-(this.inverted?i:0);if(o>t)break;let h=this.ranges[e+r];if(t<=o+h&&e==3*n)return!0;i+=this.ranges[e+s]-h}return!1}forEach(t){let e=this.inverted?2:1,i=this.inverted?1:2;for(let n=0,r=0;n<this.ranges.length;n+=3){let s=this.ranges[n],o=s-(this.inverted?r:0),h=s+(this.inverted?0:r),a=this.ranges[n+e],l=this.ranges[n+i];t(o,o+a,h,h+l),r+=l-a}}invert(){return new Qt(this.ranges,!this.inverted)}toString(){return(this.inverted?"-":"")+JSON.stringify(this.ranges)}static offset(t){return 0==t?Qt.empty:new Qt(t<0?[0,-t,0]:[0,0,t])}}Qt.empty=new Qt([]);class Zt{constructor(t,e,i=0,n=(t?t.length:0)){this.mirror=e,this.from=i,this.to=n,this._maps=t||[],this.ownData=!(t||e)}get maps(){return this._maps}slice(t=0,e=this.maps.length){return new Zt(this._maps,this.mirror,t,e)}appendMap(t,e){this.ownData||(this._maps=this._maps.slice(),this.mirror=this.mirror&&this.mirror.slice(),this.ownData=!0),this.to=this._maps.push(t),null!=e&&this.setMirror(this._maps.length-1,e)}appendMapping(t){for(let e=0,i=this._maps.length;e<t._maps.length;e++){let n=t.getMirror(e);this.appendMap(t._maps[e],null!=n&&n<e?i+n:void 0)}}getMirror(t){if(this.mirror)for(let e=0;e<this.mirror.length;e++)if(this.mirror[e]==t)return this.mirror[e+(e%2?-1:1)]}setMirror(t,e){this.mirror||(this.mirror=[]),this.mirror.push(t,e)}appendMappingInverted(t){for(let e=t.maps.length-1,i=this._maps.length+t._maps.length;e>=0;e--){let n=t.getMirror(e);this.appendMap(t._maps[e].invert(),null!=n&&n>e?i-n-1:void 0)}}invert(){let t=new Zt;return t.appendMappingInverted(this),t}map(t,e=1){if(this.mirror)return this._map(t,e,!0);for(let i=this.from;i<this.to;i++)t=this._maps[i].map(t,e);return t}mapResult(t,e=1){return this._map(t,e,!1)}_map(t,e,i){let n=0;for(let i=this.from;i<this.to;i++){let r=this._maps[i].mapResult(t,e);if(null!=r.recover){let e=this.getMirror(i);if(null!=e&&e>i&&e<this.to){i=e,t=this._maps[e].recover(r.recover);continue}}n|=r.delInfo,t=r.pos}return i?t:new Jt(t,n,null)}}const te=Object.create(null);class ee{getMap(){return Qt.empty}merge(t){return null}static fromJSON(t,e){if(!e||!e.stepType)throw new RangeError("Invalid input for Step.fromJSON");let i=te[e.stepType];if(!i)throw new RangeError(`No step type ${e.stepType} defined`);return i.fromJSON(t,e)}static jsonID(t,e){if(t in te)throw new RangeError("Duplicate use of step JSON ID "+t);return te[t]=e,e.prototype.jsonID=t,e}}class ie{constructor(t,e){this.doc=t,this.failed=e}static ok(t){return new ie(t,null)}static fail(t){return new ie(null,t)}static fromReplace(t,e,i,n){try{return ie.ok(t.replace(e,i,n))}catch(t){if(t instanceof X)return ie.fail(t.message);throw t}}}function ne(t,e,i){let n=[];for(let r=0;r<t.childCount;r++){let s=t.child(r);s.content.size&&(s=s.copy(ne(s.content,e,s))),s.isInline&&(s=e(s,i,r)),n.push(s)}return U.fromArray(n)}class re extends ee{constructor(t,e,i){super(),this.from=t,this.to=e,this.mark=i}apply(t){let e=t.slice(this.from,this.to),i=t.resolve(this.from),n=i.node(i.sharedDepth(this.to)),r=new Y(ne(e.content,((t,e)=>t.isAtom&&e.type.allowsMarkType(this.mark.type)?t.mark(this.mark.addToSet(t.marks)):t),n),e.openStart,e.openEnd);return ie.fromReplace(t,this.from,this.to,r)}invert(){return new se(this.from,this.to,this.mark)}map(t){let e=t.mapResult(this.from,1),i=t.mapResult(this.to,-1);return e.deleted&&i.deleted||e.pos>=i.pos?null:new re(e.pos,i.pos,this.mark)}merge(t){return t instanceof re&&t.mark.eq(this.mark)&&this.from<=t.to&&this.to>=t.from?new re(Math.min(this.from,t.from),Math.max(this.to,t.to),this.mark):null}toJSON(){return{stepType:"addMark",mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(t,e){if("number"!=typeof e.from||"number"!=typeof e.to)throw new RangeError("Invalid input for AddMarkStep.fromJSON");return new re(e.from,e.to,t.markFromJSON(e.mark))}}ee.jsonID("addMark",re);class se extends ee{constructor(t,e,i){super(),this.from=t,this.to=e,this.mark=i}apply(t){let e=t.slice(this.from,this.to),i=new Y(ne(e.content,(t=>t.mark(this.mark.removeFromSet(t.marks))),t),e.openStart,e.openEnd);return ie.fromReplace(t,this.from,this.to,i)}invert(){return new re(this.from,this.to,this.mark)}map(t){let e=t.mapResult(this.from,1),i=t.mapResult(this.to,-1);return e.deleted&&i.deleted||e.pos>=i.pos?null:new se(e.pos,i.pos,this.mark)}merge(t){return t instanceof se&&t.mark.eq(this.mark)&&this.from<=t.to&&this.to>=t.from?new se(Math.min(this.from,t.from),Math.max(this.to,t.to),this.mark):null}toJSON(){return{stepType:"removeMark",mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(t,e){if("number"!=typeof e.from||"number"!=typeof e.to)throw new RangeError("Invalid input for RemoveMarkStep.fromJSON");return new se(e.from,e.to,t.markFromJSON(e.mark))}}ee.jsonID("removeMark",se);class oe extends ee{constructor(t,e){super(),this.pos=t,this.mark=e}apply(t){let e=t.nodeAt(this.pos);if(!e)return ie.fail("No node at mark step's position");let i=e.type.create(e.attrs,null,this.mark.addToSet(e.marks));return ie.fromReplace(t,this.pos,this.pos+1,new Y(U.from(i),0,e.isLeaf?0:1))}invert(t){let e=t.nodeAt(this.pos);if(e){let t=this.mark.addToSet(e.marks);if(t.length==e.marks.length){for(let i=0;i<e.marks.length;i++)if(!e.marks[i].isInSet(t))return new oe(this.pos,e.marks[i]);return new oe(this.pos,this.mark)}}return new he(this.pos,this.mark)}map(t){let e=t.mapResult(this.pos,1);return e.deletedAfter?null:new oe(e.pos,this.mark)}toJSON(){return{stepType:"addNodeMark",pos:this.pos,mark:this.mark.toJSON()}}static fromJSON(t,e){if("number"!=typeof e.pos)throw new RangeError("Invalid input for AddNodeMarkStep.fromJSON");return new oe(e.pos,t.markFromJSON(e.mark))}}ee.jsonID("addNodeMark",oe);class he extends ee{constructor(t,e){super(),this.pos=t,this.mark=e}apply(t){let e=t.nodeAt(this.pos);if(!e)return ie.fail("No node at mark step's position");let i=e.type.create(e.attrs,null,this.mark.removeFromSet(e.marks));return ie.fromReplace(t,this.pos,this.pos+1,new Y(U.from(i),0,e.isLeaf?0:1))}invert(t){let e=t.nodeAt(this.pos);return e&&this.mark.isInSet(e.marks)?new oe(this.pos,this.mark):this}map(t){let e=t.mapResult(this.pos,1);return e.deletedAfter?null:new he(e.pos,this.mark)}toJSON(){return{stepType:"removeNodeMark",pos:this.pos,mark:this.mark.toJSON()}}static fromJSON(t,e){if("number"!=typeof e.pos)throw new RangeError("Invalid input for RemoveNodeMarkStep.fromJSON");return new he(e.pos,t.markFromJSON(e.mark))}}ee.jsonID("removeNodeMark",he);class ae extends ee{constructor(t,e,i,n=!1){super(),this.from=t,this.to=e,this.slice=i,this.structure=n}apply(t){return this.structure&&ue(t,this.from,this.to)?ie.fail("Structure replace would overwrite content"):ie.fromReplace(t,this.from,this.to,this.slice)}getMap(){return new Qt([this.from,this.to-this.from,this.slice.size])}invert(t){return new ae(this.from,this.from+this.slice.size,t.slice(this.from,this.to))}map(t){let e=t.mapResult(this.to,-1),i=this.from==this.to&&ae.MAP_BIAS<0?e:t.mapResult(this.from,1);return i.deletedAcross&&e.deletedAcross?null:new ae(i.pos,Math.max(i.pos,e.pos),this.slice,this.structure)}merge(t){if(!(t instanceof ae)||t.structure||this.structure)return null;if(this.from+this.slice.size!=t.from||this.slice.openEnd||t.slice.openStart){if(t.to!=this.from||this.slice.openStart||t.slice.openEnd)return null;{let e=this.slice.size+t.slice.size==0?Y.empty:new Y(t.slice.content.append(this.slice.content),t.slice.openStart,this.slice.openEnd);return new ae(t.from,this.to,e,this.structure)}}{let e=this.slice.size+t.slice.size==0?Y.empty:new Y(this.slice.content.append(t.slice.content),this.slice.openStart,t.slice.openEnd);return new ae(this.from,this.to+(t.to-t.from),e,this.structure)}}toJSON(){let t={stepType:"replace",from:this.from,to:this.to};return this.slice.size&&(t.slice=this.slice.toJSON()),this.structure&&(t.structure=!0),t}static fromJSON(t,e){if("number"!=typeof e.from||"number"!=typeof e.to)throw new RangeError("Invalid input for ReplaceStep.fromJSON");return new ae(e.from,e.to,Y.fromJSON(t,e.slice),!!e.structure)}}ae.MAP_BIAS=1,ee.jsonID("replace",ae);class le extends ee{constructor(t,e,i,n,r,s,o=!1){super(),this.from=t,this.to=e,this.gapFrom=i,this.gapTo=n,this.slice=r,this.insert=s,this.structure=o}apply(t){if(this.structure&&(ue(t,this.from,this.gapFrom)||ue(t,this.gapTo,this.to)))return ie.fail("Structure gap-replace would overwrite content");let e=t.slice(this.gapFrom,this.gapTo);if(e.openStart||e.openEnd)return ie.fail("Gap is not a flat range");let i=this.slice.insertAt(this.insert,e.content);return i?ie.fromReplace(t,this.from,this.to,i):ie.fail("Content does not fit in gap")}getMap(){return new Qt([this.from,this.gapFrom-this.from,this.insert,this.gapTo,this.to-this.gapTo,this.slice.size-this.insert])}invert(t){let e=this.gapTo-this.gapFrom;return new le(this.from,this.from+this.slice.size+e,this.from+this.insert,this.from+this.insert+e,t.slice(this.from,this.to).removeBetween(this.gapFrom-this.from,this.gapTo-this.from),this.gapFrom-this.from,this.structure)}map(t){let e=t.mapResult(this.from,1),i=t.mapResult(this.to,-1),n=this.from==this.gapFrom?e.pos:t.map(this.gapFrom,-1),r=this.to==this.gapTo?i.pos:t.map(this.gapTo,1);return e.deletedAcross&&i.deletedAcross||n<e.pos||r>i.pos?null:new le(e.pos,i.pos,n,r,this.slice,this.insert,this.structure)}toJSON(){let t={stepType:"replaceAround",from:this.from,to:this.to,gapFrom:this.gapFrom,gapTo:this.gapTo,insert:this.insert};return this.slice.size&&(t.slice=this.slice.toJSON()),this.structure&&(t.structure=!0),t}static fromJSON(t,e){if("number"!=typeof e.from||"number"!=typeof e.to||"number"!=typeof e.gapFrom||"number"!=typeof e.gapTo||"number"!=typeof e.insert)throw new RangeError("Invalid input for ReplaceAroundStep.fromJSON");return new le(e.from,e.to,e.gapFrom,e.gapTo,Y.fromJSON(t,e.slice),e.insert,!!e.structure)}}function ue(t,e,i){let n=t.resolve(e),r=i-e,s=n.depth;for(;r>0&&s>0&&n.indexAfter(s)==n.node(s).childCount;)s--,r--;if(r>0){let t=n.node(s).maybeChild(n.indexAfter(s));for(;r>0;){if(!t||t.isLeaf)return!0;t=t.firstChild,r--}}return!1}function ce(t,e,i,n=i.contentMatch,r=!0){let s=t.doc.nodeAt(e),o=[],h=e+1;for(let e=0;e<s.childCount;e++){let a=s.child(e),l=h+a.nodeSize,u=n.matchType(a.type);if(u){n=u;for(let e=0;e<a.marks.length;e++)i.allowsMarkType(a.marks[e].type)||t.step(new se(h,l,a.marks[e]));if(r&&a.isText&&"pre"!=i.whitespace){let t,e,n=/\r?\n|\r/g;for(;t=n.exec(a.text);)e||(e=new Y(U.from(i.schema.text(" ",i.allowedMarks(a.marks))),0,0)),o.push(new ae(h+t.index,h+t.index+t[0].length,e))}}else o.push(new ae(h,l,Y.empty));h=l}if(!n.validEnd){let e=n.fillBefore(U.empty,!0);t.replace(h,h,new Y(e,0,0))}for(let e=o.length-1;e>=0;e--)t.step(o[e])}function fe(t,e,i){return(0==e||t.canReplace(e,t.childCount))&&(i==t.childCount||t.canReplace(0,i))}function de(t){let e=t.parent.content.cutByIndex(t.startIndex,t.endIndex);for(let i=t.depth,n=0,r=0;;--i){let s=t.$from.node(i),o=t.$from.index(i)+n,h=t.$to.indexAfter(i)-r;if(i<t.depth&&s.canReplace(o,h,e))return i;if(0==i||s.type.spec.isolating||!fe(s,o,h))break;o&&(n=1),h<s.childCount&&(r=1)}return null}function pe(t,e,i,n){e.forEach(((r,s)=>{if(r.isText){let o,h=/\r?\n|\r/g;for(;o=h.exec(r.text);){let r=t.mapping.slice(n).map(i+1+s+o.index);t.replaceWith(r,r+1,e.type.schema.linebreakReplacement.create())}}}))}function ge(t,e,i,n){e.forEach(((r,s)=>{if(r.type==r.type.schema.linebreakReplacement){let r=t.mapping.slice(n).map(i+1+s);t.replaceWith(r,r+1,e.type.schema.text("\n"))}}))}function me(t,e,i=1,n){let r=t.resolve(e),s=r.depth-i,o=n&&n[n.length-1]||r.parent;if(s<0||r.parent.type.spec.isolating||!r.parent.canReplace(r.index(),r.parent.childCount)||!o.type.validContent(r.parent.content.cutByIndex(r.index(),r.parent.childCount)))return!1;for(let t=r.depth-1,e=i-2;t>s;t--,e--){let i=r.node(t),s=r.index(t);if(i.type.spec.isolating)return!1;let o=i.content.cutByIndex(s,i.childCount),h=n&&n[e+1];h&&(o=o.replaceChild(0,h.type.create(h.attrs)));let a=n&&n[e]||i;if(!i.canReplace(s+1,i.childCount)||!a.type.validContent(o))return!1}let h=r.indexAfter(s),a=n&&n[0];return r.node(s).canReplaceWith(h,h,a?a.type:r.node(s+1).type)}function we(t,e){let i=t.resolve(e),n=i.index();return function(t,e){return!(!t||!e||t.isLeaf||!function(t,e){e.content.size||t.type.compatibleContent(e.type);let i=t.contentMatchAt(t.childCount),{linebreakReplacement:n}=t.type.schema;for(let r=0;r<e.childCount;r++){let s=e.child(r);if(i=i.matchType(s.type==n?t.type.schema.nodes.text:s.type),!i)return!1;if(!t.type.allowsMarks(s.marks))return!1}return i.validEnd}(t,e))}(i.nodeBefore,i.nodeAfter)&&i.parent.canReplace(n,n+1)}function ve(t,e,i=e,n=Y.empty){if(e==i&&!n.size)return null;let r=t.resolve(e),s=t.resolve(i);return ye(r,s,n)?new ae(e,i,n):new be(r,s,n).fit()}function ye(t,e,i){return!i.openStart&&!i.openEnd&&t.start()==e.start()&&t.parent.canReplace(t.index(),e.index(),i.content)}ee.jsonID("replaceAround",le);class be{constructor(t,e,i){this.$from=t,this.$to=e,this.unplaced=i,this.frontier=[],this.placed=U.empty;for(let e=0;e<=t.depth;e++){let i=t.node(e);this.frontier.push({type:i.type,match:i.contentMatchAt(t.indexAfter(e))})}for(let e=t.depth;e>0;e--)this.placed=U.from(t.node(e).copy(this.placed))}get depth(){return this.frontier.length-1}fit(){for(;this.unplaced.size;){let t=this.findFittable();t?this.placeNodes(t):this.openMore()||this.dropNode()}let t=this.mustMoveInline(),e=this.placed.size-this.depth-this.$from.depth,i=this.$from,n=this.close(t<0?this.$to:i.doc.resolve(t));if(!n)return null;let r=this.placed,s=i.depth,o=n.depth;for(;s&&o&&1==r.childCount;)r=r.firstChild.content,s--,o--;let h=new Y(r,s,o);return t>-1?new le(i.pos,t,this.$to.pos,this.$to.end(),h,e):h.size||i.pos!=this.$to.pos?new ae(i.pos,n.pos,h):null}findFittable(){let t=this.unplaced.openStart;for(let e=this.unplaced.content,i=0,n=this.unplaced.openEnd;i<t;i++){let r=e.firstChild;if(e.childCount>1&&(n=0),r.type.spec.isolating&&n<=i){t=i;break}e=r.content}for(let e=1;e<=2;e++)for(let i=1==e?t:this.unplaced.openStart;i>=0;i--){let t,n=null;i?(n=Se(this.unplaced.content,i-1).firstChild,t=n.content):t=this.unplaced.content;let r=t.firstChild;for(let t=this.depth;t>=0;t--){let s,{type:o,match:h}=this.frontier[t],a=null;if(1==e&&(r?h.matchType(r.type)||(a=h.fillBefore(U.from(r),!1)):n&&o.compatibleContent(n.type)))return{sliceDepth:i,frontierDepth:t,parent:n,inject:a};if(2==e&&r&&(s=h.findWrapping(r.type)))return{sliceDepth:i,frontierDepth:t,parent:n,wrap:s};if(n&&h.matchType(n.type))break}}}openMore(){let{content:t,openStart:e,openEnd:i}=this.unplaced,n=Se(t,e);return!(!n.childCount||n.firstChild.isLeaf||(this.unplaced=new Y(t,e+1,Math.max(i,n.size+e>=t.size-i?e+1:0)),0))}dropNode(){let{content:t,openStart:e,openEnd:i}=this.unplaced,n=Se(t,e);if(n.childCount<=1&&e>0){let r=t.size-e<=e+n.size;this.unplaced=new Y(ke(t,e-1,1),e-1,r?e-1:i)}else this.unplaced=new Y(ke(t,e,1),e,i)}placeNodes({sliceDepth:t,frontierDepth:e,parent:i,inject:n,wrap:r}){for(;this.depth>e;)this.closeFrontierNode();if(r)for(let t=0;t<r.length;t++)this.openFrontierNode(r[t]);let s=this.unplaced,o=i?i.content:s.content,h=s.openStart-t,a=0,l=[],{match:u,type:c}=this.frontier[e];if(n){for(let t=0;t<n.childCount;t++)l.push(n.child(t));u=u.matchFragment(n)}let f=o.size+t-(s.content.size-s.openEnd);for(;a<o.childCount;){let t=o.child(a),e=u.matchType(t.type);if(!e)break;a++,(a>1||0==h||t.content.size)&&(u=e,l.push(xe(t.mark(c.allowedMarks(t.marks)),1==a?h:0,a==o.childCount?f:-1)))}let d=a==o.childCount;d||(f=-1),this.placed=Me(this.placed,e,U.from(l)),this.frontier[e].match=u,d&&f<0&&i&&i.type==this.frontier[this.depth].type&&this.frontier.length>1&&this.closeFrontierNode();for(let t=0,e=o;t<f;t++){let t=e.lastChild;this.frontier.push({type:t.type,match:t.contentMatchAt(t.childCount)}),e=t.content}this.unplaced=d?0==t?Y.empty:new Y(ke(s.content,t-1,1),t-1,f<0?s.openEnd:t-1):new Y(ke(s.content,t,a),s.openStart,s.openEnd)}mustMoveInline(){if(!this.$to.parent.isTextblock)return-1;let t,e=this.frontier[this.depth];if(!e.type.isTextblock||!Ae(this.$to,this.$to.depth,e.type,e.match,!1)||this.$to.depth==this.depth&&(t=this.findCloseLevel(this.$to))&&t.depth==this.depth)return-1;let{depth:i}=this.$to,n=this.$to.after(i);for(;i>1&&n==this.$to.end(--i);)++n;return n}findCloseLevel(t){t:for(let e=Math.min(this.depth,t.depth);e>=0;e--){let{match:i,type:n}=this.frontier[e],r=e<t.depth&&t.end(e+1)==t.pos+(t.depth-(e+1)),s=Ae(t,e,n,i,r);if(s){for(let i=e-1;i>=0;i--){let{match:e,type:n}=this.frontier[i],r=Ae(t,i,n,e,!0);if(!r||r.childCount)continue t}return{depth:e,fit:s,move:r?t.doc.resolve(t.after(e+1)):t}}}}close(t){let e=this.findCloseLevel(t);if(!e)return null;for(;this.depth>e.depth;)this.closeFrontierNode();e.fit.childCount&&(this.placed=Me(this.placed,e.depth,e.fit)),t=e.move;for(let i=e.depth+1;i<=t.depth;i++){let e=t.node(i),n=e.type.contentMatch.fillBefore(e.content,!0,t.index(i));this.openFrontierNode(e.type,e.attrs,n)}return t}openFrontierNode(t,e=null,i){let n=this.frontier[this.depth];n.match=n.match.matchType(t),this.placed=Me(this.placed,this.depth,U.from(t.create(e,i))),this.frontier.push({type:t,match:t.contentMatch})}closeFrontierNode(){let t=this.frontier.pop().match.fillBefore(U.empty,!0);t.childCount&&(this.placed=Me(this.placed,this.frontier.length,t))}}function ke(t,e,i){return 0==e?t.cutByIndex(i,t.childCount):t.replaceChild(0,t.firstChild.copy(ke(t.firstChild.content,e-1,i)))}function Me(t,e,i){return 0==e?t.append(i):t.replaceChild(t.childCount-1,t.lastChild.copy(Me(t.lastChild.content,e-1,i)))}function Se(t,e){for(let i=0;i<e;i++)t=t.firstChild.content;return t}function xe(t,e,i){if(e<=0)return t;let n=t.content;return e>1&&(n=n.replaceChild(0,xe(n.firstChild,e-1,1==n.childCount?i-1:0))),e>0&&(n=t.type.contentMatch.fillBefore(n).append(n),i<=0&&(n=n.append(t.type.contentMatch.matchFragment(n).fillBefore(U.empty,!0)))),t.copy(n)}function Ae(t,e,i,n,r){let s=t.node(e),o=r?t.indexAfter(e):t.index(e);if(o==s.childCount&&!i.compatibleContent(s.type))return null;let h=n.fillBefore(s.content,!0,o);return h&&!function(t,e,i){for(let n=i;n<e.childCount;n++)if(!t.allowsMarks(e.child(n).marks))return!0;return!1}(i,s.content,o)?h:null}function $e(t,e,i,n,r){if(e<i){let r=t.firstChild;t=t.replaceChild(0,r.copy($e(r.content,e+1,i,n,r)))}if(e>n){let e=r.contentMatchAt(0),i=e.fillBefore(t).append(t);t=i.append(e.matchFragment(i).fillBefore(U.empty,!0))}return t}function ze(t,e){let i=[];for(let n=Math.min(t.depth,e.depth);n>=0;n--){let r=t.start(n);if(r<t.pos-(t.depth-n)||e.end(n)>e.pos+(e.depth-n)||t.node(n).type.spec.isolating||e.node(n).type.spec.isolating)break;(r==e.start(n)||n==t.depth&&n==e.depth&&t.parent.inlineContent&&e.parent.inlineContent&&n&&e.start(n-1)==r-1)&&i.push(n)}return i}class Ce extends ee{constructor(t,e,i){super(),this.pos=t,this.attr=e,this.value=i}apply(t){let e=t.nodeAt(this.pos);if(!e)return ie.fail("No node at attribute step's position");let i=Object.create(null);for(let t in e.attrs)i[t]=e.attrs[t];i[this.attr]=this.value;let n=e.type.create(i,null,e.marks);return ie.fromReplace(t,this.pos,this.pos+1,new Y(U.from(n),0,e.isLeaf?0:1))}getMap(){return Qt.empty}invert(t){return new Ce(this.pos,this.attr,t.nodeAt(this.pos).attrs[this.attr])}map(t){let e=t.mapResult(this.pos,1);return e.deletedAfter?null:new Ce(e.pos,this.attr,this.value)}toJSON(){return{stepType:"attr",pos:this.pos,attr:this.attr,value:this.value}}static fromJSON(t,e){if("number"!=typeof e.pos||"string"!=typeof e.attr)throw new RangeError("Invalid input for AttrStep.fromJSON");return new Ce(e.pos,e.attr,e.value)}}ee.jsonID("attr",Ce);class Te extends ee{constructor(t,e){super(),this.attr=t,this.value=e}apply(t){let e=Object.create(null);for(let i in t.attrs)e[i]=t.attrs[i];e[this.attr]=this.value;let i=t.type.create(e,t.content,t.marks);return ie.ok(i)}getMap(){return Qt.empty}invert(t){return new Te(this.attr,t.attrs[this.attr])}map(t){return this}toJSON(){return{stepType:"docAttr",attr:this.attr,value:this.value}}static fromJSON(t,e){if("string"!=typeof e.attr)throw new RangeError("Invalid input for DocAttrStep.fromJSON");return new Te(e.attr,e.value)}}ee.jsonID("docAttr",Te);let Ee=class extends Error{};Ee=function t(e){let i=Error.call(this,e);return i.__proto__=t.prototype,i},(Ee.prototype=Object.create(Error.prototype)).constructor=Ee,Ee.prototype.name="TransformError";class Oe{constructor(t){this.doc=t,this.steps=[],this.docs=[],this.mapping=new Zt}get before(){return this.docs.length?this.docs[0]:this.doc}step(t){let e=this.maybeStep(t);if(e.failed)throw new Ee(e.failed);return this}maybeStep(t){let e=t.apply(this.doc);return e.failed||this.addStep(t,e.doc),e}get docChanged(){return this.steps.length>0}changedRange(){let t=1e9,e=-1e9;for(let i=0;i<this.mapping.maps.length;i++){let n=this.mapping.maps[i];i&&(t=n.map(t,1),e=n.map(e,-1)),n.forEach(((i,n,r,s)=>{t=Math.min(t,r),e=Math.max(e,s)}))}return 1e9==t?null:{from:t,to:e}}addStep(t,e){this.docs.push(this.doc),this.steps.push(t),this.mapping.appendMap(t.getMap()),this.doc=e}replace(t,e=t,i=Y.empty){let n=ve(this.doc,t,e,i);return n&&this.step(n),this}replaceWith(t,e,i){return this.replace(t,e,new Y(U.from(i),0,0))}delete(t,e){return this.replace(t,e,Y.empty)}insert(t,e){return this.replaceWith(t,t,e)}replaceRange(t,e,i){return function(t,e,i,n){if(!n.size)return t.deleteRange(e,i);let r=t.doc.resolve(e),s=t.doc.resolve(i);if(ye(r,s,n))return t.step(new ae(e,i,n));let o=ze(r,s);0==o[o.length-1]&&o.pop();let h=-(r.depth+1);o.unshift(h);for(let t=r.depth,e=r.pos-1;t>0;t--,e--){let i=r.node(t).type.spec;if(i.defining||i.definingAsContext||i.isolating)break;o.indexOf(t)>-1?h=t:r.before(t)==e&&o.splice(1,0,-t)}let a=o.indexOf(h),l=[],u=n.openStart;for(let t=n.content,e=0;;e++){let i=t.firstChild;if(l.push(i),e==n.openStart)break;t=i.content}for(let t=u-1;t>=0;t--){let e=l[t],i=(c=e.type).spec.defining||c.spec.definingForContent;if(i&&!e.sameMarkup(r.node(Math.abs(h)-1)))u=t;else if(i||!e.type.isTextblock)break}var c;for(let e=n.openStart;e>=0;e--){let h=(e+u+1)%(n.openStart+1),c=l[h];if(c)for(let e=0;e<o.length;e++){let l=o[(e+a)%o.length],u=!0;l<0&&(u=!1,l=-l);let f=r.node(l-1),d=r.index(l-1);if(f.canReplaceWith(d,d,c.type,c.marks))return t.replace(r.before(l),u?s.after(l):i,new Y($e(n.content,0,n.openStart,h),h,n.openEnd))}}let f=t.steps.length;for(let h=o.length-1;h>=0&&(t.replace(e,i,n),!(t.steps.length>f));h--){let t=o[h];t<0||(e=r.before(t),i=s.after(t))}}(this,t,e,i),this}replaceRangeWith(t,e,i){return function(t,e,i,n){if(!n.isInline&&e==i&&t.doc.resolve(e).parent.content.size){let r=function(t,e,i){let n=t.resolve(e);if(n.parent.canReplaceWith(n.index(),n.index(),i))return e;if(0==n.parentOffset)for(let t=n.depth-1;t>=0;t--){let e=n.index(t);if(n.node(t).canReplaceWith(e,e,i))return n.before(t+1);if(e>0)return null}if(n.parentOffset==n.parent.content.size)for(let t=n.depth-1;t>=0;t--){let e=n.indexAfter(t);if(n.node(t).canReplaceWith(e,e,i))return n.after(t+1);if(e<n.node(t).childCount)return null}return null}(t.doc,e,n.type);null!=r&&(e=i=r)}t.replaceRange(e,i,new Y(U.from(n),0,0))}(this,t,e,i),this}deleteRange(t,e){return function(t,e,i){let n=t.doc.resolve(e),r=t.doc.resolve(i);if(n.parent.isTextblock&&r.parent.isTextblock&&n.start()!=r.start()&&0==n.parentOffset&&0==r.parentOffset){let s=n.sharedDepth(i),o=!1;for(let t=n.depth;t>s;t--)n.node(t).type.spec.isolating&&(o=!0);for(let t=r.depth;t>s;t--)r.node(t).type.spec.isolating&&(o=!0);if(!o){for(let t=n.depth;t>0&&e==n.start(t);t--)e=n.before(t);for(let t=r.depth;t>0&&i==r.start(t);t--)i=r.before(t);n=t.doc.resolve(e),r=t.doc.resolve(i)}}let s=ze(n,r);for(let e=0;e<s.length;e++){let i=s[e],o=e==s.length-1;if(o&&0==i||n.node(i).type.contentMatch.validEnd)return t.delete(n.start(i),r.end(i));if(i>0&&(o||n.node(i-1).canReplace(n.index(i-1),r.indexAfter(i-1))))return t.delete(n.before(i),r.after(i))}for(let s=1;s<=n.depth&&s<=r.depth;s++)if(e-n.start(s)==n.depth-s&&i>n.end(s)&&r.end(s)-i!=r.depth-s&&n.start(s-1)==r.start(s-1)&&n.node(s-1).canReplace(n.index(s-1),r.index(s-1)))return t.delete(n.before(s),i);t.delete(e,i)}(this,t,e),this}lift(t,e){return function(t,e,i){let{$from:n,$to:r,depth:s}=e,o=n.before(s+1),h=r.after(s+1),a=o,l=h,u=U.empty,c=0;for(let t=s,e=!1;t>i;t--)e||n.index(t)>0?(e=!0,u=U.from(n.node(t).copy(u)),c++):a--;let f=U.empty,d=0;for(let t=s,e=!1;t>i;t--)e||r.after(t+1)<r.end(t)?(e=!0,f=U.from(r.node(t).copy(f)),d++):l++;t.step(new le(a,l,o,h,new Y(u.append(f),c,d),u.size-c,!0))}(this,t,e),this}join(t,e=1){return function(t,e,i){let n=null,{linebreakReplacement:r}=t.doc.type.schema,s=t.doc.resolve(e-i),o=s.node().type;if(r&&o.inlineContent){let t="pre"==o.whitespace,e=!!o.contentMatch.matchType(r);t&&!e?n=!1:!t&&e&&(n=!0)}let h=t.steps.length;if(!1===n){let n=t.doc.resolve(e+i);ge(t,n.node(),n.before(),h)}o.inlineContent&&ce(t,e+i-1,o,s.node().contentMatchAt(s.index()),null==n);let a=t.mapping.slice(h),l=a.map(e-i);if(t.step(new ae(l,a.map(e+i,-1),Y.empty,!0)),!0===n){let e=t.doc.resolve(l);pe(t,e.node(),e.before(),t.steps.length)}}(this,t,e),this}wrap(t,e){return function(t,e,i){let n=U.empty;for(let t=i.length-1;t>=0;t--){if(n.size){let e=i[t].type.contentMatch.matchFragment(n);if(!e||!e.validEnd)throw new RangeError("Wrapper type given to Transform.wrap does not form valid content of its parent wrapper")}n=U.from(i[t].type.create(i[t].attrs,n))}let r=e.start,s=e.end;t.step(new le(r,s,r,s,new Y(n,0,0),i.length,!0))}(this,t,e),this}setBlockType(t,e=t,i,n=null){return function(t,e,i,n,r){if(!n.isTextblock)throw new RangeError("Type given to setBlockType should be a textblock");let s=t.steps.length;t.doc.nodesBetween(e,i,((e,i)=>{let o="function"==typeof r?r(e):r;if(e.isTextblock&&!e.hasMarkup(n,o)&&function(t,e,i){let n=t.resolve(e),r=n.index();return n.parent.canReplaceWith(r,r+1,i)}(t.doc,t.mapping.slice(s).map(i),n)){let r=null;if(n.schema.linebreakReplacement){let t="pre"==n.whitespace,e=!!n.contentMatch.matchType(n.schema.linebreakReplacement);t&&!e?r=!1:!t&&e&&(r=!0)}!1===r&&ge(t,e,i,s),ce(t,t.mapping.slice(s).map(i,1),n,void 0,null===r);let h=t.mapping.slice(s),a=h.map(i,1),l=h.map(i+e.nodeSize,1);return t.step(new le(a,l,a+1,l-1,new Y(U.from(n.create(o,null,e.marks)),0,0),1,!0)),!0===r&&pe(t,e,i,s),!1}}))}(this,t,e,i,n),this}setNodeMarkup(t,e,i=null,n){return function(t,e,i,n,r){let s=t.doc.nodeAt(e);if(!s)throw new RangeError("No node at given position");i||(i=s.type);let o=i.create(n,null,r||s.marks);if(s.isLeaf)return t.replaceWith(e,e+s.nodeSize,o);if(!i.validContent(s.content))throw new RangeError("Invalid content for node type "+i.name);t.step(new le(e,e+s.nodeSize,e+1,e+s.nodeSize-1,new Y(U.from(o),0,0),1,!0))}(this,t,e,i,n),this}setNodeAttribute(t,e,i){return this.step(new Ce(t,e,i)),this}setDocAttribute(t,e){return this.step(new Te(t,e)),this}addNodeMark(t,e){return this.step(new oe(t,e)),this}removeNodeMark(t,e){let i=this.doc.nodeAt(t);if(!i)throw new RangeError("No node at position "+t);if(e instanceof G)e.isInSet(i.marks)&&this.step(new he(t,e));else{let n,r=i.marks,s=[];for(;n=e.isInSet(r);)s.push(new he(t,n)),r=n.removeFromSet(r);for(let t=s.length-1;t>=0;t--)this.step(s[t])}return this}split(t,e=1,i){return function(t,e,i=1,n){let r=t.doc.resolve(e),s=U.empty,o=U.empty;for(let t=r.depth,e=r.depth-i,h=i-1;t>e;t--,h--){s=U.from(r.node(t).copy(s));let e=n&&n[h];o=U.from(e?e.type.create(e.attrs,o):r.node(t).copy(o))}t.step(new ae(e,e,new Y(s.append(o),i,i),!0))}(this,t,e,i),this}addMark(t,e,i){return function(t,e,i,n){let r,s,o=[],h=[];t.doc.nodesBetween(e,i,((t,a,l)=>{if(!t.isInline)return;let u=t.marks;if(!n.isInSet(u)&&l.type.allowsMarkType(n.type)){let l=Math.max(a,e),c=Math.min(a+t.nodeSize,i),f=n.addToSet(u);for(let t=0;t<u.length;t++)u[t].isInSet(f)||(r&&r.to==l&&r.mark.eq(u[t])?r.to=c:o.push(r=new se(l,c,u[t])));s&&s.to==l?s.to=c:h.push(s=new re(l,c,n))}})),o.forEach((e=>t.step(e))),h.forEach((e=>t.step(e)))}(this,t,e,i),this}removeMark(t,e,i){return function(t,e,i,n){let r=[],s=0;t.doc.nodesBetween(e,i,((t,o)=>{if(!t.isInline)return;s++;let h=null;if(n instanceof Ot){let e,i=t.marks;for(;e=n.isInSet(i);)(h||(h=[])).push(e),i=e.removeFromSet(i)}else n?n.isInSet(t.marks)&&(h=[n]):h=t.marks;if(h&&h.length){let n=Math.min(o+t.nodeSize,i);for(let t=0;t<h.length;t++){let i,a=h[t];for(let t=0;t<r.length;t++){let e=r[t];e.step==s-1&&a.eq(r[t].style)&&(i=e)}i?(i.to=n,i.step=s):r.push({style:a,from:Math.max(o,e),to:n,step:s})}}})),r.forEach((e=>t.step(new se(e.from,e.to,e.style))))}(this,t,e,i),this}clearIncompatible(t,e,i){return ce(this,t,e,i),this}}const Ie=Object.create(null);class je{constructor(t,e,i){this.$anchor=t,this.$head=e,this.ranges=i||[new Pe(t.min(e),t.max(e))]}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 t=this.ranges;for(let e=0;e<t.length;e++)if(t[e].$from.pos!=t[e].$to.pos)return!1;return!0}content(){return this.$from.doc.slice(this.from,this.to,!0)}replace(t,e=Y.empty){let i=e.content.lastChild,n=null;for(let t=0;t<e.openEnd;t++)n=i,i=i.lastChild;let r=t.steps.length,s=this.ranges;for(let o=0;o<s.length;o++){let{$from:h,$to:a}=s[o],l=t.mapping.slice(r);t.replaceRange(l.map(h.pos),l.map(a.pos),o?Y.empty:e),0==o&&Ke(t,r,(i?i.isInline:n&&n.isTextblock)?-1:1)}}replaceWith(t,e){let i=t.steps.length,n=this.ranges;for(let r=0;r<n.length;r++){let{$from:s,$to:o}=n[r],h=t.mapping.slice(i),a=h.map(s.pos),l=h.map(o.pos);r?t.deleteRange(a,l):(t.replaceRangeWith(a,l,e),Ke(t,i,e.isInline?-1:1))}}static findFrom(t,e,i=!1){let n=t.parent.inlineContent?new _e(t):Ue(t.node(0),t.parent,t.pos,t.index(),e,i);if(n)return n;for(let n=t.depth-1;n>=0;n--){let r=e<0?Ue(t.node(0),t.node(n),t.before(n+1),t.index(n),e,i):Ue(t.node(0),t.node(n),t.after(n+1),t.index(n)+1,e,i);if(r)return r}return null}static near(t,e=1){return this.findFrom(t,e)||this.findFrom(t,-e)||new Ne(t.node(0))}static atStart(t){return Ue(t,t,0,0,1)||new Ne(t)}static atEnd(t){return Ue(t,t,t.content.size,t.childCount,-1)||new Ne(t)}static fromJSON(t,e){if(!e||!e.type)throw new RangeError("Invalid input for Selection.fromJSON");let i=Ie[e.type];if(!i)throw new RangeError(`No selection type ${e.type} defined`);return i.fromJSON(t,e)}static jsonID(t,e){if(t in Ie)throw new RangeError("Duplicate use of selection JSON ID "+t);return Ie[t]=e,e.prototype.jsonID=t,e}getBookmark(){return _e.between(this.$anchor,this.$head).getBookmark()}}je.prototype.visible=!0;class Pe{constructor(t,e){this.$from=t,this.$to=e}}let Re=!1;function De(t){Re||t.parent.inlineContent||(Re=!0,console.warn("TextSelection endpoint not pointing into a node with inline content ("+t.parent.type.name+")"))}class _e extends je{constructor(t,e=t){De(t),De(e),super(t,e)}get $cursor(){return this.$anchor.pos==this.$head.pos?this.$head:null}map(t,e){let i=t.resolve(e.map(this.head));if(!i.parent.inlineContent)return je.near(i);let n=t.resolve(e.map(this.anchor));return new _e(n.parent.inlineContent?n:i,i)}replace(t,e=Y.empty){if(super.replace(t,e),e==Y.empty){let e=this.$from.marksAcross(this.$to);e&&t.ensureMarks(e)}}eq(t){return t instanceof _e&&t.anchor==this.anchor&&t.head==this.head}getBookmark(){return new Le(this.anchor,this.head)}toJSON(){return{type:"text",anchor:this.anchor,head:this.head}}static fromJSON(t,e){if("number"!=typeof e.anchor||"number"!=typeof e.head)throw new RangeError("Invalid input for TextSelection.fromJSON");return new _e(t.resolve(e.anchor),t.resolve(e.head))}static create(t,e,i=e){let n=t.resolve(e);return new this(n,i==e?n:t.resolve(i))}static between(t,e,i){let n=t.pos-e.pos;if(i&&!n||(i=n>=0?1:-1),!e.parent.inlineContent){let t=je.findFrom(e,i,!0)||je.findFrom(e,-i,!0);if(!t)return je.near(e,i);e=t.$head}return t.parent.inlineContent||(0==n||(t=(je.findFrom(t,-i,!0)||je.findFrom(t,i,!0)).$anchor).pos<e.pos!=n<0)&&(t=e),new _e(t,e)}}je.jsonID("text",_e);class Le{constructor(t,e){this.anchor=t,this.head=e}map(t){return new Le(t.map(this.anchor),t.map(this.head))}resolve(t){return _e.between(t.resolve(this.anchor),t.resolve(this.head))}}class Be extends je{constructor(t){let e=t.nodeAfter,i=t.node(0).resolve(t.pos+e.nodeSize);super(t,i),this.node=e}map(t,e){let{deleted:i,pos:n}=e.mapResult(this.anchor),r=t.resolve(n);return i?je.near(r):new Be(r)}content(){return new Y(U.from(this.node),0,0)}eq(t){return t instanceof Be&&t.anchor==this.anchor}toJSON(){return{type:"node",anchor:this.anchor}}getBookmark(){return new Fe(this.anchor)}static fromJSON(t,e){if("number"!=typeof e.anchor)throw new RangeError("Invalid input for NodeSelection.fromJSON");return new Be(t.resolve(e.anchor))}static create(t,e){return new Be(t.resolve(e))}static isSelectable(t){return!t.isText&&!1!==t.type.spec.selectable}}Be.prototype.visible=!1,je.jsonID("node",Be);class Fe{constructor(t){this.anchor=t}map(t){let{deleted:e,pos:i}=t.mapResult(this.anchor);return e?new Le(i,i):new Fe(i)}resolve(t){let e=t.resolve(this.anchor),i=e.nodeAfter;return i&&Be.isSelectable(i)?new Be(e):je.near(e)}}class Ne extends je{constructor(t){super(t.resolve(0),t.resolve(t.content.size))}replace(t,e=Y.empty){if(e==Y.empty){t.delete(0,t.doc.content.size);let e=je.atStart(t.doc);e.eq(t.selection)||t.setSelection(e)}else super.replace(t,e)}toJSON(){return{type:"all"}}static fromJSON(t){return new Ne(t)}map(t){return new Ne(t)}eq(t){return t instanceof Ne}getBookmark(){return We}}je.jsonID("all",Ne);const We={map(){return this},resolve:t=>new Ne(t)};function Ue(t,e,i,n,r,s=!1){if(e.inlineContent)return _e.create(t,i);for(let o=n-(r>0?0:1);r>0?o<e.childCount:o>=0;o+=r){let n=e.child(o);if(n.isAtom){if(!s&&Be.isSelectable(n))return Be.create(t,i-(r<0?n.nodeSize:0))}else{let e=Ue(t,n,i+r,r<0?n.childCount:0,r,s);if(e)return e}i+=n.nodeSize*r}return null}function Ke(t,e,i){let n=t.steps.length-1;if(n<e)return;let r,s=t.steps[n];(s instanceof ae||s instanceof le)&&(t.mapping.maps[n].forEach(((t,e,i,n)=>{null==r&&(r=n)})),t.setSelection(je.near(t.doc.resolve(r),i)))}class He extends Oe{constructor(t){super(t.doc),this.curSelectionFor=0,this.updated=0,this.meta=Object.create(null),this.time=Date.now(),this.curSelection=t.selection,this.storedMarks=t.storedMarks}get selection(){return this.curSelectionFor<this.steps.length&&(this.curSelection=this.curSelection.map(this.doc,this.mapping.slice(this.curSelectionFor)),this.curSelectionFor=this.steps.length),this.curSelection}setSelection(t){if(t.$from.doc!=this.doc)throw new RangeError("Selection passed to setSelection must point at the current document");return this.curSelection=t,this.curSelectionFor=this.steps.length,this.updated=-3&this.updated|1,this.storedMarks=null,this}get selectionSet(){return(1&this.updated)>0}setStoredMarks(t){return this.storedMarks=t,this.updated|=2,this}ensureMarks(t){return G.sameSet(this.storedMarks||this.selection.$from.marks(),t)||this.setStoredMarks(t),this}addStoredMark(t){return this.ensureMarks(t.addToSet(this.storedMarks||this.selection.$head.marks()))}removeStoredMark(t){return this.ensureMarks(t.removeFromSet(this.storedMarks||this.selection.$head.marks()))}get storedMarksSet(){return(2&this.updated)>0}addStep(t,e){super.addStep(t,e),this.updated=-3&this.updated,this.storedMarks=null}setTime(t){return this.time=t,this}replaceSelection(t){return this.selection.replace(this,t),this}replaceSelectionWith(t,e=!0){let i=this.selection;return e&&(t=t.mark(this.storedMarks||(i.empty?i.$from.marks():i.$from.marksAcross(i.$to)||G.none))),i.replaceWith(this,t),this}deleteSelection(){return this.selection.replace(this),this}insertText(t,e,i){let n=this.doc.type.schema;if(null==e)return t?this.replaceSelectionWith(n.text(t),!0):this.deleteSelection();{if(null==i&&(i=e),!t)return this.deleteRange(e,i);let r=this.storedMarks;if(!r){let t=this.doc.resolve(e);r=i==e?t.marks():t.marksAcross(this.doc.resolve(i))}return this.replaceRangeWith(e,i,n.text(t,r)),this.selection.empty||this.selection.to!=e+t.length||this.setSelection(je.near(this.selection.$to)),this}}setMeta(t,e){return this.meta["string"==typeof t?t:t.key]=e,this}getMeta(t){return this.meta["string"==typeof t?t:t.key]}get isGeneric(){for(let t in this.meta)return!1;return!0}scrollIntoView(){return this.updated|=4,this}get scrolledIntoView(){return(4&this.updated)>0}}function Ve(t,e){return e&&t?t.bind(e):t}class Ge{constructor(t,e,i){this.name=t,this.init=Ve(e.init,i),this.apply=Ve(e.apply,i)}}const Xe=[new Ge("doc",{init:t=>t.doc||t.schema.topNodeType.createAndFill(),apply:t=>t.doc}),new Ge("selection",{init:(t,e)=>t.selection||je.atStart(e.doc),apply:t=>t.selection}),new Ge("storedMarks",{init:t=>t.storedMarks||null,apply:(t,e,i,n)=>n.selection.$cursor?t.storedMarks:null}),new Ge("scrollToSelection",{init:()=>0,apply:(t,e)=>t.scrolledIntoView?e+1:e})];class Ye{constructor(t,e){this.schema=t,this.plugins=[],this.pluginsByKey=Object.create(null),this.fields=Xe.slice(),e&&e.forEach((t=>{if(this.pluginsByKey[t.key])throw new RangeError("Adding different instances of a keyed plugin ("+t.key+")");this.plugins.push(t),this.pluginsByKey[t.key]=t,t.spec.state&&this.fields.push(new Ge(t.key,t.spec.state,t))}))}}class qe{constructor(t){this.config=t}get schema(){return this.config.schema}get plugins(){return this.config.plugins}apply(t){return this.applyTransaction(t).state}filterTransaction(t,e=-1){for(let i=0;i<this.config.plugins.length;i++)if(i!=e){let e=this.config.plugins[i];if(e.spec.filterTransaction&&!e.spec.filterTransaction.call(e,t,this))return!1}return!0}applyTransaction(t){if(!this.filterTransaction(t))return{state:this,transactions:[]};let e=[t],i=this.applyInner(t),n=null;for(;;){let r=!1;for(let s=0;s<this.config.plugins.length;s++){let o=this.config.plugins[s];if(o.spec.appendTransaction){let h=n?n[s].n:0,a=n?n[s].state:this,l=h<e.length&&o.spec.appendTransaction.call(o,h?e.slice(h):e,a,i);if(l&&i.filterTransaction(l,s)){if(l.setMeta("appendedTransaction",t),!n){n=[];for(let t=0;t<this.config.plugins.length;t++)n.push(t<s?{state:i,n:e.length}:{state:this,n:0})}e.push(l),i=i.applyInner(l),r=!0}n&&(n[s]={state:i,n:e.length})}}if(!r)return{state:i,transactions:e}}}applyInner(t){if(!t.before.eq(this.doc))throw new RangeError("Applying a mismatched transaction");let e=new qe(this.config),i=this.config.fields;for(let n=0;n<i.length;n++){let r=i[n];e[r.name]=r.apply(t,this[r.name],this,e)}return e}get tr(){return new He(this)}static create(t){let e=new Ye(t.doc?t.doc.type.schema:t.schema,t.plugins),i=new qe(e);for(let n=0;n<e.fields.length;n++)i[e.fields[n].name]=e.fields[n].init(t,i);return i}reconfigure(t){let e=new Ye(this.schema,t.plugins),i=e.fields,n=new qe(e);for(let e=0;e<i.length;e++){let r=i[e].name;n[r]=this.hasOwnProperty(r)?this[r]:i[e].init(t,n)}return n}toJSON(t){let e={doc:this.doc.toJSON(),selection:this.selection.toJSON()};if(this.storedMarks&&(e.storedMarks=this.storedMarks.map((t=>t.toJSON()))),t&&"object"==typeof t)for(let i in t){if("doc"==i||"selection"==i)throw new RangeError("The JSON fields `doc` and `selection` are reserved");let n=t[i],r=n.spec.state;r&&r.toJSON&&(e[i]=r.toJSON.call(n,this[n.key]))}return e}static fromJSON(t,e,i){if(!e)throw new RangeError("Invalid input for EditorState.fromJSON");if(!t.schema)throw new RangeError("Required config field 'schema' missing");let n=new Ye(t.schema,t.plugins),r=new qe(n);return n.fields.forEach((n=>{if("doc"==n.name)r.doc=dt.fromJSON(t.schema,e.doc);else if("selection"==n.name)r.selection=je.fromJSON(r.doc,e.selection);else if("storedMarks"==n.name)e.storedMarks&&(r.storedMarks=e.storedMarks.map(t.schema.markFromJSON));else{if(i)for(let s in i){let o=i[s],h=o.spec.state;if(o.key==n.name&&h&&h.fromJSON&&Object.prototype.hasOwnProperty.call(e,s))return void(r[n.name]=h.fromJSON.call(o,t,e[s],r))}r[n.name]=n.init(t,r)}})),r}}function Je(t,e,i){for(let n in t){let r=t[n];r instanceof Function?r=r.bind(e):"handleDOMEvents"==n&&(r=Je(r,e,{})),i[n]=r}return i}class Qe{constructor(t){var e;this.spec=t,this.props={},t.props&&Je(t.props,this,this.props),this.key=t.key?t.key.key:(e="plugin")in Ze?e+"$"+ ++Ze[e]:(Ze[e]=0,e+"$")}getState(t){return t[this.key]}}const Ze=Object.create(null),ti=function(t){for(var e=0;;e++)if(!(t=t.previousSibling))return e},ei=function(t){let e=t.assignedSlot||t.parentNode;return e&&11==e.nodeType?e.host:e};let ii=null;const ni=function(t,e,i){let n=ii||(ii=document.createRange());return n.setEnd(t,null==i?t.nodeValue.length:i),n.setStart(t,e||0),n},ri=function(t,e,i,n){return i&&(oi(t,e,i,n,-1)||oi(t,e,i,n,1))},si=/^(img|br|input|textarea|hr)$/i;function oi(t,e,i,n,r){for(var s;;){if(t==i&&e==n)return!0;if(e==(r<0?0:hi(t))){let i=t.parentNode;if(!i||1!=i.nodeType||ai(t)||si.test(t.nodeName)||"false"==t.contentEditable)return!1;e=ti(t)+(r<0?0:1),t=i}else{if(1!=t.nodeType)return!1;{let i=t.childNodes[e+(r<0?-1:0)];if(1==i.nodeType&&"false"==i.contentEditable){if(!(null===(s=i.pmViewDesc)||void 0===s?void 0:s.ignoreForSelection))return!1;e+=r}else t=i,e=r<0?hi(t):0}}}}function hi(t){return 3==t.nodeType?t.nodeValue.length:t.childNodes.length}function ai(t){let e;for(let i=t;i&&!(e=i.pmViewDesc);i=i.parentNode);return e&&e.node&&e.node.isBlock&&(e.dom==t||e.contentDOM==t)}const li=function(t){return t.focusNode&&ri(t.focusNode,t.focusOffset,t.anchorNode,t.anchorOffset)};function ui(t,e){let i=document.createEvent("Event");return i.initEvent("keydown",!0,!0),i.keyCode=t,i.key=i.code=e,i}const ci="undefined"!=typeof navigator?navigator:null,fi="undefined"!=typeof document?document:null,di=ci&&ci.userAgent||"",pi=/Edge\/(\d+)/.exec(di),gi=/MSIE \d/.exec(di),mi=/Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(di),wi=!!(gi||mi||pi),vi=gi?document.documentMode:mi?+mi[1]:pi?+pi[1]:0,yi=!wi&&/gecko\/(\d+)/i.test(di),bi=!wi&&/Chrome\/(\d+)/.exec(di),ki=!!bi,Mi=bi?+bi[1]:0,Si=!wi&&!!ci&&/Apple Computer/.test(ci.vendor),xi=Si&&(/Mobile\/\w+/.test(di)||!!ci&&ci.maxTouchPoints>2),Ai=xi||!!ci&&/Mac/.test(ci.platform),$i=!!ci&&/Win/.test(ci.platform),zi=/Android \d/.test(di),Ci=!!fi&&"webkitFontSmoothing"in fi.documentElement.style,Ti=Ci?+(/\bAppleWebKit\/(\d+)/.exec(navigator.userAgent)||[0,0])[1]:0;function Ei(t){let e=t.defaultView&&t.defaultView.visualViewport;return e?{left:0,right:e.width,top:0,bottom:e.height}:{left:0,right:t.documentElement.clientWidth,top:0,bottom:t.documentElement.clientHeight}}function Oi(t,e){return"number"==typeof t?t:t[e]}function Ii(t){let e=t.getBoundingClientRect();return{left:e.left,right:e.left+t.clientWidth*(e.width/t.offsetWidth||1),top:e.top,bottom:e.top+t.clientHeight*(e.height/t.offsetHeight||1)}}function ji(t,e,i){if(!Ni(e)&&0==e.left)return;let n=t.someProp("scrollThreshold")||0,r=t.someProp("scrollMargin")||5,s=t.dom.ownerDocument;for(let o=i||t.dom;o;){if(1!=o.nodeType){o=ei(o);continue}let t=o,i=t==s.body,h=i?Ei(s):Ii(t),a=0,l=0;if(e.top<h.top+Oi(n,"top")?l=-(h.top-e.top+Oi(r,"top")):e.bottom>h.bottom-Oi(n,"bottom")&&(l=e.bottom-e.top>h.bottom-h.top?e.top+Oi(r,"top")-h.top:e.bottom-h.bottom+Oi(r,"bottom")),e.left<h.left+Oi(n,"left")?a=-(h.left-e.left+Oi(r,"left")):e.right>h.right-Oi(n,"right")&&(a=e.right-h.right+Oi(r,"right")),a||l)if(i)s.defaultView.scrollBy(a,l);else{let i=t.scrollLeft,n=t.scrollTop;l&&(t.scrollTop+=l),a&&(t.scrollLeft+=a);let r=t.scrollLeft-i,s=t.scrollTop-n;e={left:e.left-r,top:e.top-s,right:e.right-r,bottom:e.bottom-s}}let u=i?"fixed":getComputedStyle(o).position;if(/^(fixed|sticky)$/.test(u))break;o="absolute"==u?o.offsetParent:ei(o)}}function Pi(t){let e=[],i=t.ownerDocument;for(let n=t;n&&(e.push({dom:n,top:n.scrollTop,left:n.scrollLeft}),t!=i);n=ei(n));return e}function Ri(t,e){for(let i=0;i<t.length;i++){let{dom:n,top:r,left:s}=t[i];n.scrollTop!=r+e&&(n.scrollTop=r+e),n.scrollLeft!=s&&(n.scrollLeft=s)}}let Di=null;function _i(t,e){let i,n,r,s,o=2e8,h=0,a=e.top,l=e.top;for(let u=t.firstChild,c=0;u;u=u.nextSibling,c++){let t;if(1==u.nodeType)t=u.getClientRects();else{if(3!=u.nodeType)continue;t=ni(u).getClientRects()}for(let f=0;f<t.length;f++){let d=t[f];if(d.top<=a&&d.bottom>=l){a=Math.max(d.bottom,a),l=Math.min(d.top,l);let t=d.left>e.left?d.left-e.left:d.right<e.left?e.left-d.right:0;if(t<o){i=u,o=t,n=t&&3==i.nodeType?{left:d.right<e.left?d.right:d.left,top:e.top}:e,1==u.nodeType&&t&&(h=c+(e.left>=(d.left+d.right)/2?1:0));continue}}else d.top>e.top&&!r&&d.left<=e.left&&d.right>=e.left&&(r=u,s={left:Math.max(d.left,Math.min(d.right,e.left)),top:d.top});!i&&(e.left>=d.right&&e.top>=d.top||e.left>=d.left&&e.top>=d.bottom)&&(h=c+1)}}return!i&&r&&(i=r,n=s,o=0),i&&3==i.nodeType?function(t,e){let i,n=t.nodeValue.length,r=document.createRange();for(let s=0;s<n;s++){r.setEnd(t,s+1),r.setStart(t,s);let n=Wi(r,1);if(n.top!=n.bottom&&Li(e,n)){i={node:t,offset:s+(e.left>=(n.left+n.right)/2?1:0)};break}}return r.detach(),i||{node:t,offset:0}}(i,n):!i||o&&1==i.nodeType?{node:t,offset:h}:_i(i,n)}function Li(t,e){return t.left>=e.left-1&&t.left<=e.right+1&&t.top>=e.top-1&&t.top<=e.bottom+1}function Bi(t,e,i){let n=t.childNodes.length;if(n&&i.top<i.bottom)for(let r=Math.max(0,Math.min(n-1,Math.floor(n*(e.top-i.top)/(i.bottom-i.top))-2)),s=r;;){let i=t.childNodes[s];if(1==i.nodeType){let t=i.getClientRects();for(let n=0;n<t.length;n++){let r=t[n];if(Li(e,r))return Bi(i,e,r)}}if((s=(s+1)%n)==r)break}return t}function Fi(t,e){let i,n=t.dom.ownerDocument,r=0,s=function(t,e,i){if(t.caretPositionFromPoint)try{let n=t.caretPositionFromPoint(e,i);if(n)return{node:n.offsetNode,offset:Math.min(hi(n.offsetNode),n.offset)}}catch(t){}if(t.caretRangeFromPoint){let n=t.caretRangeFromPoint(e,i);if(n)return{node:n.startContainer,offset:Math.min(hi(n.startContainer),n.startOffset)}}}(n,e.left,e.top);s&&({node:i,offset:r}=s);let o,h=(t.root.elementFromPoint?t.root:n).elementFromPoint(e.left,e.top);if(!h||!t.dom.contains(1!=h.nodeType?h.parentNode:h)){let i=t.dom.getBoundingClientRect();if(!Li(e,i))return null;if(h=Bi(t.dom,e,i),!h)return null}if(Si)for(let t=h;i&&t;t=ei(t))t.draggable&&(i=void 0);if(h=function(t,e){let i=t.parentNode;return i&&/^li$/i.test(i.nodeName)&&e.left<t.getBoundingClientRect().left?i:t}(h,e),i){if(yi&&1==i.nodeType&&(r=Math.min(r,i.childNodes.length),r<i.childNodes.length)){let t,n=i.childNodes[r];"IMG"==n.nodeName&&(t=n.getBoundingClientRect()).right<=e.left&&t.bottom>e.top&&r++}let n;Ci&&r&&1==i.nodeType&&1==(n=i.childNodes[r-1]).nodeType&&"false"==n.contentEditable&&n.getBoundingClientRect().top>=e.top&&r--,i==t.dom&&r==i.childNodes.length-1&&1==i.lastChild.nodeType&&e.top>i.lastChild.getBoundingClientRect().bottom?o=t.state.doc.content.size:0!=r&&1==i.nodeType&&"BR"==i.childNodes[r-1].nodeName||(o=function(t,e,i,n){let r=-1;for(let i=e,s=!1;i!=t.dom;){let e,o=t.docView.nearestDesc(i,!0);if(!o)return null;if(1==o.dom.nodeType&&(o.node.isBlock&&o.parent||!o.contentDOM)&&((e=o.dom.getBoundingClientRect()).width||e.height)&&(o.node.isBlock&&o.parent&&!/^T(R|BODY|HEAD|FOOT)$/.test(o.dom.nodeName)&&(!s&&e.left>n.left||e.top>n.top?r=o.posBefore:(!s&&e.right<n.left||e.bottom<n.top)&&(r=o.posAfter),s=!0),!o.contentDOM&&r<0&&!o.node.isText))return(o.node.isBlock?n.top<(e.top+e.bottom)/2:n.left<(e.left+e.right)/2)?o.posBefore:o.posAfter;i=o.dom.parentNode}return r>-1?r:t.docView.posFromDOM(e,i,-1)}(t,i,r,e))}null==o&&(o=function(t,e,i){let{node:n,offset:r}=_i(e,i),s=-1;if(1==n.nodeType&&!n.firstChild){let t=n.getBoundingClientRect();s=t.left!=t.right&&i.left>(t.left+t.right)/2?1:-1}return t.docView.posFromDOM(n,r,s)}(t,h,e));let a=t.docView.nearestDesc(h,!0);return{pos:o,inside:a?a.posAtStart-a.border:-1}}function Ni(t){return t.top<t.bottom||t.left<t.right}function Wi(t,e){let i=t.getClientRects();if(i.length){let t=i[e<0?0:i.length-1];if(Ni(t))return t}return Array.prototype.find.call(i,Ni)||t.getBoundingClientRect()}const Ui=/[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/;function Ki(t,e,i){let{node:n,offset:r,atom:s}=t.docView.domFromPos(e,i<0?-1:1),o=Ci||yi;if(3==n.nodeType){if(!o||!Ui.test(n.nodeValue)&&(i<0?r:r!=n.nodeValue.length)){let t=r,e=r,s=i<0?1:-1;return i<0&&!r?(e++,s=-1):i>=0&&r==n.nodeValue.length?(t--,s=1):i<0?t--:e++,Hi(Wi(ni(n,t,e),s),s<0)}{let t=Wi(ni(n,r,r),i);if(yi&&r&&/\s/.test(n.nodeValue[r-1])&&r<n.nodeValue.length){let e=Wi(ni(n,r-1,r-1),-1);if(e.top==t.top){let i=Wi(ni(n,r,r+1),-1);if(i.top!=t.top)return Hi(i,i.left<e.left)}}return t}}if(!t.state.doc.resolve(e-(s||0)).parent.inlineContent){if(null==s&&r&&(i<0||r==hi(n))){let t=n.childNodes[r-1];if(1==t.nodeType)return Vi(t.getBoundingClientRect(),!1)}if(null==s&&r<hi(n)){let t=n.childNodes[r];if(1==t.nodeType)return Vi(t.getBoundingClientRect(),!0)}return Vi(n.getBoundingClientRect(),i>=0)}if(null==s&&r&&(i<0||r==hi(n))){let t=n.childNodes[r-1],e=3==t.nodeType?ni(t,hi(t)-(o?0:1)):1!=t.nodeType||"BR"==t.nodeName&&t.nextSibling?null:t;if(e)return Hi(Wi(e,1),!1)}if(null==s&&r<hi(n)){let t=n.childNodes[r];for(;t.pmViewDesc&&t.pmViewDesc.ignoreForCoords;)t=t.nextSibling;let e=t?3==t.nodeType?ni(t,0,o?0:1):1==t.nodeType?t:null:null;if(e)return Hi(Wi(e,-1),!0)}return Hi(Wi(3==n.nodeType?ni(n):n,-i),i>=0)}function Hi(t,e){if(0==t.width)return t;let i=e?t.left:t.right;return{top:t.top,bottom:t.bottom,left:i,right:i}}function Vi(t,e){if(0==t.height)return t;let i=e?t.top:t.bottom;return{top:i,bottom:i,left:t.left,right:t.right}}function Gi(t,e,i){let n=t.state,r=t.root.activeElement;n!=e&&t.updateState(e),r!=t.dom&&t.focus();try{return i()}finally{n!=e&&t.updateState(n),r!=t.dom&&r&&r.focus()}}const Xi=/[\u0590-\u08ac]/;let Yi=null,qi=null,Ji=!1;class Qi{constructor(t,e,i,n){this.parent=t,this.children=e,this.dom=i,this.contentDOM=n,this.dirty=0,i.pmViewDesc=this}matchesWidget(t){return!1}matchesMark(t){return!1}matchesNode(t,e,i){return!1}matchesHack(t){return!1}parseRule(t){return null}stopEvent(t){return!1}get size(){let t=0;for(let e=0;e<this.children.length;e++)t+=this.children[e].size;return t}get border(){return 0}destroy(){this.parent=void 0,this.dom.pmViewDesc==this&&(this.dom.pmViewDesc=void 0);for(let t=0;t<this.children.length;t++)this.children[t].destroy()}posBeforeChild(t){for(let e=0,i=this.posAtStart;;e++){let n=this.children[e];if(n==t)return i;i+=n.size}}get posBefore(){return this.parent.posBeforeChild(this)}get posAtStart(){return this.parent?this.parent.posBeforeChild(this)+this.border:0}get posAfter(){return this.posBefore+this.size}get posAtEnd(){return this.posAtStart+this.size-2*this.border}localPosFromDOM(t,e,i){if(this.contentDOM&&this.contentDOM.contains(1==t.nodeType?t:t.parentNode)){if(i<0){let i,n;if(t==this.contentDOM)i=t.childNodes[e-1];else{for(;t.parentNode!=this.contentDOM;)t=t.parentNode;i=t.previousSibling}for(;i&&(!(n=i.pmViewDesc)||n.parent!=this);)i=i.previousSibling;return i?this.posBeforeChild(n)+n.size:this.posAtStart}{let i,n;if(t==this.contentDOM)i=t.childNodes[e];else{for(;t.parentNode!=this.contentDOM;)t=t.parentNode;i=t.nextSibling}for(;i&&(!(n=i.pmViewDesc)||n.parent!=this);)i=i.nextSibling;return i?this.posBeforeChild(n):this.posAtEnd}}let n;if(t==this.dom&&this.contentDOM)n=e>ti(this.contentDOM);else if(this.contentDOM&&this.contentDOM!=this.dom&&this.dom.contains(this.contentDOM))n=2&t.compareDocumentPosition(this.contentDOM);else if(this.dom.firstChild){if(0==e)for(let e=t;;e=e.parentNode){if(e==this.dom){n=!1;break}if(e.previousSibling)break}if(null==n&&e==t.childNodes.length)for(let e=t;;e=e.parentNode){if(e==this.dom){n=!0;break}if(e.nextSibling)break}}return(null==n?i>0:n)?this.posAtEnd:this.posAtStart}nearestDesc(t,e=!1){for(let i=!0,n=t;n;n=n.parentNode){let r,s=this.getDesc(n);if(s&&(!e||s.node)){if(!i||!(r=s.nodeDOM)||(1==r.nodeType?r.contains(1==t.nodeType?t:t.parentNode):r==t))return s;i=!1}}}getDesc(t){let e=t.pmViewDesc;for(let t=e;t;t=t.parent)if(t==this)return e}posFromDOM(t,e,i){for(let n=t;n;n=n.parentNode){let r=this.getDesc(n);if(r)return r.localPosFromDOM(t,e,i)}return-1}descAt(t){for(let e=0,i=0;e<this.children.length;e++){let n=this.children[e],r=i+n.size;if(i==t&&r!=i){for(;!n.border&&n.children.length;)for(let t=0;t<n.children.length;t++){let e=n.children[t];if(e.size){n=e;break}}return n}if(t<r)return n.descAt(t-i-n.border);i=r}}domFromPos(t,e){if(!this.contentDOM)return{node:this.dom,offset:0,atom:t+1};let i=0,n=0;for(let e=0;i<this.children.length;i++){let r=this.children[i],s=e+r.size;if(s>t||r instanceof on){n=t-e;break}e=s}if(n)return this.children[i].domFromPos(n-this.children[i].border,e);for(let t;i&&!(t=this.children[i-1]).size&&t instanceof Zi&&t.side>=0;i--);if(e<=0){let t,n=!0;for(;t=i?this.children[i-1]:null,t&&t.dom.parentNode!=this.contentDOM;i--,n=!1);return t&&e&&n&&!t.border&&!t.domAtom?t.domFromPos(t.size,e):{node:this.contentDOM,offset:t?ti(t.dom)+1:0}}{let t,n=!0;for(;t=i<this.children.length?this.children[i]:null,t&&t.dom.parentNode!=this.contentDOM;i++,n=!1);return t&&n&&!t.border&&!t.domAtom?t.domFromPos(0,e):{node:this.contentDOM,offset:t?ti(t.dom):this.contentDOM.childNodes.length}}}parseRange(t,e,i=0){if(0==this.children.length)return{node:this.contentDOM,from:t,to:e,fromOffset:0,toOffset:this.contentDOM.childNodes.length};let n=-1,r=-1;for(let s=i,o=0;;o++){let i=this.children[o],h=s+i.size;if(-1==n&&t<=h){let r=s+i.border;if(t>=r&&e<=h-i.border&&i.node&&i.contentDOM&&this.contentDOM.contains(i.contentDOM))return i.parseRange(t,e,r);t=s;for(let e=o;e>0;e--){let i=this.children[e-1];if(i.size&&i.dom.parentNode==this.contentDOM&&!i.emptyChildAt(1)){n=ti(i.dom)+1;break}t-=i.size}-1==n&&(n=0)}if(n>-1&&(h>e||o==this.children.length-1)){e=h;for(let t=o+1;t<this.children.length;t++){let i=this.children[t];if(i.size&&i.dom.parentNode==this.contentDOM&&!i.emptyChildAt(-1)){r=ti(i.dom);break}e+=i.size}-1==r&&(r=this.contentDOM.childNodes.length);break}s=h}return{node:this.contentDOM,from:t,to:e,fromOffset:n,toOffset:r}}emptyChildAt(t){if(this.border||!this.contentDOM||!this.children.length)return!1;let e=this.children[t<0?0:this.children.length-1];return 0==e.size||e.emptyChildAt(t)}domAfterPos(t){let{node:e,offset:i}=this.domFromPos(t,0);if(1!=e.nodeType||i==e.childNodes.length)throw new RangeError("No node after pos "+t);return e.childNodes[i]}setSelection(t,e,i,n=!1){let r=Math.min(t,e),s=Math.max(t,e);for(let o=0,h=0;o<this.children.length;o++){let a=this.children[o],l=h+a.size;if(r>h&&s<l)return a.setSelection(t-h-a.border,e-h-a.border,i,n);h=l}let o=this.domFromPos(t,t?-1:1),h=e==t?o:this.domFromPos(e,e?-1:1),a=i.root.getSelection(),l=i.domSelectionRange(),u=!1;if((yi||Si)&&t==e){let{node:t,offset:e}=o;if(3==t.nodeType){if(u=!(!e||"\n"!=t.nodeValue[e-1]),u&&e==t.nodeValue.length)for(let e,i=t;i;i=i.parentNode){if(e=i.nextSibling){"BR"==e.nodeName&&(o=h={node:e.parentNode,offset:ti(e)+1});break}let t=i.pmViewDesc;if(t&&t.node&&t.node.isBlock)break}}else{let i=t.childNodes[e-1];u=i&&("BR"==i.nodeName||"false"==i.contentEditable)}}if(yi&&l.focusNode&&l.focusNode!=h.node&&1==l.focusNode.nodeType){let t=l.focusNode.childNodes[l.focusOffset];t&&"false"==t.contentEditable&&(n=!0)}if(!(n||u&&Si)&&ri(o.node,o.offset,l.anchorNode,l.anchorOffset)&&ri(h.node,h.offset,l.focusNode,l.focusOffset))return;let c=!1;if((a.extend||t==e)&&(!u||!yi)){a.collapse(o.node,o.offset);try{t!=e&&a.extend(h.node,h.offset),c=!0}catch(t){}}if(!c){if(t>e){let t=o;o=h,h=t}let i=document.createRange();i.setEnd(h.node,h.offset),i.setStart(o.node,o.offset),a.removeAllRanges(),a.addRange(i)}}ignoreMutation(t){return!this.contentDOM&&"selection"!=t.type}get contentLost(){return this.contentDOM&&this.contentDOM!=this.dom&&!this.dom.contains(this.contentDOM)}markDirty(t,e){for(let i=0,n=0;n<this.children.length;n++){let r=this.children[n],s=i+r.size;if(i==s?t<=s&&e>=i:t<s&&e>i){let n=i+r.border,o=s-r.border;if(t>=n&&e<=o)return this.dirty=t==i||e==s?2:1,void(t!=n||e!=o||!r.contentLost&&r.dom.parentNode==this.contentDOM?r.markDirty(t-n,e-n):r.dirty=3);r.dirty=r.dom!=r.contentDOM||r.dom.parentNode!=this.contentDOM||r.children.length?3:2}i=s}this.dirty=2}markParentsDirty(){let t=1;for(let e=this.parent;e;e=e.parent,t++){let i=1==t?2:1;e.dirty<i&&(e.dirty=i)}}get domAtom(){return!1}get ignoreForCoords(){return!1}get ignoreForSelection(){return!1}isText(t){return!1}}class Zi extends Qi{constructor(t,e,i,n){let r,s=e.type.toDOM;if("function"==typeof s&&(s=s(i,(()=>r?r.parent?r.parent.posBeforeChild(r):void 0:n))),!e.type.spec.raw){if(1!=s.nodeType){let t=document.createElement("span");t.appendChild(s),s=t}s.contentEditable="false",s.classList.add("ProseMirror-widget")}super(t,[],s,null),this.widget=e,this.widget=e,r=this}matchesWidget(t){return 0==this.dirty&&t.type.eq(this.widget.type)}parseRule(){return{ignore:!0}}stopEvent(t){let e=this.widget.spec.stopEvent;return!!e&&e(t)}ignoreMutation(t){return"selection"!=t.type||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 tn extends Qi{constructor(t,e,i,n){super(t,[],e,null),this.textDOM=i,this.text=n}get size(){return this.text.length}localPosFromDOM(t,e){return t!=this.textDOM?this.posAtStart+(e?this.size:0):this.posAtStart+e}domFromPos(t){return{node:this.textDOM,offset:t}}ignoreMutation(t){return"characterData"===t.type&&t.target.nodeValue==t.oldValue}}class en extends Qi{constructor(t,e,i,n,r){super(t,[],i,n),this.mark=e,this.spec=r}static create(t,e,i,n){let r=n.nodeViews[e.type.name],s=r&&r(e,n,i);return s&&s.dom||(s=Kt.renderSpec(document,e.type.spec.toDOM(e,i),null,e.attrs)),new en(t,e,s.dom,s.contentDOM||s.dom,s)}parseRule(){return 3&this.dirty||this.mark.type.spec.reparseInView?null:{mark:this.mark.type.name,attrs:this.mark.attrs,contentElement:this.contentDOM}}matchesMark(t){return 3!=this.dirty&&this.mark.eq(t)}markDirty(t,e){if(super.markDirty(t,e),0!=this.dirty){let t=this.parent;for(;!t.node;)t=t.parent;t.dirty<this.dirty&&(t.dirty=this.dirty),this.dirty=0}}slice(t,e,i){let n=en.create(this.parent,this.mark,!0,i),r=this.children,s=this.size;e<s&&(r=yn(r,e,s,i)),t>0&&(r=yn(r,0,t,i));for(let t=0;t<r.length;t++)r[t].parent=n;return n.children=r,n}ignoreMutation(t){return this.spec.ignoreMutation?this.spec.ignoreMutation(t):super.ignoreMutation(t)}destroy(){this.spec.destroy&&this.spec.destroy(),super.destroy()}}class nn extends Qi{constructor(t,e,i,n,r,s,o){super(t,[],r,s),this.node=e,this.outerDeco=i,this.innerDeco=n,this.nodeDOM=o}static create(t,e,i,n,r,s){let o,h=r.nodeViews[e.type.name],a=h&&h(e,r,(()=>o?o.parent?o.parent.posBeforeChild(o):void 0:s),i,n),l=a&&a.dom,u=a&&a.contentDOM;if(e.isText)if(l){if(3!=l.nodeType)throw new RangeError("Text must be rendered as a DOM text node")}else l=document.createTextNode(e.text);else if(!l){let t=Kt.renderSpec(document,e.type.spec.toDOM(e),null,e.attrs);({dom:l,contentDOM:u}=t)}u||e.isText||"BR"==l.nodeName||(l.hasAttribute("contenteditable")||(l.contentEditable="false"),e.type.spec.draggable&&(l.draggable=!0));let c=l;return l=pn(l,i,e),a?o=new hn(t,e,i,n,l,u||null,c,a):e.isText?new sn(t,e,i,n,l,c):new nn(t,e,i,n,l,u||null,c)}parseRule(t){if(this.node.type.spec.reparseInView)return null;let e={node:this.node.type.name,attrs:this.node.attrs};if("pre"==this.node.type.whitespace&&(e.preserveWhitespace="full"),this.contentDOM)if(this.contentLost){for(let t=this.children.length-1;t>=0;t--){let i=this.children[t];if(this.dom.contains(i.dom.parentNode)){e.contentElement=i.dom.parentNode;break}}if(!e.contentElement){let i=t&&t.find((e=>1==e.nodeType&&t.indexOf(e.parentNode)<0&&this.dom.contains(e)));i?e.contentElement=i:e.getContent=()=>U.empty}}else e.contentElement=this.contentDOM;else e.getContent=()=>this.node.content;return e}matchesNode(t,e,i){return 0==this.dirty&&t.eq(this.node)&&gn(e,this.outerDeco)&&i.eq(this.innerDeco)}get size(){return this.node.nodeSize}get border(){return this.node.isLeaf?0:1}updateChildren(t,e){let i=this.node.inlineContent,n=e,r=t.composing?this.localCompositionInfo(t,e):null,s=r&&r.pos>-1?r:null,o=r&&r.pos<0,h=new wn(this,s&&s.node,t);!function(t,e,i,n){let r=e.locals(t),s=0;if(0==r.length){for(let i=0;i<t.childCount;i++){let o=t.child(i);n(o,r,e.forChild(s,o),i),s+=o.nodeSize}return}let o=0,h=[],a=null;for(let l=0;;){let u,c,f,d;for(;o<r.length&&r[o].to==s;){let t=r[o++];t.widget&&(u?(c||(c=[u])).push(t):u=t)}if(u)if(c){c.sort(vn);for(let t=0;t<c.length;t++)i(c[t],l,!!a)}else i(u,l,!!a);if(a)d=-1,f=a,a=null;else{if(!(l<t.childCount))break;d=l,f=t.child(l++)}for(let t=0;t<h.length;t++)h[t].to<=s&&h.splice(t--,1);for(;o<r.length&&r[o].from<=s&&r[o].to>s;)h.push(r[o++]);let p=s+f.nodeSize;if(f.isText){let t=p;o<r.length&&r[o].from<t&&(t=r[o].from);for(let e=0;e<h.length;e++)h[e].to<t&&(t=h[e].to);t<p&&(a=f.cut(t-s),f=f.cut(0,t-s),p=t,d=-1)}else for(;o<r.length&&r[o].to<p;)o++;n(f,f.isInline&&!f.isLeaf?h.filter((t=>!t.inline)):h.slice(),e.forChild(s,f),d),s=p}}(this.node,this.innerDeco,((e,r,s)=>{e.spec.marks?h.syncToMarks(e.spec.marks,i,t,r):e.type.side>=0&&!s&&h.syncToMarks(r==this.node.childCount?G.none:this.node.child(r).marks,i,t,r),h.placeWidget(e,t,n)}),((e,s,a,l)=>{let u;h.syncToMarks(e.marks,i,t,l),h.findNodeMatch(e,s,a,l)||o&&t.state.selection.from>n&&t.state.selection.to<n+e.nodeSize&&(u=h.findIndexWithChild(r.node))>-1&&h.updateNodeAt(e,s,a,u,t)||h.updateNextNode(e,s,a,t,l,n)||h.addNode(e,s,a,t,n),n+=e.nodeSize})),h.syncToMarks([],i,t,0),this.node.isTextblock&&h.addTextblockHacks(),h.destroyRest(),(h.changed||2==this.dirty)&&(s&&this.protectLocalComposition(t,s),an(this.contentDOM,this.children,t),xi&&function(t){if("UL"==t.nodeName||"OL"==t.nodeName){let e=t.style.cssText;t.style.cssText=e+"; list-style: square !important",window.getComputedStyle(t),t.style.cssText=e}}(this.dom))}localCompositionInfo(t,e){let{from:i,to:n}=t.state.selection;if(!(t.state.selection instanceof _e)||i<e||n>e+this.node.content.size)return null;let r=t.input.compositionNode;if(!r||!this.dom.contains(r.parentNode))return null;if(this.node.inlineContent){let t=r.nodeValue,s=function(t,e,i,n){for(let r=0,s=0;r<t.childCount&&s<=n;){let o=t.child(r++),h=s;if(s+=o.nodeSize,!o.isText)continue;let a=o.text;for(;r<t.childCount;){let e=t.child(r++);if(s+=e.nodeSize,!e.isText)break;a+=e.text}if(s>=i){if(s>=n&&a.slice(n-e.length-h,n-h)==e)return n-e.length;let t=h<n?a.lastIndexOf(e,n-h-1):-1;if(t>=0&&t+e.length+h>=i)return h+t;if(i==n&&a.length>=n+e.length-h&&a.slice(n-h,n-h+e.length)==e)return n}}return-1}(this.node.content,t,i-e,n-e);return s<0?null:{node:r,pos:s,text:t}}return{node:r,pos:-1,text:""}}protectLocalComposition(t,{node:e,pos:i,text:n}){if(this.getDesc(e))return;let r=e;for(;r.parentNode!=this.contentDOM;r=r.parentNode){for(;r.previousSibling;)r.parentNode.removeChild(r.previousSibling);for(;r.nextSibling;)r.parentNode.removeChild(r.nextSibling);r.pmViewDesc&&(r.pmViewDesc=void 0)}let s=new tn(this,r,e,n);t.input.compositionNodes.push(s),this.children=yn(this.children,i,i+n.length,t,s)}update(t,e,i,n){return!(3==this.dirty||!t.sameMarkup(this.node)||(this.updateInner(t,e,i,n),0))}updateInner(t,e,i,n){this.updateOuterDeco(e),this.node=t,this.innerDeco=i,this.contentDOM&&this.updateChildren(n,this.posAtStart),this.dirty=0}updateOuterDeco(t){if(gn(t,this.outerDeco))return;let e=1!=this.nodeDOM.nodeType,i=this.dom;this.dom=fn(this.dom,this.nodeDOM,cn(this.outerDeco,this.node,e),cn(t,this.node,e)),this.dom!=i&&(i.pmViewDesc=void 0,this.dom.pmViewDesc=this),this.outerDeco=t}selectNode(){1==this.nodeDOM.nodeType&&(this.nodeDOM.classList.add("ProseMirror-selectednode"),!this.contentDOM&&this.node.type.spec.draggable||(this.nodeDOM.draggable=!0))}deselectNode(){1==this.nodeDOM.nodeType&&(this.nodeDOM.classList.remove("ProseMirror-selectednode"),!this.contentDOM&&this.node.type.spec.draggable||this.nodeDOM.removeAttribute("draggable"))}get domAtom(){return this.node.isAtom}}function rn(t,e,i,n,r){pn(n,e,t);let s=new nn(void 0,t,e,i,n,n,n);return s.contentDOM&&s.updateChildren(r,0),s}class sn extends nn{constructor(t,e,i,n,r,s){super(t,e,i,n,r,null,s)}parseRule(){let t=this.nodeDOM.parentNode;for(;t&&t!=this.dom&&!t.pmIsDeco;)t=t.parentNode;return{skip:t||!0}}update(t,e,i,n){return!(3==this.dirty||0!=this.dirty&&!this.inParent()||!t.sameMarkup(this.node)||(this.updateOuterDeco(e),0==this.dirty&&t.text==this.node.text||t.text==this.nodeDOM.nodeValue||(this.nodeDOM.nodeValue=t.text,n.trackWrites==this.nodeDOM&&(n.trackWrites=null)),this.node=t,this.dirty=0,0))}inParent(){let t=this.parent.contentDOM;for(let e=this.nodeDOM;e;e=e.parentNode)if(e==t)return!0;return!1}domFromPos(t){return{node:this.nodeDOM,offset:t}}localPosFromDOM(t,e,i){return t==this.nodeDOM?this.posAtStart+Math.min(e,this.node.text.length):super.localPosFromDOM(t,e,i)}ignoreMutation(t){return"characterData"!=t.type&&"selection"!=t.type}slice(t,e,i){let n=this.node.cut(t,e),r=document.createTextNode(n.text);return new sn(this.parent,n,this.outerDeco,this.innerDeco,r,r)}markDirty(t,e){super.markDirty(t,e),this.dom==this.nodeDOM||0!=t&&e!=this.nodeDOM.nodeValue.length||(this.dirty=3)}get domAtom(){return!1}isText(t){return this.node.text==t}}class on extends Qi{parseRule(){return{ignore:!0}}matchesHack(t){return 0==this.dirty&&this.dom.nodeName==t}get domAtom(){return!0}get ignoreForCoords(){return"IMG"==this.dom.nodeName}}class hn extends nn{constructor(t,e,i,n,r,s,o,h){super(t,e,i,n,r,s,o),this.spec=h}update(t,e,i,n){if(3==this.dirty)return!1;if(this.spec.update&&(this.node.type==t.type||this.spec.multiType)){let r=this.spec.update(t,e,i);return r&&this.updateInner(t,e,i,n),r}return!(!this.contentDOM&&!t.isLeaf)&&super.update(t,e,i,n)}selectNode(){this.spec.selectNode?this.spec.selectNode():super.selectNode()}deselectNode(){this.spec.deselectNode?this.spec.deselectNode():super.deselectNode()}setSelection(t,e,i,n){this.spec.setSelection?this.spec.setSelection(t,e,i.root):super.setSelection(t,e,i,n)}destroy(){this.spec.destroy&&this.spec.destroy(),super.destroy()}stopEvent(t){return!!this.spec.stopEvent&&this.spec.stopEvent(t)}ignoreMutation(t){return this.spec.ignoreMutation?this.spec.ignoreMutation(t):super.ignoreMutation(t)}}function an(t,e,i){let n=t.firstChild,r=!1;for(let s=0;s<e.length;s++){let o=e[s],h=o.dom;if(h.parentNode==t){for(;h!=n;)n=mn(n),r=!0;n=n.nextSibling}else r=!0,t.insertBefore(h,n);if(o instanceof en){let e=n?n.previousSibling:t.lastChild;an(o.contentDOM,o.children,i),n=e?e.nextSibling:t.firstChild}}for(;n;)n=mn(n),r=!0;r&&i.trackWrites==t&&(i.trackWrites=null)}const ln=function(t){t&&(this.nodeName=t)};ln.prototype=Object.create(null);const un=[new ln];function cn(t,e,i){if(0==t.length)return un;let n=i?un[0]:new ln,r=[n];for(let s=0;s<t.length;s++){let o=t[s].type.attrs;if(o){o.nodeName&&r.push(n=new ln(o.nodeName));for(let t in o){let s=o[t];null!=s&&(i&&1==r.length&&r.push(n=new ln(e.isInline?"span":"div")),"class"==t?n.class=(n.class?n.class+" ":"")+s:"style"==t?n.style=(n.style?n.style+";":"")+s:"nodeName"!=t&&(n[t]=s))}}}return r}function fn(t,e,i,n){if(i==un&&n==un)return e;let r=e;for(let e=0;e<n.length;e++){let s=n[e],o=i[e];if(e){let e;o&&o.nodeName==s.nodeName&&r!=t&&(e=r.parentNode)&&e.nodeName.toLowerCase()==s.nodeName||(e=document.createElement(s.nodeName),e.pmIsDeco=!0,e.appendChild(r),o=un[0]),r=e}dn(r,o||un[0],s)}return r}function dn(t,e,i){for(let n in e)"class"==n||"style"==n||"nodeName"==n||n in i||t.removeAttribute(n);for(let n in i)"class"!=n&&"style"!=n&&"nodeName"!=n&&i[n]!=e[n]&&t.setAttribute(n,i[n]);if(e.class!=i.class){let n=e.class?e.class.split(" ").filter(Boolean):[],r=i.class?i.class.split(" ").filter(Boolean):[];for(let e=0;e<n.length;e++)-1==r.indexOf(n[e])&&t.classList.remove(n[e]);for(let e=0;e<r.length;e++)-1==n.indexOf(r[e])&&t.classList.add(r[e]);0==t.classList.length&&t.removeAttribute("class")}if(e.style!=i.style){if(e.style){let i,n=/\s*([\w\-\xa1-\uffff]+)\s*:(?:"(?:\\.|[^"])*"|'(?:\\.|[^'])*'|\(.*?\)|[^;])*/g;for(;i=n.exec(e.style);)t.style.removeProperty(i[1])}i.style&&(t.style.cssText+=i.style)}}function pn(t,e,i){return fn(t,t,un,cn(e,i,1!=t.nodeType))}function gn(t,e){if(t.length!=e.length)return!1;for(let i=0;i<t.length;i++)if(!t[i].type.eq(e[i].type))return!1;return!0}function mn(t){let e=t.nextSibling;return t.parentNode.removeChild(t),e}class wn{constructor(t,e,i){this.lock=e,this.view=i,this.index=0,this.stack=[],this.changed=!1,this.top=t,this.preMatch=function(t,e){let i=e,n=i.children.length,r=t.childCount,s=new Map,o=[];t:for(;r>0;){let h;for(;;)if(n){let t=i.children[n-1];if(!(t instanceof en)){h=t,n--;break}i=t,n=t.children.length}else{if(i==e)break t;n=i.parent.children.indexOf(i),i=i.parent}let a=h.node;if(a){if(a!=t.child(r-1))break;--r,s.set(h,r),o.push(h)}}return{index:r,matched:s,matches:o.reverse()}}(t.node.content,t)}destroyBetween(t,e){if(t!=e){for(let i=t;i<e;i++)this.top.children[i].destroy();this.top.children.splice(t,e-t),this.changed=!0}}destroyRest(){this.destroyBetween(this.index,this.top.children.length)}syncToMarks(t,e,i,n){let r=0,s=this.stack.length>>1,o=Math.min(s,t.length);for(;r<o&&(r==s-1?this.top:this.stack[r+1<<1]).matchesMark(t[r])&&!1!==t[r].type.spec.spanning;)r++;for(;r<s;)this.destroyRest(),this.top.dirty=0,this.index=this.stack.pop(),this.top=this.stack.pop(),s--;for(;s<t.length;){this.stack.push(this.top,this.index+1);let r=-1,o=this.top.children.length;n<this.preMatch.index&&(o=Math.min(this.index+3,o));for(let e=this.index;e<o;e++){let i=this.top.children[e];if(i.matchesMark(t[s])&&!this.isLocked(i.dom)){r=e;break}}if(r<0&&this.index<this.top.children.length){let e=this.top.children[this.index];e instanceof en&&3!=e.dirty&&e.mark.type==t[s].type&&e.spec.update&&!this.isLocked(e.dom)&&e.spec.update(t[s])&&(e.mark=t[s],r=this.index,this.changed=!0)}if(r>-1)r>this.index&&(this.changed=!0,this.destroyBetween(this.index,r)),this.top=this.top.children[this.index];else{let n=en.create(this.top,t[s],e,i);this.top.children.splice(this.index,0,n),this.top=n,this.changed=!0}this.index=0,s++}}findNodeMatch(t,e,i,n){let r,s=-1;if(n>=this.preMatch.index&&(r=this.preMatch.matches[n-this.preMatch.index]).parent==this.top&&r.matchesNode(t,e,i))s=this.top.children.indexOf(r,this.index);else for(let n=this.index,r=Math.min(this.top.children.length,n+5);n<r;n++){let r=this.top.children[n];if(r.matchesNode(t,e,i)&&!this.preMatch.matched.has(r)){s=n;break}}return!(s<0||(this.destroyBetween(this.index,s),this.index++,0))}updateNodeAt(t,e,i,n,r){let s=this.top.children[n];return 3==s.dirty&&s.dom==s.contentDOM&&(s.dirty=2),!!s.update(t,e,i,r)&&(this.destroyBetween(this.index,n),this.index++,!0)}findIndexWithChild(t){for(;;){let e=t.parentNode;if(!e)return-1;if(e==this.top.contentDOM){let e=t.pmViewDesc;if(e)for(let t=this.index;t<this.top.children.length;t++)if(this.top.children[t]==e)return t;return-1}t=e}}updateNextNode(t,e,i,n,r,s){for(let o=this.index;o<this.top.children.length;o++){let h=this.top.children[o];if(h instanceof nn){let a=this.preMatch.matched.get(h);if(null!=a&&a!=r)return!1;let l,u=h.dom,c=this.isLocked(u)&&!(t.isText&&h.node&&h.node.isText&&h.nodeDOM.nodeValue==t.text&&3!=h.dirty&&gn(e,h.outerDeco));if(!c&&h.update(t,e,i,n))return this.destroyBetween(this.index,o),h.dom!=u&&(this.changed=!0),this.index++,!0;if(!c&&(l=this.recreateWrapper(h,t,e,i,n,s)))return this.destroyBetween(this.index,o),this.top.children[this.index]=l,l.contentDOM&&(l.dirty=2,l.updateChildren(n,s+1),l.dirty=0),this.changed=!0,this.index++,!0;break}}return!1}recreateWrapper(t,e,i,n,r,s){if(t.dirty||e.isAtom||!t.children.length||!t.node.content.eq(e.content)||!gn(i,t.outerDeco)||!n.eq(t.innerDeco))return null;let o=nn.create(this.top,e,i,n,r,s);if(o.contentDOM){o.children=t.children,t.children=[];for(let t of o.children)t.parent=o}return t.destroy(),o}addNode(t,e,i,n,r){let s=nn.create(this.top,t,e,i,n,r);s.contentDOM&&s.updateChildren(n,r+1),this.top.children.splice(this.index++,0,s),this.changed=!0}placeWidget(t,e,i){let n=this.index<this.top.children.length?this.top.children[this.index]:null;if(!n||!n.matchesWidget(t)||t!=n.widget&&n.widget.type.toDOM.parentNode){let n=new Zi(this.top,t,e,i);this.top.children.splice(this.index++,0,n),this.changed=!0}else this.index++}addTextblockHacks(){let t=this.top.children[this.index-1],e=this.top;for(;t instanceof en;)e=t,t=e.children[e.children.length-1];(!t||!(t instanceof sn)||/\n$/.test(t.node.text)||this.view.requiresGeckoHackNode&&/\s$/.test(t.node.text))&&((Si||ki)&&t&&"false"==t.dom.contentEditable&&this.addHackNode("IMG",e),this.addHackNode("BR",this.top))}addHackNode(t,e){if(e==this.top&&this.index<e.children.length&&e.children[this.index].matchesHack(t))this.index++;else{let i=document.createElement(t);"IMG"==t&&(i.className="ProseMirror-separator",i.alt=""),"BR"==t&&(i.className="ProseMirror-trailingBreak");let n=new on(this.top,[],i,null);e!=this.top?e.children.push(n):e.children.splice(this.index++,0,n),this.changed=!0}}isLocked(t){return this.lock&&(t==this.lock||1==t.nodeType&&t.contains(this.lock.parentNode))}}function vn(t,e){return t.type.side-e.type.side}function yn(t,e,i,n,r){let s=[];for(let o=0,h=0;o<t.length;o++){let a=t[o],l=h,u=h+=a.size;l>=i||u<=e?s.push(a):(l<e&&s.push(a.slice(0,e-l,n)),r&&(s.push(r),r=void 0),u>i&&s.push(a.slice(i-l,a.size,n)))}return s}function bn(t,e=null){let i=t.domSelectionRange(),n=t.state.doc;if(!i.focusNode)return null;let r=t.docView.nearestDesc(i.focusNode),s=r&&0==r.size,o=t.docView.posFromDOM(i.focusNode,i.focusOffset,1);if(o<0)return null;let h,a,l=n.resolve(o);if(li(i)){for(h=o;r&&!r.node;)r=r.parent;let t=r.node;if(r&&t.isAtom&&Be.isSelectable(t)&&r.parent&&(!t.isInline||!function(t,e,i){for(let n=0==e,r=e==hi(t);n||r;){if(t==i)return!0;let e=ti(t);if(!(t=t.parentNode))return!1;n=n&&0==e,r=r&&e==hi(t)}}(i.focusNode,i.focusOffset,r.dom))){let t=r.posBefore;a=new Be(o==t?l:n.resolve(t))}}else{if(i instanceof t.dom.ownerDocument.defaultView.Selection&&i.rangeCount>1){let e=o,r=o;for(let n=0;n<i.rangeCount;n++){let s=i.getRangeAt(n);e=Math.min(e,t.docView.posFromDOM(s.startContainer,s.startOffset,1)),r=Math.max(r,t.docView.posFromDOM(s.endContainer,s.endOffset,-1))}if(e<0)return null;[h,o]=r==t.state.selection.anchor?[r,e]:[e,r],l=n.resolve(o)}else h=t.docView.posFromDOM(i.anchorNode,i.anchorOffset,1);if(h<0)return null}let u=n.resolve(h);return a||(a=Tn(t,u,l,"pointer"==e||t.state.selection.head<l.pos&&!s?1:-1)),a}function kn(t){return t.editable?t.hasFocus():On(t)&&document.activeElement&&document.activeElement.contains(t.dom)}function Mn(t,e=!1){let i=t.state.selection;if(zn(t,i),!kn(t))return;let n=t.input.mouseDown;if(!e&&ki&&n){let e=t.domSelectionRange(),i=t.domObserver.currentSelection;if(e.anchorNode&&i.anchorNode&&ri(e.anchorNode,e.anchorOffset,i.anchorNode,i.anchorOffset)&&n.delaySelUpdate())return void t.domObserver.setCurSelection()}if(t.domObserver.disconnectSelection(),t.cursorWrapper)!function(t){let e=t.domSelection();if(!e)return;let i=t.cursorWrapper.dom,n="IMG"==i.nodeName;n?e.collapse(i.parentNode,ti(i)+1):e.collapse(i,0),!n&&!t.state.selection.visible&&wi&&vi<=11&&(i.disabled=!0,i.disabled=!1)}(t);else{let n,r,{anchor:s,head:o}=i;!Sn||i instanceof _e||(i.$from.parent.inlineContent||(n=xn(t,i.from)),i.empty||i.$from.parent.inlineContent||(r=xn(t,i.to))),t.docView.setSelection(s,o,t,e),Sn&&(n&&$n(n),r&&$n(r)),i.visible?t.dom.classList.remove("ProseMirror-hideselection"):(t.dom.classList.add("ProseMirror-hideselection"),"onselectionchange"in document&&function(t){let e=t.dom.ownerDocument;e.removeEventListener("selectionchange",t.input.hideSelectionGuard);let i=t.domSelectionRange(),n=i.anchorNode,r=i.anchorOffset;e.addEventListener("selectionchange",t.input.hideSelectionGuard=()=>{i.anchorNode==n&&i.anchorOffset==r||(e.removeEventListener("selectionchange",t.input.hideSelectionGuard),setTimeout((()=>{kn(t)&&!t.state.selection.visible||t.dom.classList.remove("ProseMirror-hideselection")}),20))})}(t))}t.domObserver.setCurSelection(),t.domObserver.connectSelection()}const Sn=Si||ki&&Mi<63;function xn(t,e){let{node:i,offset:n}=t.docView.domFromPos(e,0),r=n<i.childNodes.length?i.childNodes[n]:null,s=n?i.childNodes[n-1]:null;if(Si&&r&&"false"==r.contentEditable)return An(r);if(!(r&&"false"!=r.contentEditable||s&&"false"!=s.contentEditable)){if(r)return An(r);if(s)return An(s)}}function An(t){return t.contentEditable="true",Si&&t.draggable&&(t.draggable=!1,t.wasDraggable=!0),t}function $n(t){t.contentEditable="false",t.wasDraggable&&(t.draggable=!0,t.wasDraggable=null)}function zn(t,e){if(e instanceof Be){let i=t.docView.descAt(e.from);i!=t.lastSelectedViewDesc&&(Cn(t),i&&i.selectNode(),t.lastSelectedViewDesc=i)}else Cn(t)}function Cn(t){t.lastSelectedViewDesc&&(t.lastSelectedViewDesc.parent&&t.lastSelectedViewDesc.deselectNode(),t.lastSelectedViewDesc=void 0)}function Tn(t,e,i,n){return t.someProp("createSelectionBetween",(n=>n(t,e,i)))||_e.between(e,i,n)}function En(t){return!(t.editable&&!t.hasFocus())&&On(t)}function On(t){let e=t.domSelectionRange();if(!e.anchorNode)return!1;try{return t.dom.contains(3==e.anchorNode.nodeType?e.anchorNode.parentNode:e.anchorNode)&&(t.editable||t.dom.contains(3==e.focusNode.nodeType?e.focusNode.parentNode:e.focusNode))}catch(t){return!1}}function In(t,e){let{$anchor:i,$head:n}=t.selection,r=e>0?i.max(n):i.min(n),s=r.parent.inlineContent?r.depth?t.doc.resolve(e>0?r.after():r.before()):null:r;return s&&je.findFrom(s,e)}function jn(t,e){return t.dispatch(t.state.tr.setSelection(e).scrollIntoView()),!0}function Pn(t,e,i){let n=t.state.selection;if(!(n instanceof _e)){if(n instanceof Be&&n.node.isInline)return jn(t,new _e(e>0?n.$to:n.$from));{let i=In(t.state,e);return!!i&&jn(t,i)}}if(i.indexOf("s")>-1){let{$head:i}=n,r=i.textOffset?null:e<0?i.nodeBefore:i.nodeAfter;if(!r||r.isText||!r.isLeaf)return!1;let s=t.state.doc.resolve(i.pos+r.nodeSize*(e<0?-1:1));return jn(t,new _e(n.$anchor,s))}if(!n.empty)return!1;if(t.endOfTextblock(e>0?"forward":"backward")){let i=In(t.state,e);return!!(i&&i instanceof Be)&&jn(t,i)}if(!(Ai&&i.indexOf("m")>-1)){let i,r=n.$head,s=r.textOffset?null:e<0?r.nodeBefore:r.nodeAfter;if(!s||s.isText)return!1;let o=e<0?r.pos-s.nodeSize:r.pos;return!!(s.isAtom||(i=t.docView.descAt(o))&&!i.contentDOM)&&(Be.isSelectable(s)?jn(t,new Be(e<0?t.state.doc.resolve(r.pos-s.nodeSize):r)):!!Ci&&jn(t,new _e(t.state.doc.resolve(e<0?o:o+s.nodeSize))))}}function Rn(t){return 3==t.nodeType?t.nodeValue.length:t.childNodes.length}function Dn(t,e){let i=t.pmViewDesc;return i&&0==i.size&&(e<0||t.nextSibling||"BR"!=t.nodeName)}function _n(t,e){return e<0?function(t){let e=t.domSelectionRange(),i=e.focusNode,n=e.focusOffset;if(!i)return;let r,s,o=!1;for(yi&&1==i.nodeType&&n<Rn(i)&&Dn(i.childNodes[n],-1)&&(o=!0);;)if(n>0){if(1!=i.nodeType)break;{let t=i.childNodes[n-1];if(Dn(t,-1))r=i,s=--n;else{if(3!=t.nodeType)break;i=t,n=i.nodeValue.length}}}else{if(Ln(i))break;{let e=i.previousSibling;for(;e&&Dn(e,-1);)r=i.parentNode,s=ti(e),e=e.previousSibling;if(e)i=e,n=Rn(i);else{if(i=i.parentNode,i==t.dom)break;n=0}}}o?Bn(t,i,n):r&&Bn(t,r,s)}(t):function(t){let e=t.domSelectionRange(),i=e.focusNode,n=e.focusOffset;if(!i)return;let r,s,o=Rn(i);for(;;)if(n<o){if(1!=i.nodeType)break;if(!Dn(i.childNodes[n],1))break;r=i,s=++n}else{if(Ln(i))break;{let e=i.nextSibling;for(;e&&Dn(e,1);)r=e.parentNode,s=ti(e)+1,e=e.nextSibling;if(e)i=e,n=0,o=Rn(i);else{if(i=i.parentNode,i==t.dom)break;n=o=0}}}r&&Bn(t,r,s)}(t)}function Ln(t){let e=t.pmViewDesc;return e&&e.node&&e.node.isBlock}function Bn(t,e,i){if(3!=e.nodeType){let t,n;(n=function(t,e){for(;t&&e==t.childNodes.length&&!ai(t);)e=ti(t)+1,t=t.parentNode;for(;t&&e<t.childNodes.length;){let i=t.childNodes[e];if(3==i.nodeType)return i;if(1==i.nodeType&&"false"==i.contentEditable)break;t=i,e=0}}(e,i))?(e=n,i=0):(t=function(t,e){for(;t&&!e&&!ai(t);)e=ti(t),t=t.parentNode;for(;t&&e;){let i=t.childNodes[e-1];if(3==i.nodeType)return i;if(1==i.nodeType&&"false"==i.contentEditable)break;e=(t=i).childNodes.length}}(e,i))&&(e=t,i=t.nodeValue.length)}let n=t.domSelection();if(!n)return;if(li(n)){let t=document.createRange();t.setEnd(e,i),t.setStart(e,i),n.removeAllRanges(),n.addRange(t)}else n.extend&&n.extend(e,i);t.domObserver.setCurSelection();let{state:r}=t;setTimeout((()=>{t.state==r&&Mn(t)}),50)}function Fn(t,e){let i=t.state.doc.resolve(e);if(!ki&&!$i&&i.parent.inlineContent){let n=t.coordsAtPos(e);if(e>i.start()){let i=t.coordsAtPos(e-1),r=(i.top+i.bottom)/2;if(r>n.top&&r<n.bottom&&Math.abs(i.left-n.left)>1)return i.left<n.left?"ltr":"rtl"}if(e<i.end()){let i=t.coordsAtPos(e+1),r=(i.top+i.bottom)/2;if(r>n.top&&r<n.bottom&&Math.abs(i.left-n.left)>1)return i.left>n.left?"ltr":"rtl"}}return"rtl"==getComputedStyle(t.dom).direction?"rtl":"ltr"}function Nn(t,e,i){let n=t.state.selection;if(n instanceof _e&&!n.empty||i.indexOf("s")>-1)return!1;if(Ai&&i.indexOf("m")>-1)return!1;let{$from:r,$to:s}=n;if(!r.parent.inlineContent||t.endOfTextblock(e<0?"up":"down")){let i=In(t.state,e);if(i&&i instanceof Be)return jn(t,i)}if(!r.parent.inlineContent){let i=e<0?r:s,o=n instanceof Ne?je.near(i,e):je.findFrom(i,e);return!!o&&jn(t,o)}return!1}function Wn(t,e){if(!(t.state.selection instanceof _e))return!0;let{$head:i,$anchor:n,empty:r}=t.state.selection;if(!i.sameParent(n))return!0;if(!r)return!1;if(t.endOfTextblock(e>0?"forward":"backward"))return!0;let s=!i.textOffset&&(e<0?i.nodeBefore:i.nodeAfter);if(s&&!s.isText){let n=t.state.tr;return e<0?n.delete(i.pos-s.nodeSize,i.pos):n.delete(i.pos,i.pos+s.nodeSize),t.dispatch(n),!0}return!1}function Un(t,e,i){t.domObserver.stop(),e.contentEditable=i,t.domObserver.start()}function Kn(t,e){t.someProp("transformCopied",(i=>{e=i(e,t)}));let i=[],{content:n,openStart:r,openEnd:s}=e;for(;r>1&&s>1&&1==n.childCount&&1==n.firstChild.childCount;){r--,s--;let t=n.firstChild;i.push(t.type.name,t.attrs!=t.type.defaultAttrs?t.attrs:null),n=t.content}let o=t.someProp("clipboardSerializer")||Kt.fromSchema(t.state.schema),h=Zn(),a=h.createElement("div");a.appendChild(o.serializeFragment(n,{document:h}));let l,u=a.firstChild,c=0;for(;u&&1==u.nodeType&&(l=Qn[u.nodeName.toLowerCase()]);){for(let t=l.length-1;t>=0;t--){let e=h.createElement(l[t]);for(;a.firstChild;)e.appendChild(a.firstChild);a.appendChild(e),c++}u=a.firstChild}u&&1==u.nodeType&&u.setAttribute("data-pm-slice",`${r} ${s}${c?` -${c}`:""} ${JSON.stringify(i)}`);let f=t.someProp("clipboardTextSerializer",(i=>i(e,t)))||e.content.textBetween(0,e.content.size,"\n\n");return{dom:a,text:f,slice:e}}function Hn(t,e,i,n,r){let s,o,h=r.parent.type.spec.code;if(!i&&!e)return null;let a=!!e&&(n||h||!i);if(a){if(t.someProp("transformPastedText",(i=>{e=i(e,h||n,t)})),h)return o=new Y(U.from(t.state.schema.text(e.replace(/\r\n?/g,"\n"))),0,0),t.someProp("transformPasted",(e=>{o=e(o,t,!0)})),o;let i=t.someProp("clipboardTextParser",(i=>i(e,r,n,t)));if(i)o=i;else{let i=r.marks(),{schema:n}=t.state,o=Kt.fromSchema(n);s=document.createElement("div"),e.split(/(?:\r\n?|\n)+/).forEach((t=>{let e=s.appendChild(document.createElement("p"));t&&e.appendChild(o.serializeNode(n.text(t,i)))}))}}else t.someProp("transformPastedHTML",(e=>{i=e(i,t)})),s=function(t){let e=/^(\s*<meta [^>]*>)*/.exec(t);e&&(t=t.slice(e[0].length));let i,n=Zn(),r=n.body,s=/<([a-z][^>\s]+)/i.exec(t);if((i=s&&Qn[s[1].toLowerCase()])&&(t=i.map((t=>"<"+t+">")).join("")+t+i.map((t=>"</"+t+">")).reverse().join("")),r.innerHTML=function(t){let e=window.trustedTypes;return e?(tr||(tr=e.defaultPolicy||e.createPolicy("ProseMirrorClipboard",{createHTML:t=>t})),tr.createHTML(t)):t}(t),i)for(let t=0;t<i.length;t++)r=r.querySelector(i[t])||r;for(let t=0;t<n.styleSheets.length;t++){let e=n.styleSheets[t];for(let t=0;t<e.rules.length;t++){let i=e.rules[t];if(i instanceof CSSStyleRule){let t=r.querySelectorAll(i.selectorText);for(let e=0;e<t.length;e++)t[e].style.cssText+=i.style.cssText}}}return r}(i),Ci&&function(t){let e=t.querySelectorAll(ki?"span:not([class]):not([style])":"span.Apple-converted-space");for(let i=0;i<e.length;i++){let n=e[i];1==n.childNodes.length&&" "==n.textContent&&n.parentNode&&n.parentNode.replaceChild(t.ownerDocument.createTextNode(" "),n)}}(s);let l=s&&s.querySelector("[data-pm-slice]"),u=l&&/^(\d+) (\d+)(?: -(\d+))? (.*)/.exec(l.getAttribute("data-pm-slice")||"");if(u&&u[3])for(let t=+u[3];t>0;t--){let t=s.firstChild;for(;t&&1!=t.nodeType;)t=t.nextSibling;if(!t)break;s=t}if(!o){let e=t.someProp("clipboardParser")||t.someProp("domParser")||Pt.fromSchema(t.state.schema);o=e.parseSlice(s,{preserveWhitespace:!(!a&&!u),context:r,ruleFromNode:t=>"BR"!=t.nodeName||t.nextSibling||!t.parentNode||Vn.test(t.parentNode.nodeName)?null:{ignore:!0}})}if(u)o=function(t,e){if(!t.size)return t;let i,n=t.content.firstChild.type.schema;try{i=JSON.parse(e)}catch(e){return t}let{content:r,openStart:s,openEnd:o}=t;for(let t=i.length-2;t>=0;t-=2){let e=n.nodes[i[t]];if(!e||e.hasRequiredAttrs())break;r=U.from(e.create(i[t+1],r)),s++,o++}return new Y(r,s,o)}(Jn(o,+u[1],+u[2]),u[4]);else if(o=Y.maxOpen(function(t,e){if(t.childCount<2)return t;for(let i=e.depth;i>=0;i--){let n,r=e.node(i).contentMatchAt(e.index(i)),s=[];if(t.forEach((t=>{if(!s)return;let e,i=r.findWrapping(t.type);if(!i)return s=null;if(e=s.length&&n.length&&Xn(i,n,t,s[s.length-1],0))s[s.length-1]=e;else{s.length&&(s[s.length-1]=Yn(s[s.length-1],n.length));let e=Gn(t,i);s.push(e),r=r.matchType(e.type),n=i}})),s)return U.from(s)}return t}(o.content,r),!0),o.openStart||o.openEnd){let t=0,e=0;for(let e=o.content.firstChild;t<o.openStart&&!e.type.spec.isolating;t++,e=e.firstChild);for(let t=o.content.lastChild;e<o.openEnd&&!t.type.spec.isolating;e++,t=t.lastChild);o=Jn(o,t,e)}return t.someProp("transformPasted",(e=>{o=e(o,t,a)})),o}const Vn=/^(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 Gn(t,e,i=0){for(let n=e.length-1;n>=i;n--)t=e[n].create(null,U.from(t));return t}function Xn(t,e,i,n,r){if(r<t.length&&r<e.length&&t[r]==e[r]){let s=Xn(t,e,i,n.lastChild,r+1);if(s)return n.copy(n.content.replaceChild(n.childCount-1,s));if(n.contentMatchAt(n.childCount).matchType(r==t.length-1?i.type:t[r+1]))return n.copy(n.content.append(U.from(Gn(i,t,r+1))))}}function Yn(t,e){if(0==e)return t;let i=t.content.replaceChild(t.childCount-1,Yn(t.lastChild,e-1)),n=t.contentMatchAt(t.childCount).fillBefore(U.empty,!0);return t.copy(i.append(n))}function qn(t,e,i,n,r,s){let o=e<0?t.firstChild:t.lastChild,h=o.content;return t.childCount>1&&(s=0),r<n-1&&(h=qn(h,e,i,n,r+1,s)),r>=i&&(h=e<0?o.contentMatchAt(0).fillBefore(h,s<=r).append(h):h.append(o.contentMatchAt(o.childCount).fillBefore(U.empty,!0))),t.replaceChild(e<0?0:t.childCount-1,o.copy(h))}function Jn(t,e,i){return e<t.openStart&&(t=new Y(qn(t.content,-1,e,t.openStart,0,t.openEnd),e,t.openEnd)),i<t.openEnd&&(t=new Y(qn(t.content,1,i,t.openEnd,0,0),t.openStart,i)),t}const Qn={thead:["table"],tbody:["table"],tfoot:["table"],caption:["table"],colgroup:["table"],col:["table","colgroup"],tr:["table","tbody"],td:["table","tbody","tr"],th:["table","tbody","tr"]};function Zn(){return document.implementation.createHTMLDocument("title")}let tr=null;const er={},ir={},nr={touchstart:!0,touchmove:!0};class rr{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 sr(t,e){t.input.lastSelectionOrigin=e,t.input.lastSelectionTime=Date.now()}function or(t){t.someProp("handleDOMEvents",(e=>{for(let i in e)t.input.eventHandlers[i]||t.dom.addEventListener(i,t.input.eventHandlers[i]=e=>hr(t,e))}))}function hr(t,e){return t.someProp("handleDOMEvents",(i=>{let n=i[e.type];return!!n&&(n(t,e)||e.defaultPrevented)}))}function ar(t,e){if(!e.bubbles)return!0;if(e.defaultPrevented)return!1;for(let i=e.target;i!=t.dom;i=i.parentNode)if(!i||11==i.nodeType||i.pmViewDesc&&i.pmViewDesc.stopEvent(e))return!1;return!0}function lr(t){return{left:t.clientX,top:t.clientY}}function ur(t,e,i,n,r){if(-1==n)return!1;let s=t.state.doc.resolve(n);for(let n=s.depth+1;n>0;n--)if(t.someProp(e,(e=>n>s.depth?e(t,i,s.nodeAfter,s.before(n),r,!0):e(t,i,s.node(n),s.before(n),r,!1))))return!0;return!1}function cr(t,e){if(t.focused||t.focus(),t.state.selection.eq(e))return;let i=t.state.tr.setSelection(e);i.setMeta("pointer",!0),t.dispatch(i)}function fr(t,e,i,n){return ur(t,"handleDoubleClickOn",e,i,n)||t.someProp("handleDoubleClick",(i=>i(t,e,n)))}function dr(t,e,i,n){return ur(t,"handleTripleClickOn",e,i,n)||t.someProp("handleTripleClick",(i=>i(t,e,n)))||function(t,e,i){if(0!=i.button)return!1;let n=pr(t,e,!0),r=t.state.doc;return!!n&&(cr(t,n),n instanceof _e&&r.eq(t.state.doc)&&(t.input.mouseDown=new yr(t,n)),!0)}(t,i,n)}function pr(t,e,i){let n=t.state.doc;if(-1==e)return n.inlineContent?_e.create(n,0,n.content.size):null;let r=n.resolve(e);for(let t=r.depth+1;t>0;t--){let e=t>r.depth?r.nodeAfter:r.node(t),s=r.before(t);if(e.inlineContent)return _e.create(n,s+1,s+1+e.content.size);if(i&&Be.isSelectable(e))return Be.create(n,s)}return null}function gr(t){return xr(t)}ir.keydown=(t,e)=>{let i=e;if(t.input.shiftKey=16==i.keyCode||i.shiftKey,!br(t)&&(t.input.lastKeyCode=i.keyCode,t.input.lastKeyCodeTime=Date.now(),!zi||!ki||13!=i.keyCode))if(229!=i.keyCode&&t.domObserver.forceFlush(),!xi||13!=i.keyCode||i.ctrlKey||i.altKey||i.metaKey)t.someProp("handleKeyDown",(e=>e(t,i)))||function(t,e){let i=e.keyCode,n=function(t){let e="";return t.ctrlKey&&(e+="c"),t.metaKey&&(e+="m"),t.altKey&&(e+="a"),t.shiftKey&&(e+="s"),e}(e);if(8==i||Ai&&72==i&&"c"==n)return Wn(t,-1)||_n(t,-1);if(46==i&&!e.shiftKey||Ai&&68==i&&"c"==n)return Wn(t,1)||_n(t,1);if(13==i||27==i)return!0;if(37==i||Ai&&66==i&&"c"==n){let e=37==i?"ltr"==Fn(t,t.state.selection.from)?-1:1:-1;return Pn(t,e,n)||_n(t,e)}if(39==i||Ai&&70==i&&"c"==n){let e=39==i?"ltr"==Fn(t,t.state.selection.from)?1:-1:1;return Pn(t,e,n)||_n(t,e)}return 38==i||Ai&&80==i&&"c"==n?Nn(t,-1,n)||_n(t,-1):40==i||Ai&&78==i&&"c"==n?function(t){if(!Si||t.state.selection.$head.parentOffset>0)return!1;let{focusNode:e,focusOffset:i}=t.domSelectionRange();if(e&&1==e.nodeType&&0==i&&e.firstChild&&"false"==e.firstChild.contentEditable){let i=e.firstChild;Un(t,i,"true"),setTimeout((()=>Un(t,i,"false")),20)}return!1}(t)||Nn(t,1,n)||_n(t,1):n==(Ai?"m":"c")&&(66==i||73==i||89==i||90==i)}(t,i)?i.preventDefault():sr(t,"key");else{let e=Date.now();t.input.lastIOSEnter=e,t.input.lastIOSEnterFallbackTimeout=setTimeout((()=>{t.input.lastIOSEnter==e&&(t.someProp("handleKeyDown",(e=>e(t,ui(13,"Enter")))),t.input.lastIOSEnter=0)}),200)}},ir.keyup=(t,e)=>{16==e.keyCode&&(t.input.shiftKey=!1)},ir.keypress=(t,e)=>{let i=e;if(br(t)||!i.charCode||i.ctrlKey&&!i.altKey||Ai&&i.metaKey)return;if(t.someProp("handleKeyPress",(e=>e(t,i))))return void i.preventDefault();let n=t.state.selection;if(!(n instanceof _e&&n.$from.sameParent(n.$to))){let e=String.fromCharCode(i.charCode),r=()=>t.state.tr.insertText(e).scrollIntoView();/[\r\n]/.test(e)||t.someProp("handleTextInput",(i=>i(t,n.$from.pos,n.$to.pos,e,r)))||t.dispatch(r()),i.preventDefault()}};const mr=Ai?"metaKey":"ctrlKey";er.mousedown=(t,e)=>{let i=e;t.input.shiftKey=i.shiftKey;let n=gr(t),r=Date.now(),s="singleClick";r-t.input.lastClick.time<500&&function(t,e){let i=e.x-t.clientX,n=e.y-t.clientY;return i*i+n*n<100}(i,t.input.lastClick)&&!i[mr]&&t.input.lastClick.button==i.button&&("singleClick"==t.input.lastClick.type?s="doubleClick":"doubleClick"==t.input.lastClick.type&&(s="tripleClick")),t.input.lastClick={time:r,x:i.clientX,y:i.clientY,type:s,button:i.button},t.input.mouseDown&&t.input.mouseDown.done();let o=t.posAtCoords(lr(i));o&&("singleClick"==s?t.input.mouseDown=new vr(t,o,i,!!n):("doubleClick"==s?fr:dr)(t,o.pos,o.inside,i)?i.preventDefault():sr(t,"pointer"))};class wr{constructor(t){this.view=t,this.mightDrag=null,t.root.addEventListener("mouseup",this.up=this.up.bind(this)),t.root.addEventListener("mousemove",this.move=this.move.bind(this))}up(t){this.done()}move(t){0==t.buttons&&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 vr extends wr{constructor(t,e,i,n){let r,s;if(super(t),this.pos=e,this.event=i,this.flushed=n,this.delayedSelectionSync=!1,this.startDoc=t.state.doc,this.selectNode=!!i[mr],this.allowDefault=i.shiftKey,e.inside>-1)r=t.state.doc.nodeAt(e.inside),s=e.inside;else{let i=t.state.doc.resolve(e.pos);r=i.parent,s=i.depth?i.before():0}const o=n?null:i.target,h=o?t.docView.nearestDesc(o,!0):null;this.target=h&&1==h.nodeDOM.nodeType?h.nodeDOM:null;let{selection:a}=t.state;0==i.button&&(r.type.spec.draggable&&!1!==r.type.spec.selectable||a instanceof Be&&a.from<=s&&a.to>s)&&(this.mightDrag={node:r,pos:s,addAttr:!(!this.target||this.target.draggable),setUneditable:!(!this.target||!yi||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()),sr(t,"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||Mn(this.view)}))}up(t){if(this.done(),!this.view.dom.contains(t.target))return;let e=this.pos;this.view.state.doc!=this.startDoc&&(e=this.view.posAtCoords(lr(t))),this.updateAllowDefault(t),this.allowDefault||!e?sr(this.view,"pointer"):function(t,e,i,n,r){return ur(t,"handleClickOn",e,i,n)||t.someProp("handleClick",(i=>i(t,e,n)))||(r?function(t,e){if(-1==e)return!1;let i,n,r=t.state.selection;r instanceof Be&&(i=r.node);let s=t.state.doc.resolve(e);for(let t=s.depth+1;t>0;t--){let e=t>s.depth?s.nodeAfter:s.node(t);if(Be.isSelectable(e)){n=i&&r.$from.depth>0&&t>=r.$from.depth&&s.before(r.$from.depth+1)==r.$from.pos?s.before(r.$from.depth):s.before(t);break}}return null!=n&&(cr(t,Be.create(t.state.doc,n)),!0)}(t,i):function(t,e){if(-1==e)return!1;let i=t.state.doc.resolve(e),n=i.nodeAfter;return!!(n&&n.isAtom&&Be.isSelectable(n))&&(cr(t,new Be(i)),!0)}(t,i))}(this.view,e.pos,e.inside,t,this.selectNode)?t.preventDefault():0==t.button&&(this.flushed||Si&&this.mightDrag&&!this.mightDrag.node.isAtom||ki&&!this.view.state.selection.visible&&Math.min(Math.abs(e.pos-this.view.state.selection.from),Math.abs(e.pos-this.view.state.selection.to))<=2)?(cr(this.view,je.near(this.view.state.doc.resolve(e.pos))),t.preventDefault()):sr(this.view,"pointer")}move(t){this.updateAllowDefault(t),sr(this.view,"pointer"),super.move(t)}updateAllowDefault(t){!this.allowDefault&&(Math.abs(this.event.x-t.clientX)>4||Math.abs(this.event.y-t.clientY)>4)&&(this.allowDefault=!0)}delaySelUpdate(){return!!this.allowDefault&&(this.delayedSelectionSync=!0,!0)}}class yr extends wr{constructor(t,e){super(t),this.startSelection=e,this.startDoc=t.state.doc}move(t){if(0==t.buttons||this.view.isDestroyed||!this.view.state.doc.eq(this.startDoc))return void this.done();t.preventDefault(),sr(this.view,"pointer");let e=this.view.posAtCoords(lr(t)),i=e&&pr(this.view,e.inside,!1);if(!i)return;let{doc:n}=this.view.state,r=this.startSelection,[s,o]=i.from<r.from?[r.to,i.from]:[r.from,i.to];cr(this.view,_e.create(n,s,o))}}function br(t){return!!t.composing||!!(Si&&Math.abs(Date.now()-t.input.compositionEndedAt)<500)&&(t.input.compositionEndedAt=-2e8,!0)}er.touchstart=t=>{t.input.lastTouch=Date.now(),gr(t),sr(t,"pointer")},er.touchmove=t=>{t.input.lastTouch=Date.now(),sr(t,"pointer")},er.contextmenu=t=>gr(t);const kr=zi?5e3:-1;function Mr(t,e){clearTimeout(t.input.composingTimeout),e>-1&&(t.input.composingTimeout=setTimeout((()=>xr(t)),e))}function Sr(t){for(t.composing&&(t.input.composing=!1,t.input.compositionEndedAt=Date.now());t.input.compositionNodes.length>0;)t.input.compositionNodes.pop().markParentsDirty()}function xr(t,e=!1){if(!(zi&&t.domObserver.flushingSoon>=0)){if(t.domObserver.forceFlush(),Sr(t),e||t.docView&&t.docView.dirty){let i=bn(t),n=t.state.selection;return i&&!i.eq(n)?t.dispatch(t.state.tr.setSelection(i)):!t.markCursor&&!e||n.$from.node(n.$from.sharedDepth(n.to)).inlineContent?t.updateState(t.state):t.dispatch(t.state.tr.deleteSelection()),!0}return!1}}ir.compositionstart=ir.compositionupdate=t=>{if(!t.composing){t.domObserver.flush();let{state:e}=t,i=e.selection.$to;if(e.selection instanceof _e&&(e.storedMarks||!i.textOffset&&i.parentOffset&&i.nodeBefore.marks.some((t=>!1===t.type.spec.inclusive))||ki&&$i&&function(t){let{focusNode:e,focusOffset:i}=t.domSelectionRange();if(!e||1!=e.nodeType||i>=e.childNodes.length)return!1;let n=e.childNodes[i];return 1==n.nodeType&&"false"==n.contentEditable}(t)))t.markCursor=t.state.storedMarks||i.marks(),xr(t,!0),t.markCursor=null;else if(xr(t,!e.selection.empty),yi&&e.selection.empty&&i.parentOffset&&!i.textOffset&&i.nodeBefore.marks.length){let e=t.domSelectionRange();for(let i=e.focusNode,n=e.focusOffset;i&&1==i.nodeType&&0!=n;){let e=n<0?i.lastChild:i.childNodes[n-1];if(!e)break;if(3==e.nodeType){let i=t.domSelection();i&&i.collapse(e,e.nodeValue.length);break}i=e,n=-1}}t.input.composing=!0}Mr(t,kr)},ir.compositionend=t=>{t.composing&&(t.input.composing=!1,t.input.compositionEndedAt=Date.now(),t.input.compositionPendingChanges=t.domObserver.pendingRecords().length?t.input.compositionID:0,t.input.compositionNode=null,t.input.badSafariComposition?t.domObserver.forceFlush():t.input.compositionPendingChanges&&Promise.resolve().then((()=>t.domObserver.flush())),t.input.compositionID++,Mr(t,20))};const Ar=wi&&vi<15||xi&&Ti<604;function $r(t,e,i,n,r){let s=Hn(t,e,i,n,t.state.selection.$from);if(t.someProp("handlePaste",(e=>e(t,r,s||Y.empty))))return!0;if(!s)return!1;let o=function(t){return 0==t.openStart&&0==t.openEnd&&1==t.content.childCount?t.content.firstChild:null}(s),h=o?t.state.tr.replaceSelectionWith(o,n):t.state.tr.replaceSelection(s);return t.dispatch(h.scrollIntoView().setMeta("paste",!0).setMeta("uiEvent","paste")),!0}function zr(t){let e=t.getData("text/plain")||t.getData("Text");if(e)return e;let i=t.getData("text/uri-list");return i?i.replace(/\r?\n/g," "):""}er.copy=ir.cut=(t,e)=>{let i=e,n=t.state.selection,r="cut"==i.type;if(n.empty)return;let s=Ar?null:i.clipboardData,o=n.content(),{dom:h,text:a}=Kn(t,o);s?(i.preventDefault(),s.clearData(),s.setData("text/html",h.innerHTML),s.setData("text/plain",a)):function(t,e){if(!t.dom.parentNode)return;let i=t.dom.parentNode.appendChild(document.createElement("div"));i.appendChild(e),i.style.cssText="position: fixed; left: -10000px; top: 10px";let n=getSelection(),r=document.createRange();r.selectNodeContents(e),t.dom.blur(),n.removeAllRanges(),n.addRange(r),setTimeout((()=>{i.parentNode&&i.parentNode.removeChild(i),t.focus()}),50)}(t,h),r&&t.dispatch(t.state.tr.deleteSelection().scrollIntoView().setMeta("uiEvent","cut"))},ir.paste=(t,e)=>{let i=e;if(t.composing&&!zi)return;let n=Ar?null:i.clipboardData,r=t.input.shiftKey&&45!=t.input.lastKeyCode;n&&$r(t,zr(n),n.getData("text/html"),r,i)?i.preventDefault():function(t,e){if(!t.dom.parentNode)return;let i=t.input.shiftKey||t.state.selection.$from.parent.type.spec.code,n=t.dom.parentNode.appendChild(document.createElement(i?"textarea":"div"));i||(n.contentEditable="true"),n.style.cssText="position: fixed; left: -10000px; top: 10px",n.focus();let r=t.input.shiftKey&&45!=t.input.lastKeyCode;setTimeout((()=>{t.focus(),n.parentNode&&n.parentNode.removeChild(n),i?$r(t,n.value,null,r,e):$r(t,n.textContent,n.innerHTML,r,e)}),50)}(t,i)};class Cr{constructor(t,e,i){this.slice=t,this.move=e,this.node=i}}const Tr=Ai?"altKey":"ctrlKey";function Er(t,e){let i;return t.someProp("dragCopies",(t=>{i=i||t(e)})),null!=i?!i:!e[Tr]}er.dragstart=(t,e)=>{let i=e,n=t.input.mouseDown;if(n&&n.done(),!i.dataTransfer)return;let r,s=t.state.selection,o=s.empty?null:t.posAtCoords(lr(i));if(o&&o.pos>=s.from&&o.pos<=(s instanceof Be?s.to-1:s.to));else if(n&&n.mightDrag)r=Be.create(t.state.doc,n.mightDrag.pos);else if(i.target&&1==i.target.nodeType){let e=t.docView.nearestDesc(i.target,!0);e&&e.node.type.spec.draggable&&e!=t.docView&&(r=Be.create(t.state.doc,e.posBefore))}let h=(r||t.state.selection).content(),{dom:a,text:l,slice:u}=Kn(t,h);(!i.dataTransfer.files.length||!ki||Mi>120)&&i.dataTransfer.clearData(),i.dataTransfer.setData(Ar?"Text":"text/html",a.innerHTML),i.dataTransfer.effectAllowed="copyMove",Ar||i.dataTransfer.setData("text/plain",l),t.dragging=new Cr(u,Er(t,i),r)},er.dragend=t=>{let e=t.dragging;window.setTimeout((()=>{t.dragging==e&&(t.dragging=null)}),50)},ir.dragover=ir.dragenter=(t,e)=>e.preventDefault(),ir.drop=(t,e)=>{try{!function(t,e,i){if(!e.dataTransfer)return;let n=t.posAtCoords(lr(e));if(!n)return;let r=t.state.doc.resolve(n.pos),s=i&&i.slice;s?t.someProp("transformPasted",(e=>{s=e(s,t,!1)})):s=Hn(t,zr(e.dataTransfer),Ar?null:e.dataTransfer.getData("text/html"),!1,r);let o=!(!i||!Er(t,e));if(t.someProp("handleDrop",(i=>i(t,e,s||Y.empty,o))))return void e.preventDefault();if(!s)return;e.preventDefault();let h=s?function(t,e,i){let n=t.resolve(e);if(!i.content.size)return e;let r=i.content;for(let t=0;t<i.openStart;t++)r=r.firstChild.content;for(let t=1;t<=(0==i.openStart&&i.size?2:1);t++)for(let e=n.depth;e>=0;e--){let i=e==n.depth?0:n.pos<=(n.start(e+1)+n.end(e+1))/2?-1:1,s=n.index(e)+(i>0?1:0),o=n.node(e),h=!1;if(1==t)h=o.canReplace(s,s,r);else{let t=o.contentMatchAt(s).findWrapping(r.firstChild.type);h=t&&o.canReplaceWith(s,s,t[0])}if(h)return 0==i?n.pos:i<0?n.before(e+1):n.after(e+1)}return null}(t.state.doc,r.pos,s):r.pos;null==h&&(h=r.pos);let a=t.state.tr;if(o){let{node:t}=i;t?t.replace(a):a.deleteSelection()}let l=a.mapping.map(h),u=0==s.openStart&&0==s.openEnd&&1==s.content.childCount,c=a.doc;if(u?a.replaceRangeWith(l,l,s.content.firstChild):a.replaceRange(l,l,s),a.doc.eq(c))return;let f=a.doc.resolve(l);if(u&&Be.isSelectable(s.content.firstChild)&&f.nodeAfter&&f.nodeAfter.sameMarkup(s.content.firstChild))a.setSelection(new Be(f));else{let e=a.mapping.map(h);a.mapping.maps[a.mapping.maps.length-1].forEach(((t,i,n,r)=>e=r)),a.setSelection(Tn(t,f,a.doc.resolve(e)))}t.focus(),t.dispatch(a.setMeta("uiEvent","drop"))}(t,e,t.dragging)}finally{t.dragging=null}},er.focus=t=>{t.input.lastFocus=Date.now(),t.focused||(t.domObserver.stop(),t.dom.classList.add("ProseMirror-focused"),t.domObserver.start(),t.focused=!0,setTimeout((()=>{t.docView&&t.hasFocus()&&!t.domObserver.currentSelection.eq(t.domSelectionRange())&&Mn(t)}),20))},er.blur=(t,e)=>{let i=e;t.focused&&(t.domObserver.stop(),t.dom.classList.remove("ProseMirror-focused"),t.domObserver.start(),i.relatedTarget&&t.dom.contains(i.relatedTarget)&&t.domObserver.currentSelection.clear(),t.focused=!1)},er.beforeinput=(t,e)=>{if(zi&&"deleteContentBackward"==e.inputType){t.domObserver.flushSoon();let{domChangeCount:e}=t.input;setTimeout((()=>{if(t.input.domChangeCount!=e)return;if(t.dom.blur(),t.focus(),t.someProp("handleKeyDown",(e=>e(t,ui(8,"Backspace")))))return;let{$cursor:i}=t.state.selection;i&&i.pos>0&&t.dispatch(t.state.tr.delete(i.pos-1,i.pos).scrollIntoView())}),50)}};for(let t in ir)er[t]=ir[t];function Or(t,e){if(t==e)return!0;for(let i in t)if(t[i]!==e[i])return!1;for(let i in e)if(!(i in t))return!1;return!0}class Ir{constructor(t,e){this.toDOM=t,this.spec=e||_r,this.side=this.spec.side||0}map(t,e,i,n){let{pos:r,deleted:s}=t.mapResult(e.from+n,this.side<0?-1:1);return s?null:new Rr(r-i,r-i,this)}valid(){return!0}eq(t){return this==t||t instanceof Ir&&(this.spec.key&&this.spec.key==t.spec.key||this.toDOM==t.toDOM&&Or(this.spec,t.spec))}destroy(t){this.spec.destroy&&this.spec.destroy(t)}}class jr{constructor(t,e){this.attrs=t,this.spec=e||_r}map(t,e,i,n){let r=t.map(e.from+n,this.spec.inclusiveStart?-1:1)-i,s=t.map(e.to+n,this.spec.inclusiveEnd?1:-1)-i;return r>=s?null:new Rr(r,s,this)}valid(t,e){return e.from<e.to}eq(t){return this==t||t instanceof jr&&Or(this.attrs,t.attrs)&&Or(this.spec,t.spec)}static is(t){return t.type instanceof jr}destroy(){}}class Pr{constructor(t,e){this.attrs=t,this.spec=e||_r}map(t,e,i,n){let r=t.mapResult(e.from+n,1);if(r.deleted)return null;let s=t.mapResult(e.to+n,-1);return s.deleted||s.pos<=r.pos?null:new Rr(r.pos-i,s.pos-i,this)}valid(t,e){let i,{index:n,offset:r}=t.content.findIndex(e.from);return r==e.from&&!(i=t.child(n)).isText&&r+i.nodeSize==e.to}eq(t){return this==t||t instanceof Pr&&Or(this.attrs,t.attrs)&&Or(this.spec,t.spec)}destroy(){}}class Rr{constructor(t,e,i){this.from=t,this.to=e,this.type=i}copy(t,e){return new Rr(t,e,this.type)}eq(t,e=0){return this.type.eq(t.type)&&this.from+e==t.from&&this.to+e==t.to}map(t,e,i){return this.type.map(t,this,e,i)}static widget(t,e,i){return new Rr(t,t,new Ir(e,i))}static inline(t,e,i,n){return new Rr(t,e,new jr(i,n))}static node(t,e,i,n){return new Rr(t,e,new Pr(i,n))}get spec(){return this.type.spec}get inline(){return this.type instanceof jr}get widget(){return this.type instanceof Ir}}const Dr=[],_r={};class Lr{constructor(t,e){this.local=t.length?t:Dr,this.children=e.length?e:Dr}static create(t,e){return e.length?Kr(e,t,0,_r):Br}find(t,e,i){let n=[];return this.findInner(null==t?0:t,null==e?1e9:e,n,0,i),n}findInner(t,e,i,n,r){for(let s=0;s<this.local.length;s++){let o=this.local[s];o.from<=e&&o.to>=t&&(!r||r(o.spec))&&i.push(o.copy(o.from+n,o.to+n))}for(let s=0;s<this.children.length;s+=3)if(this.children[s]<e&&this.children[s+1]>t){let o=this.children[s]+1;this.children[s+2].findInner(t-o,e-o,i,n+o,r)}}map(t,e,i){return this==Br||0==t.maps.length?this:this.mapInner(t,e,0,0,i||_r)}mapInner(t,e,i,n,r){let s;for(let o=0;o<this.local.length;o++){let h=this.local[o].map(t,i,n);h&&h.type.valid(e,h)?(s||(s=[])).push(h):r.onRemove&&r.onRemove(this.local[o].spec)}return this.children.length?function(t,e,i,n,r,s,o){let h=t.slice();for(let t=0,e=s;t<i.maps.length;t++){let n=0;i.maps[t].forEach(((t,i,r,s)=>{let o=s-r-(i-t);for(let r=0;r<h.length;r+=3){let s=h[r+1];if(s<0||t>s+e-n)continue;let a=h[r]+e-n;i>=a?h[r+1]=t<=a?-2:-1:t>=e&&o&&(h[r]+=o,h[r+1]+=o)}n+=o})),e=i.maps[t].map(e,-1)}let a=!1;for(let e=0;e<h.length;e+=3)if(h[e+1]<0){if(-2==h[e+1]){a=!0,h[e+1]=-1;continue}let l=i.map(t[e]+s),u=l-r;if(u<0||u>=n.content.size){a=!0;continue}let c=i.map(t[e+1]+s,-1)-r,{index:f,offset:d}=n.content.findIndex(u),p=n.maybeChild(f);if(p&&d==u&&d+p.nodeSize==c){let n=h[e+2].mapInner(i,p,l+1,t[e]+s+1,o);n!=Br?(h[e]=u,h[e+1]=c,h[e+2]=n):(h[e+1]=-2,a=!0)}else a=!0}if(a){let a=function(t,e,i,n,r,s,o){function h(t,e){for(let s=0;s<t.local.length;s++){let h=t.local[s].map(n,r,e);h?i.push(h):o.onRemove&&o.onRemove(t.local[s].spec)}for(let i=0;i<t.children.length;i+=3)h(t.children[i+2],t.children[i]+e+1)}for(let i=0;i<t.length;i+=3)-1==t[i+1]&&h(t[i+2],e[i]+s+1);return i}(h,t,e,i,r,s,o),l=Kr(a,n,0,o);e=l.local;for(let t=0;t<h.length;t+=3)h[t+1]<0&&(h.splice(t,3),t-=3);for(let t=0,e=0;t<l.children.length;t+=3){let i=l.children[t];for(;e<h.length&&h[e]<i;)e+=3;h.splice(e,0,l.children[t],l.children[t+1],l.children[t+2])}}return new Lr(e.sort(Hr),h)}(this.children,s||[],t,e,i,n,r):s?new Lr(s.sort(Hr),Dr):Br}add(t,e){return e.length?this==Br?Lr.create(t,e):this.addInner(t,e,0):this}addInner(t,e,i){let n,r=0;t.forEach(((t,s)=>{let o,h=s+i;if(o=Wr(e,t,h)){for(n||(n=this.children.slice());r<n.length&&n[r]<s;)r+=3;n[r]==s?n[r+2]=n[r+2].addInner(t,o,h+1):n.splice(r,0,s,s+t.nodeSize,Kr(o,t,h+1,_r)),r+=3}}));let s=Nr(r?Ur(e):e,-i);for(let e=0;e<s.length;e++)s[e].type.valid(t,s[e])||s.splice(e--,1);return new Lr(s.length?this.local.concat(s).sort(Hr):this.local,n||this.children)}remove(t){return 0==t.length||this==Br?this:this.removeInner(t,0)}removeInner(t,e){let i=this.children,n=this.local;for(let n=0;n<i.length;n+=3){let r,s=i[n]+e,o=i[n+1]+e;for(let e,i=0;i<t.length;i++)(e=t[i])&&e.from>s&&e.to<o&&(t[i]=null,(r||(r=[])).push(e));if(!r)continue;i==this.children&&(i=this.children.slice());let h=i[n+2].removeInner(r,s+1);h!=Br?i[n+2]=h:(i.splice(n,3),n-=3)}if(n.length)for(let i,r=0;r<t.length;r++)if(i=t[r])for(let t=0;t<n.length;t++)n[t].eq(i,e)&&(n==this.local&&(n=this.local.slice()),n.splice(t--,1));return i==this.children&&n==this.local?this:n.length||i.length?new Lr(n,i):Br}forChild(t,e){if(this==Br)return this;if(e.isLeaf)return Lr.empty;let i,n;for(let e=0;e<this.children.length;e+=3)if(this.children[e]>=t){this.children[e]==t&&(i=this.children[e+2]);break}let r=t+1,s=r+e.content.size;for(let t=0;t<this.local.length;t++){let e=this.local[t];if(e.from<s&&e.to>r&&e.type instanceof jr){let t=Math.max(r,e.from)-r,i=Math.min(s,e.to)-r;t<i&&(n||(n=[])).push(e.copy(t,i))}}if(n){let t=new Lr(n.sort(Hr),Dr);return i?new Fr([t,i]):t}return i||Br}eq(t){if(this==t)return!0;if(!(t instanceof Lr)||this.local.length!=t.local.length||this.children.length!=t.children.length)return!1;for(let e=0;e<this.local.length;e++)if(!this.local[e].eq(t.local[e]))return!1;for(let e=0;e<this.children.length;e+=3)if(this.children[e]!=t.children[e]||this.children[e+1]!=t.children[e+1]||!this.children[e+2].eq(t.children[e+2]))return!1;return!0}locals(t){return Vr(this.localsInner(t))}localsInner(t){if(this==Br)return Dr;if(t.inlineContent||!this.local.some(jr.is))return this.local;let e=[];for(let t=0;t<this.local.length;t++)this.local[t].type instanceof jr||e.push(this.local[t]);return e}forEachSet(t){t(this)}}Lr.empty=new Lr([],[]),Lr.removeOverlap=Vr;const Br=Lr.empty;class Fr{constructor(t){this.members=t}map(t,e){const i=this.members.map((i=>i.map(t,e,_r)));return Fr.from(i)}forChild(t,e){if(e.isLeaf)return Lr.empty;let i=[];for(let n=0;n<this.members.length;n++){let r=this.members[n].forChild(t,e);r!=Br&&(r instanceof Fr?i=i.concat(r.members):i.push(r))}return Fr.from(i)}eq(t){if(!(t instanceof Fr)||t.members.length!=this.members.length)return!1;for(let e=0;e<this.members.length;e++)if(!this.members[e].eq(t.members[e]))return!1;return!0}locals(t){let e,i=!0;for(let n=0;n<this.members.length;n++){let r=this.members[n].localsInner(t);if(r.length)if(e){i&&(e=e.slice(),i=!1);for(let t=0;t<r.length;t++)e.push(r[t])}else e=r}return e?Vr(i?e:e.sort(Hr)):Dr}static from(t){switch(t.length){case 0:return Br;case 1:return t[0];default:return new Fr(t.every((t=>t instanceof Lr))?t:t.reduce(((t,e)=>t.concat(e instanceof Lr?e:e.members)),[]))}}forEachSet(t){for(let e=0;e<this.members.length;e++)this.members[e].forEachSet(t)}}function Nr(t,e){if(!e||!t.length)return t;let i=[];for(let n=0;n<t.length;n++){let r=t[n];i.push(new Rr(r.from+e,r.to+e,r.type))}return i}function Wr(t,e,i){if(e.isLeaf)return null;let n=i+e.nodeSize,r=null;for(let e,s=0;s<t.length;s++)(e=t[s])&&e.from>i&&e.to<n&&((r||(r=[])).push(e),t[s]=null);return r}function Ur(t){let e=[];for(let i=0;i<t.length;i++)null!=t[i]&&e.push(t[i]);return e}function Kr(t,e,i,n){let r=[],s=!1;e.forEach(((e,o)=>{let h=Wr(t,e,o+i);if(h){s=!0;let t=Kr(h,e,i+o+1,n);t!=Br&&r.push(o,o+e.nodeSize,t)}}));let o=Nr(s?Ur(t):t,-i).sort(Hr);for(let t=0;t<o.length;t++)o[t].type.valid(e,o[t])||(n.onRemove&&n.onRemove(o[t].spec),o.splice(t--,1));return o.length||r.length?new Lr(o,r):Br}function Hr(t,e){return t.from-e.from||t.to-e.to}function Vr(t){let e=t;for(let i=0;i<e.length-1;i++){let n=e[i];if(n.from!=n.to)for(let r=i+1;r<e.length;r++){let s=e[r];if(s.from!=n.from){s.from<n.to&&(e==t&&(e=t.slice()),e[i]=n.copy(n.from,s.from),Gr(e,r,n.copy(s.from,n.to)));break}s.to!=n.to&&(e==t&&(e=t.slice()),e[r]=s.copy(s.from,n.to),Gr(e,r+1,s.copy(n.to,s.to)))}}return e}function Gr(t,e,i){for(;e<t.length&&Hr(i,t[e])>0;)e++;t.splice(e,0,i)}function Xr(t){let e=[];return t.someProp("decorations",(i=>{let n=i(t.state);n&&n!=Br&&e.push(n)})),t.cursorWrapper&&e.push(Lr.create(t.state.doc,[t.cursorWrapper.deco])),Fr.from(e)}const Yr={childList:!0,characterData:!0,characterDataOldValue:!0,attributes:!0,attributeOldValue:!0,subtree:!0},qr=wi&&vi<=11;class Jr{constructor(){this.anchorNode=null,this.anchorOffset=0,this.focusNode=null,this.focusOffset=0}set(t){this.anchorNode=t.anchorNode,this.anchorOffset=t.anchorOffset,this.focusNode=t.focusNode,this.focusOffset=t.focusOffset}clear(){this.anchorNode=this.focusNode=null}eq(t){return t.anchorNode==this.anchorNode&&t.anchorOffset==this.anchorOffset&&t.focusNode==this.focusNode&&t.focusOffset==this.focusOffset}}class Qr{constructor(t,e){this.view=t,this.handleDOMChange=e,this.queue=[],this.flushingSoon=-1,this.observer=null,this.currentSelection=new Jr,this.onCharData=null,this.suppressingSelectionUpdates=!1,this.lastChangedTextNode=null,this.observer=window.MutationObserver&&new window.MutationObserver((e=>{for(let t=0;t<e.length;t++)this.queue.push(e[t]);wi&&vi<=11&&e.some((t=>"childList"==t.type&&t.removedNodes.length||"characterData"==t.type&&t.oldValue.length>t.target.nodeValue.length))?this.flushSoon():Si&&t.composing&&e.some((t=>"childList"==t.type&&"TR"==t.target.nodeName))?(t.input.badSafariComposition=!0,this.flushSoon()):this.flush()})),qr&&(this.onCharData=t=>{this.queue.push({target:t.target,type:"characterData",oldValue:t.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,Yr)),this.onCharData&&this.view.dom.addEventListener("DOMCharacterDataModified",this.onCharData),this.connectSelection()}stop(){if(this.observer){let t=this.observer.takeRecords();if(t.length){for(let e=0;e<t.length;e++)this.queue.push(t[e]);window.setTimeout((()=>this.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(En(this.view)){if(this.suppressingSelectionUpdates)return Mn(this.view);if(wi&&vi<=11&&!this.view.state.selection.empty){let t=this.view.domSelectionRange();if(t.focusNode&&ri(t.focusNode,t.focusOffset,t.anchorNode,t.anchorOffset))return this.flushSoon()}this.flush()}}setCurSelection(){this.currentSelection.set(this.view.domSelectionRange())}ignoreSelectionChange(t){if(!t.focusNode)return!0;let e,i=new Set;for(let e=t.focusNode;e;e=ei(e))i.add(e);for(let n=t.anchorNode;n;n=ei(n))if(i.has(n)){e=n;break}let n=e&&this.view.docView.nearestDesc(e);return n&&n.ignoreMutation({type:"selection",target:3==e.nodeType?e.parentNode:e})?(this.setCurSelection(),!0):void 0}pendingRecords(){if(this.observer)for(let t of this.observer.takeRecords())this.queue.push(t);return this.queue}flush(){let{view:t}=this;if(!t.docView||this.flushingSoon>-1)return;let e=this.pendingRecords();e.length&&(this.queue=[]);let i=t.domSelectionRange(),n=!this.suppressingSelectionUpdates&&!this.currentSelection.eq(i)&&En(t)&&!this.ignoreSelectionChange(i),r=-1,s=-1,o=!1,h=[];if(t.editable)for(let t=0;t<e.length;t++){let i=this.registerMutation(e[t],h);i&&(r=r<0?i.from:Math.min(i.from,r),s=s<0?i.to:Math.max(i.to,s),i.typeOver&&(o=!0))}if(h.some((t=>"BR"==t.nodeName))&&(8==t.input.lastKeyCode||46==t.input.lastKeyCode||ki&&(t.composing||t.input.compositionEndedAt>Date.now()-50)&&e.some((t=>"childList"==t.type&&t.removedNodes.length)))){for(let t of h)if("BR"==t.nodeName&&t.parentNode){let e=t.nextSibling;for(;e&&1==e.nodeType;){if("false"==e.contentEditable){t.parentNode.removeChild(t);break}e=e.firstChild}}}else if(yi&&h.length){let e=h.filter((t=>"BR"==t.nodeName));if(2==e.length){let[t,i]=e;t.parentNode&&t.parentNode.parentNode==i.parentNode?i.remove():t.remove()}else{let{focusNode:i}=this.currentSelection;for(let n of e){let e=n.parentNode;!e||"LI"!=e.nodeName||i&&is(t,i)==e||n.remove()}}}let a=null;r<0&&n&&t.input.lastFocus>Date.now()-200&&Math.max(t.input.lastTouch,t.input.lastClick.time)<Date.now()-300&&li(i)&&(a=bn(t))&&a.eq(je.near(t.state.doc.resolve(0),1))?(t.input.lastFocus=0,Mn(t),this.currentSelection.set(i),t.scrollToSelection()):(r>-1||n)&&(r>-1&&(t.docView.markDirty(r,s),function(t){if(!Zr.has(t)&&(Zr.set(t,null),-1!==["normal","nowrap","pre-line"].indexOf(getComputedStyle(t.dom).whiteSpace))){if(t.requiresGeckoHackNode=yi,ts)return;console.warn("ProseMirror expects the CSS white-space property to be set, preferably to 'pre-wrap'. It is recommended to load style/prosemirror.css from the prosemirror-view package."),ts=!0}}(t)),t.input.badSafariComposition&&(t.input.badSafariComposition=!1,function(t,e){var i;let{focusNode:n,focusOffset:r}=t.domSelectionRange();for(let s of e)if("TR"==(null===(i=s.parentNode)||void 0===i?void 0:i.nodeName)){let e=s.nextSibling;for(;e&&"TD"!=e.nodeName&&"TH"!=e.nodeName;)e=e.nextSibling;if(e){let i=e;for(;;){let t=i.firstChild;if(!t||1!=t.nodeType||"false"==t.contentEditable||/^(BR|IMG)$/.test(t.nodeName))break;i=t}i.insertBefore(s,i.firstChild),n==s&&t.domSelection().collapse(s,r)}else s.parentNode.removeChild(s)}}(t,h)),this.handleDOMChange(r,s,o,h),t.docView&&t.docView.dirty?t.updateState(t.state):this.currentSelection.eq(i)||Mn(t),this.currentSelection.set(i))}registerMutation(t,e){if(e.indexOf(t.target)>-1)return null;let i=this.view.docView.nearestDesc(t.target);if("attributes"==t.type&&(i==this.view.docView||"contenteditable"==t.attributeName||"style"==t.attributeName&&!t.oldValue&&!t.target.getAttribute("style")))return null;if(!i||i.ignoreMutation(t))return null;if("childList"==t.type){for(let i=0;i<t.addedNodes.length;i++){let n=t.addedNodes[i];e.push(n),3==n.nodeType&&(this.lastChangedTextNode=n)}if(i.contentDOM&&i.contentDOM!=i.dom&&!i.contentDOM.contains(t.target))return{from:i.posBefore,to:i.posAfter};let n=t.previousSibling,r=t.nextSibling;if(wi&&vi<=11&&t.addedNodes.length)for(let e=0;e<t.addedNodes.length;e++){let{previousSibling:i,nextSibling:s}=t.addedNodes[e];(!i||Array.prototype.indexOf.call(t.addedNodes,i)<0)&&(n=i),(!s||Array.prototype.indexOf.call(t.addedNodes,s)<0)&&(r=s)}let s=n&&n.parentNode==t.target?ti(n)+1:0,o=i.localPosFromDOM(t.target,s,-1),h=r&&r.parentNode==t.target?ti(r):t.target.childNodes.length;return{from:o,to:i.localPosFromDOM(t.target,h,1)}}return"attributes"==t.type?{from:i.posAtStart-i.border,to:i.posAtEnd+i.border}:(this.lastChangedTextNode=t.target,{from:i.posAtStart,to:i.posAtEnd,typeOver:t.target.nodeValue==t.oldValue})}}let Zr=new WeakMap,ts=!1;function es(t,e){let i=e.startContainer,n=e.startOffset,r=e.endContainer,s=e.endOffset,o=t.domAtPos(t.state.selection.anchor);return ri(o.node,o.offset,r,s)&&([i,n,r,s]=[r,s,i,n]),{anchorNode:i,anchorOffset:n,focusNode:r,focusOffset:s}}function is(t,e){for(let i=e.parentNode;i&&i!=t.dom;i=i.parentNode){let e=t.docView.nearestDesc(i,!0);if(e&&e.node.isBlock)return i}return null}const ns=/^(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 rs(t,e,i){return Math.max(i.anchor,i.head)>e.content.size?null:Tn(t,e.resolve(i.anchor),e.resolve(i.head))}function ss(t,e,i){let n=t.depth,r=e?t.end():t.pos;for(;n>0&&(e||t.indexAfter(n)==t.node(n).childCount);)n--,r++,e=!1;if(i){let e=t.node(n).maybeChild(t.indexAfter(n));for(;e&&!e.isLeaf;)e=e.firstChild,r++}return r}class hs{constructor(t,e){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 rr,this.prevDirectPlugins=[],this.pluginViews=[],this.requiresGeckoHackNode=!1,this.dragging=null,this._props=e,this.state=e.state,this.directPlugins=e.plugins||[],this.directPlugins.forEach(fs),this.dispatch=this.dispatch.bind(this),this.dom=t&&t.mount||document.createElement("div"),t&&(t.appendChild?t.appendChild(this.dom):"function"==typeof t?t(this.dom):t.mount&&(this.mounted=!0)),this.editable=us(this),ls(this),this.nodeViews=cs(this),this.docView=rn(this.state.doc,as(this),Xr(this),this.dom,this),this.domObserver=new Qr(this,((t,e,i,n)=>function(t,e,i,n,r){let s=t.input.compositionPendingChanges||(t.composing?t.input.compositionID:0);if(t.input.compositionPendingChanges=0,e<0){let e=t.input.lastSelectionTime>Date.now()-50?t.input.lastSelectionOrigin:null,i=bn(t,e);if(i&&!t.state.selection.eq(i)){if(ki&&zi&&13===t.input.lastKeyCode&&Date.now()-100<t.input.lastKeyCodeTime&&t.someProp("handleKeyDown",(e=>e(t,ui(13,"Enter")))))return;let n=t.state.tr.setSelection(i);"pointer"==e?n.setMeta("pointer",!0):"key"==e&&n.scrollIntoView(),s&&n.setMeta("composition",s),t.dispatch(n)}return}let o=t.state.doc.resolve(e),h=o.sharedDepth(i);e=o.before(h+1),i=t.state.doc.resolve(i).after(h+1);let a,l,u=t.state.selection,c=function(t,e,i,n){let r,{node:s,fromOffset:o,toOffset:h,from:a,to:l}=t.docView.parseRange(e,i),u=t.domSelectionRange(),c=u.anchorNode;if(c&&t.dom.contains(1==c.nodeType?c:c.parentNode)&&(r=[{node:c,offset:u.anchorOffset}],li(u)||r.push({node:u.focusNode,offset:u.focusOffset})),ki&&8===t.input.lastKeyCode)for(let t=h;t>o;t--){let e=s.childNodes[t-1],i=e.pmViewDesc;if("BR"==e.nodeName&&!i){h=t;break}if(!i||i.size)break}let f=t.state.doc,d=t.someProp("domParser")||Pt.fromSchema(t.state.schema),p=f.resolve(a),g=null,m=d.parse(s,{topNode:p.parent,topMatch:p.parent.contentMatchAt(p.index()),topOpen:!0,from:o,to:h,preserveWhitespace:"pre"!=p.parent.type.whitespace||"full",findPositions:r,ruleFromNode:(w=n,t=>{let e=t.pmViewDesc;if(e)return e.parseRule(w);if("BR"==t.nodeName&&t.parentNode){if(Si&&/^(ul|ol)$/i.test(t.parentNode.nodeName)){let t=document.createElement("div");return t.appendChild(document.createElement("li")),{skip:t}}if(t.parentNode.lastChild==t||Si&&/^(tr|table)$/i.test(t.parentNode.nodeName))return{ignore:!0}}else if("IMG"==t.nodeName&&t.getAttribute("mark-placeholder"))return{ignore:!0};return null}),context:p});var w;if(r&&null!=r[0].pos){let t=r[0].pos,e=r[1]&&r[1].pos;null==e&&(e=t),g={anchor:t+a,head:e+a}}return{doc:m,sel:g,from:a,to:l}}(t,e,i,r),f=t.state.doc,d=f.slice(c.from,c.to);8===t.input.lastKeyCode&&Date.now()-100<t.input.lastKeyCodeTime?(a=t.state.selection.to,l="end"):(a=t.state.selection.from,l="start"),t.input.lastKeyCode=null;let p=function(t,e,i,n,r){let s=t.findDiffStart(e,i),o=i+t.size,h=i+e.size;if(null==s)return null;let{a,b:l}=t.findDiffEnd(e,o,h);return"end"==r&&(n-=a+Math.max(0,s-Math.min(a,l))-s),a<s&&o<h?(s-=n<=s&&n>=a?s-n:0,l=s+(l-a),a=s):l<s&&(s-=n<=s&&n>=l?s-n:0,a=s+(a-l),l=s),{start:s,endA:a,endB:l}}(d.content,c.doc.content,c.from,a,l);if(p&&t.input.domChangeCount++,(xi&&t.input.lastIOSEnter>Date.now()-225||zi)&&r.some((t=>1==t.nodeType&&!ns.test(t.nodeName)))&&(!p||p.endA>=p.endB)&&t.someProp("handleKeyDown",(e=>e(t,ui(13,"Enter")))))return void(t.input.lastIOSEnter=0);if(!p){if(!(n&&u instanceof _e&&!u.empty&&u.$head.sameParent(u.$anchor))||t.composing||c.sel&&c.sel.anchor!=c.sel.head){if(c.sel){let e=rs(t,t.state.doc,c.sel);if(e&&!e.eq(t.state.selection)){let i=t.state.tr.setSelection(e);s&&i.setMeta("composition",s),t.dispatch(i)}}return}p={start:u.from,endA:u.to,endB:u.to}}t.state.selection.from<t.state.selection.to&&p.start==p.endB&&t.state.selection instanceof _e&&(p.start>t.state.selection.from&&p.start<=t.state.selection.from+2&&t.state.selection.from>=c.from?p.start=t.state.selection.from:p.endA<t.state.selection.to&&p.endA>=t.state.selection.to-2&&t.state.selection.to<=c.to&&(p.endB+=t.state.selection.to-p.endA,p.endA=t.state.selection.to)),wi&&vi<=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 g=c.doc.resolveNoCache(p.start-c.from),m=c.doc.resolveNoCache(p.endB-c.from),w=f.resolve(p.start),v=g.sameParent(m)&&g.parent.inlineContent&&w.end()>=p.endA;if((xi&&t.input.lastIOSEnter>Date.now()-225&&(!v||r.some((t=>"DIV"==t.nodeName||"P"==t.nodeName)))||!v&&g.pos<c.doc.content.size&&(!g.sameParent(m)||!g.parent.inlineContent)&&g.pos<m.pos&&!/\S/.test(c.doc.textBetween(g.pos,m.pos,"","")))&&t.someProp("handleKeyDown",(e=>e(t,ui(13,"Enter")))))return void(t.input.lastIOSEnter=0);if(t.state.selection.anchor>p.start&&function(t,e,i,n,r){if(i-e<=r.pos-n.pos||ss(n,!0,!1)<r.pos)return!1;let s=t.resolve(e);if(!n.parent.isTextblock){let t=s.nodeAfter;return null!=t&&i==e+t.nodeSize}if(s.parentOffset<s.parent.content.size||!s.parent.isTextblock)return!1;let o=t.resolve(ss(s,!0,!0));return!(!o.parent.isTextblock||o.pos>i||ss(o,!0,!1)<i)&&n.parent.content.cut(n.parentOffset).eq(o.parent.content)}(f,p.start,p.endA,g,m)&&t.someProp("handleKeyDown",(e=>e(t,ui(8,"Backspace")))))return void(zi&&ki&&t.domObserver.suppressSelectionUpdates());ki&&p.endB==p.start&&(t.input.lastChromeDelete=Date.now()),zi&&!v&&g.start()!=m.start()&&0==m.parentOffset&&g.depth==m.depth&&c.sel&&c.sel.anchor==c.sel.head&&c.sel.head==p.endA&&(p.endB-=2,m=c.doc.resolveNoCache(p.endB-c.from),setTimeout((()=>{t.someProp("handleKeyDown",(function(e){return e(t,ui(13,"Enter"))}))}),20));let y,b=p.start,k=p.endA,M=e=>{let i=e||t.state.tr.replace(b,k,c.doc.slice(p.start-c.from,p.endB-c.from));if(c.sel){let e=rs(t,i.doc,c.sel);e&&!(ki&&t.composing&&e.empty&&(p.start!=p.endB||t.input.lastChromeDelete<Date.now()-100)&&(e.head==b||e.head==i.mapping.map(k)-1)||wi&&e.empty&&e.head==b)&&i.setSelection(e)}return s&&i.setMeta("composition",s),i.scrollIntoView()};if(v)if(g.pos==m.pos){wi&&vi<=11&&0==g.parentOffset&&(t.domObserver.suppressSelectionUpdates(),setTimeout((()=>Mn(t)),20));let e=M(t.state.tr.delete(b,k)),i=f.resolve(p.start).marksAcross(f.resolve(p.endA));i&&e.ensureMarks(i),t.dispatch(e)}else if(p.endA==p.endB&&(y=function(t,e){let i,n,r,s=t.firstChild.marks,o=e.firstChild.marks,h=s,a=o;for(let t=0;t<o.length;t++)h=o[t].removeFromSet(h);for(let t=0;t<s.length;t++)a=s[t].removeFromSet(a);if(1==h.length&&0==a.length)n=h[0],i="add",r=t=>t.mark(n.addToSet(t.marks));else{if(0!=h.length||1!=a.length)return null;n=a[0],i="remove",r=t=>t.mark(n.removeFromSet(t.marks))}let l=[];for(let t=0;t<e.childCount;t++)l.push(r(e.child(t)));if(U.from(l).eq(t))return{mark:n,type:i}}(g.parent.content.cut(g.parentOffset,m.parentOffset),w.parent.content.cut(w.parentOffset,p.endA-w.start())))){let e=M(t.state.tr);"add"==y.type?e.addMark(b,k,y.mark):e.removeMark(b,k,y.mark),t.dispatch(e)}else if(g.parent.child(g.index()).isText&&g.index()==m.index()-(m.textOffset?0:1)){let e=g.parent.textBetween(g.parentOffset,m.parentOffset),i=()=>M(t.state.tr.insertText(e,b,k));t.someProp("handleTextInput",(n=>n(t,b,k,e,i)))||t.dispatch(i())}else t.dispatch(M());else t.dispatch(M())}(this,t,e,i,n))),this.domObserver.start(),function(t){for(let e in er){let i=er[e];t.dom.addEventListener(e,t.input.eventHandlers[e]=e=>{!ar(t,e)||hr(t,e)||!t.editable&&e.type in ir||i(t,e)},nr[e]?{passive:!0}:void 0)}Si&&t.dom.addEventListener("input",(()=>null)),or(t)}(this),this.updatePluginViews()}get composing(){return this.input.composing}get props(){if(this._props.state!=this.state){let t=this._props;this._props={};for(let e in t)this._props[e]=t[e];this._props.state=this.state}return this._props}update(t){t.handleDOMEvents!=this._props.handleDOMEvents&&or(this);let e=this._props;this._props=t,t.plugins&&(t.plugins.forEach(fs),this.directPlugins=t.plugins),this.updateStateInner(t.state,e)}setProps(t){let e={};for(let t in this._props)e[t]=this._props[t];e.state=this.state;for(let i in t)e[i]=t[i];this.update(e)}updateState(t){this.updateStateInner(t,this._props)}updateStateInner(t,e){var i;let n=this.state,r=!1,s=!1;t.storedMarks&&this.composing&&(Sr(this),s=!0),this.state=t;let o=n.plugins!=t.plugins||this._props.plugins!=e.plugins;if(o||this._props.plugins!=e.plugins||this._props.nodeViews!=e.nodeViews){let t=cs(this);(function(t,e){let i=0,n=0;for(let n in t){if(t[n]!=e[n])return!0;i++}for(let t in e)n++;return i!=n})(t,this.nodeViews)&&(this.nodeViews=t,r=!0)}(o||e.handleDOMEvents!=this._props.handleDOMEvents)&&or(this),this.editable=us(this),ls(this);let h=Xr(this),a=as(this),l=n.plugins==t.plugins||n.doc.eq(t.doc)?t.scrollToSelection>n.scrollToSelection?"to selection":"preserve":"reset",u=r||!this.docView.matchesNode(t.doc,a,h);!u&&t.selection.eq(n.selection)||(s=!0);let c="preserve"==l&&s&&null==this.dom.style.overflowAnchor&&function(t){let e,i,n=t.dom.getBoundingClientRect(),r=Math.max(0,n.top);for(let s=(n.left+n.right)/2,o=r+1;o<Math.min(innerHeight,n.bottom);o+=5){let n=t.root.elementFromPoint(s,o);if(!n||n==t.dom||!t.dom.contains(n))continue;let h=n.getBoundingClientRect();if(h.top>=r-20){e=n,i=h.top;break}}return{refDOM:e,refTop:i,stack:Pi(t.dom)}}(this);if(s){this.domObserver.stop();let e=u&&(wi||ki)&&!this.composing&&!n.selection.empty&&!t.selection.empty&&function(t,e){let i=Math.min(t.$anchor.sharedDepth(t.head),e.$anchor.sharedDepth(e.head));return t.$anchor.start(i)!=e.$anchor.start(i)}(n.selection,t.selection);if(u){let i=ki?this.trackWrites=this.domSelectionRange().focusNode:null;this.composing&&(this.input.compositionNode=function(t){let e=t.domSelectionRange();if(!e.focusNode)return null;let i=function(t,e){for(;;){if(3==t.nodeType&&e)return t;if(1==t.nodeType&&e>0){if("false"==t.contentEditable)return null;e=hi(t=t.childNodes[e-1])}else{if(!t.parentNode||ai(t))return null;e=ti(t),t=t.parentNode}}}(e.focusNode,e.focusOffset),n=function(t,e){for(;;){if(3==t.nodeType&&e<t.nodeValue.length)return t;if(1==t.nodeType&&e<t.childNodes.length){if("false"==t.contentEditable)return null;t=t.childNodes[e],e=0}else{if(!t.parentNode||ai(t))return null;e=ti(t)+1,t=t.parentNode}}}(e.focusNode,e.focusOffset);if(i&&n&&i!=n){let e=n.pmViewDesc,r=t.domObserver.lastChangedTextNode;if(i==r||n==r)return r;if(!e||!e.isText(n.nodeValue))return n;if(t.input.compositionNode==n){let t=i.pmViewDesc;if(t&&t.isText(i.nodeValue))return n}}return i||n}(this)),!r&&this.docView.update(t.doc,a,h,this)||(this.docView.updateOuterDeco(a),this.docView.destroy(),this.docView=rn(t.doc,a,h,this.dom,this)),!i||this.trackWrites&&this.dom.contains(this.trackWrites)||(e=!0)}let i=this.input.mouseDown;e||!(i&&this.domObserver.currentSelection.eq(this.domSelectionRange())&&function(t){let e=t.docView.domFromPos(t.state.selection.anchor,0),i=t.domSelectionRange();return ri(e.node,e.offset,i.anchorNode,i.anchorOffset)}(this)&&i.delaySelUpdate())?Mn(this,e):(zn(this,t.selection),this.domObserver.setCurSelection()),this.domObserver.start()}this.updatePluginViews(n),(null===(i=this.dragging)||void 0===i?void 0:i.node)&&!n.doc.eq(t.doc)&&this.updateDraggedNode(this.dragging,n),"reset"==l?this.dom.scrollTop=0:"to selection"==l?this.scrollToSelection():c&&function({refDOM:t,refTop:e,stack:i}){let n=t?t.getBoundingClientRect().top:0;Ri(i,0==n?0:n-e)}(c)}scrollToSelection(){let t=this.domSelectionRange().focusNode;if(t&&this.dom.contains(1==t.nodeType?t:t.parentNode))if(this.someProp("handleScrollToSelection",(t=>t(this))));else if(this.state.selection instanceof Be){let e=this.docView.domAfterPos(this.state.selection.from);1==e.nodeType&&ji(this,e.getBoundingClientRect(),t)}else ji(this,this.coordsAtPos(this.state.selection.head,1),t)}destroyPluginViews(){let t;for(;t=this.pluginViews.pop();)t.destroy&&t.destroy()}updatePluginViews(t){if(t&&t.plugins==this.state.plugins&&this.directPlugins==this.prevDirectPlugins)for(let e=0;e<this.pluginViews.length;e++){let i=this.pluginViews[e];i.update&&i.update(this,t)}else{this.prevDirectPlugins=this.directPlugins,this.destroyPluginViews();for(let t=0;t<this.directPlugins.length;t++){let e=this.directPlugins[t];e.spec.view&&this.pluginViews.push(e.spec.view(this))}for(let t=0;t<this.state.plugins.length;t++){let e=this.state.plugins[t];e.spec.view&&this.pluginViews.push(e.spec.view(this))}}}updateDraggedNode(t,e){let i=t.node,n=-1;if(i.from<this.state.doc.content.size&&this.state.doc.nodeAt(i.from)==i.node)n=i.from;else{let t=i.from+(this.state.doc.content.size-e.doc.content.size);(t>0&&t<this.state.doc.content.size&&this.state.doc.nodeAt(t))==i.node&&(n=t)}this.dragging=new Cr(t.slice,t.move,n<0?void 0:Be.create(this.state.doc,n))}someProp(t,e){let i,n=this._props&&this._props[t];if(null!=n&&(i=e?e(n):n))return i;for(let n=0;n<this.directPlugins.length;n++){let r=this.directPlugins[n].props[t];if(null!=r&&(i=e?e(r):r))return i}let r=this.state.plugins;if(r)for(let n=0;n<r.length;n++){let s=r[n].props[t];if(null!=s&&(i=e?e(s):s))return i}}hasFocus(){if(wi){let t=this.root.activeElement;if(t==this.dom)return!0;if(!t||!this.dom.contains(t))return!1;for(;t&&this.dom!=t&&this.dom.contains(t);){if("false"==t.contentEditable)return!1;t=t.parentElement}return!0}return this.root.activeElement==this.dom}focus(){this.domObserver.stop(),this.editable&&function(t){if(t.setActive)return t.setActive();if(Di)return t.focus(Di);let e=Pi(t);t.focus(null==Di?{get preventScroll(){return Di={preventScroll:!0},!0}}:void 0),Di||(Di=!1,Ri(e,0))}(this.dom),Mn(this),this.domObserver.start()}get root(){let t=this._root;if(null==t)for(let t=this.dom.parentNode;t;t=t.parentNode)if(9==t.nodeType||11==t.nodeType&&t.host)return t.getSelection||(Object.getPrototypeOf(t).getSelection=()=>t.ownerDocument.getSelection()),this._root=t;return t||document}updateRoot(){this._root=null}posAtCoords(t){return Fi(this,t)}coordsAtPos(t,e=1){return Ki(this,t,e)}domAtPos(t,e=0){return this.docView.domFromPos(t,e)}nodeDOM(t){let e=this.docView.descAt(t);return e?e.nodeDOM:null}posAtDOM(t,e,i=-1){let n=this.docView.posFromDOM(t,e,i);if(null==n)throw new RangeError("DOM position not inside the editor");return n}endOfTextblock(t,e){return function(t,e,i){return Yi==e&&qi==i?Ji:(Yi=e,qi=i,Ji="up"==i||"down"==i?function(t,e,i){let n=e.selection,r="up"==i?n.$from:n.$to;return Gi(t,e,(()=>{let{node:e}=t.docView.domFromPos(r.pos,"up"==i?-1:1);for(;;){let i=t.docView.nearestDesc(e,!0);if(!i)break;if(i.node.isBlock){e=i.contentDOM||i.dom;break}e=i.dom.parentNode}let n=Ki(t,r.pos,1);for(let t=e.firstChild;t;t=t.nextSibling){let e;if(1==t.nodeType)e=t.getClientRects();else{if(3!=t.nodeType)continue;e=ni(t,0,t.nodeValue.length).getClientRects()}for(let t=0;t<e.length;t++){let r=e[t];if(r.bottom>r.top+1&&("up"==i?n.top-r.top>2*(r.bottom-n.top):r.bottom-n.bottom>2*(n.bottom-r.top)))return!1}}return!0}))}(t,e,i):function(t,e,i){let{$head:n}=e.selection;if(!n.parent.isTextblock)return!1;let r=n.parentOffset,s=!r,o=r==n.parent.content.size,h=t.domSelection();return h?Xi.test(n.parent.textContent)&&h.modify?Gi(t,e,(()=>{let{focusNode:e,focusOffset:r,anchorNode:s,anchorOffset:o}=t.domSelectionRange(),a=h.caretBidiLevel;h.modify("move",i,"character");let l=n.depth?t.docView.domAfterPos(n.before()):t.dom,{focusNode:u,focusOffset:c}=t.domSelectionRange(),f=u&&!l.contains(1==u.nodeType?u:u.parentNode)||e==u&&r==c;try{h.collapse(s,o),e&&(e!=s||r!=o)&&h.extend&&h.extend(e,r)}catch(t){}return null!=a&&(h.caretBidiLevel=a),f})):"left"==i||"backward"==i?s:o:n.pos==n.start()||n.pos==n.end()}(t,e,i))}(this,e||this.state,t)}pasteHTML(t,e){return $r(this,"",t,!1,e||new ClipboardEvent("paste"))}pasteText(t,e){return $r(this,t,null,!0,e||new ClipboardEvent("paste"))}serializeForClipboard(t){return Kn(this,t)}destroy(){this.docView&&(function(t){t.input.mouseDown&&t.input.mouseDown.done(),t.domObserver.stop();for(let e in t.input.eventHandlers)t.dom.removeEventListener(e,t.input.eventHandlers[e]);clearTimeout(t.input.composingTimeout),clearTimeout(t.input.lastIOSEnterFallbackTimeout)}(this),this.destroyPluginViews(),this.mounted?(this.docView.update(this.state.doc,[],Xr(this),this),this.dom.textContent=""):this.dom.parentNode&&this.dom.parentNode.removeChild(this.dom),this.docView.destroy(),this.docView=null,ii=null)}get isDestroyed(){return null==this.docView}dispatchEvent(t){return function(t,e){hr(t,e)||!er[e.type]||!t.editable&&e.type in ir||er[e.type](t,e)}(this,t)}domSelectionRange(){let t=this.domSelection();return t?Si&&11===this.root.nodeType&&function(t){let e=t.activeElement;for(;e&&e.shadowRoot;)e=e.shadowRoot.activeElement;return e}(this.dom.ownerDocument)==this.dom&&function(t,e){if(e.getComposedRanges){let i=e.getComposedRanges(t.root)[0];if(i)return es(t,i)}let i;function n(t){t.preventDefault(),t.stopImmediatePropagation(),i=t.getTargetRanges()[0]}return t.dom.addEventListener("beforeinput",n,!0),document.execCommand("indent"),t.dom.removeEventListener("beforeinput",n,!0),i?es(t,i):null}(this,t)||t:{focusNode:null,focusOffset:0,anchorNode:null,anchorOffset:0}}domSelection(){return this.root.getSelection()}}function as(t){let e=Object.create(null);return e.class="ProseMirror",e.contenteditable=String(t.editable),t.someProp("attributes",(i=>{if("function"==typeof i&&(i=i(t.state)),i)for(let t in i)"class"==t?e.class+=" "+i[t]:"style"==t?e.style=(e.style?e.style+";":"")+i[t]:e[t]||"contenteditable"==t||"nodeName"==t||(e[t]=String(i[t]))})),e.translate||(e.translate="no"),[Rr.node(0,t.state.doc.content.size,e)]}function ls(t){if(t.markCursor){let e=document.createElement("img");e.className="ProseMirror-separator",e.setAttribute("mark-placeholder","true"),e.setAttribute("alt",""),t.cursorWrapper={dom:e,deco:Rr.widget(t.state.selection.from,e,{raw:!0,marks:t.markCursor})}}else t.cursorWrapper=null}function us(t){return!t.someProp("editable",(e=>!1===e(t.state)))}function cs(t){let e=Object.create(null);function i(t){for(let i in t)Object.prototype.hasOwnProperty.call(e,i)||(e[i]=t[i])}return t.someProp("nodeViews",i),t.someProp("markViews",i),e}function fs(t){if(t.spec.state||t.spec.filterTransaction||t.spec.appendTransaction)throw new RangeError("Plugins passed directly to the view must not have a state component")}hs.prototype.dispatch=function(t){let e=this._props.dispatchTransaction;e?e.call(this,t):this.updateState(this.state.apply(t))};const ds=["p",0],ps=["blockquote",0],gs=["hr"],ms=["pre",["code",0]],ws=["br"],vs=["em",0],ys=["strong",0],bs=["code",0],ks=new It({nodes:{doc:{content:"block+"},paragraph:{content:"inline*",group:"block",parseDOM:[{tag:"p"}],toDOM:()=>ds},blockquote:{content:"block+",group:"block",defining:!0,parseDOM:[{tag:"blockquote"}],toDOM:()=>ps},horizontal_rule:{group:"block",parseDOM:[{tag:"hr"}],toDOM:()=>gs},heading:{attrs:{level:{default:1,validate:"number"}},content:"inline*",group:"block",defining:!0,parseDOM:[{tag:"h1",attrs:{level:1}},{tag:"h2",attrs:{level:2}},{tag:"h3",attrs:{level:3}},{tag:"h4",attrs:{level:4}},{tag:"h5",attrs:{level:5}},{tag:"h6",attrs:{level:6}}],toDOM:t=>["h"+t.attrs.level,0]},code_block:{content:"text*",marks:"",group:"block",code:!0,defining:!0,parseDOM:[{tag:"pre",preserveWhitespace:"full"}],toDOM:()=>ms},text:{group:"inline"},image:{inline:!0,attrs:{src:{validate:"string"},alt:{default:null,validate:"string|null"},title:{default:null,validate:"string|null"}},group:"inline",draggable:!0,parseDOM:[{tag:"img[src]",getAttrs:t=>({src:t.getAttribute("src"),title:t.getAttribute("title"),alt:t.getAttribute("alt")})}],toDOM(t){let{src:e,alt:i,title:n}=t.attrs;return["img",{src:e,alt:i,title:n}]}},hard_break:{inline:!0,group:"inline",selectable:!1,parseDOM:[{tag:"br"}],toDOM:()=>ws}},marks:{link:{attrs:{href:{validate:"string"},title:{default:null,validate:"string|null"}},inclusive:!1,parseDOM:[{tag:"a[href]",getAttrs:t=>({href:t.getAttribute("href"),title:t.getAttribute("title")})}],toDOM(t){let{href:e,title:i}=t.attrs;return["a",{href:e,title:i},0]}},em:{parseDOM:[{tag:"i"},{tag:"em"},{style:"font-style=italic"},{style:"font-style=normal",clearMark:t=>"em"==t.type.name}],toDOM:()=>vs},strong:{parseDOM:[{tag:"strong"},{tag:"b",getAttrs:t=>"normal"!=t.style.fontWeight&&null},{style:"font-weight=400",clearMark:t=>"strong"==t.type.name},{style:"font-weight",getAttrs:t=>/^(bold(er)?|[5-9]\d{2,})$/.test(t)&&null}],toDOM:()=>ys},code:{code:!0,parseDOM:[{tag:"code"}],toDOM:()=>bs}}}),Ms=["ol",0],Ss=["ul",0],xs=["li",0],As={attrs:{order:{default:1,validate:"number"}},parseDOM:[{tag:"ol",getAttrs:t=>({order:t.hasAttribute("start")?+t.getAttribute("start"):1})}],toDOM:t=>1==t.attrs.order?Ms:["ol",{start:t.attrs.order},0]},$s={parseDOM:[{tag:"ul"}],toDOM:()=>Ss},zs={parseDOM:[{tag:"li"}],toDOM:()=>xs,defining:!0};function Cs(t,e){let i={};for(let e in t)i[e]=t[e];for(let t in e)i[t]=e[t];return i}function Ts(t,e,i){return t.append({ordered_list:Cs(As,{content:"list_item+",group:i}),bullet_list:Cs($s,{content:"list_item+",group:i}),list_item:Cs(zs,{content:e})})}for(var Es={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:"'"},Os={48:")",49:"!",50:"@",51:"#",52:"$",53:"%",54:"^",55:"&",56:"*",57:"(",59:":",61:"+",173:"_",186:":",187:"+",188:"<",189:"_",190:">",191:"?",192:"~",219:"{",220:"|",221:"}",222:'"'},Is="undefined"!=typeof navigator&&/Mac/.test(navigator.platform),js="undefined"!=typeof navigator&&/MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent),Ps=0;Ps<10;Ps++)Es[48+Ps]=Es[96+Ps]=String(Ps);for(Ps=1;Ps<=24;Ps++)Es[Ps+111]="F"+Ps;for(Ps=65;Ps<=90;Ps++)Es[Ps]=String.fromCharCode(Ps+32),Os[Ps]=String.fromCharCode(Ps);for(var Rs in Es)Os.hasOwnProperty(Rs)||(Os[Rs]=Es[Rs]);const Ds="undefined"!=typeof navigator&&/Mac|iP(hone|[oa]d)/.test(navigator.platform),_s="undefined"!=typeof navigator&&/Win/.test(navigator.platform);function Ls(t){let e,i,n,r,s=t.split(/-(?!$)/),o=s[s.length-1];"Space"==o&&(o=" ");for(let t=0;t<s.length-1;t++){let o=s[t];if(/^(cmd|meta|m)$/i.test(o))r=!0;else if(/^a(lt)?$/i.test(o))e=!0;else if(/^(c|ctrl|control)$/i.test(o))i=!0;else if(/^s(hift)?$/i.test(o))n=!0;else{if(!/^mod$/i.test(o))throw new Error("Unrecognized modifier name: "+o);Ds?r=!0:i=!0}}return e&&(o="Alt-"+o),i&&(o="Ctrl-"+o),r&&(o="Meta-"+o),n&&(o="Shift-"+o),o}function Bs(t,e,i=!0){return e.altKey&&(t="Alt-"+t),e.ctrlKey&&(t="Ctrl-"+t),e.metaKey&&(t="Meta-"+t),i&&e.shiftKey&&(t="Shift-"+t),t}function Fs(t){return new Qe({props:{handleKeyDown:Ns(t)}})}function Ns(t){let e=function(t){let e=Object.create(null);for(let i in t)e[Ls(i)]=t[i];return e}(t);return function(t,i){let n,r=function(t){var e=!(Is&&t.metaKey&&t.shiftKey&&!t.ctrlKey&&!t.altKey||js&&t.shiftKey&&t.key&&1==t.key.length||"Unidentified"==t.key)&&t.key||(t.shiftKey?Os:Es)[t.keyCode]||t.key||"Unidentified";return"Esc"==e&&(e="Escape"),"Del"==e&&(e="Delete"),"Left"==e&&(e="ArrowLeft"),"Up"==e&&(e="ArrowUp"),"Right"==e&&(e="ArrowRight"),"Down"==e&&(e="ArrowDown"),e}(i),s=e[Bs(r,i)];if(s&&s(t.state,t.dispatch,t))return!0;if(1==r.length&&" "!=r){if(i.shiftKey){let n=e[Bs(r,i,!1)];if(n&&n(t.state,t.dispatch,t))return!0}if((i.altKey||i.metaKey||i.ctrlKey)&&!(_s&&i.ctrlKey&&i.altKey)&&(n=Es[i.keyCode])&&n!=r){let r=e[Bs(n,i)];if(r&&r(t.state,t.dispatch,t))return!0}}return!1}}const Ws=(t,e)=>!t.selection.empty&&(e&&e(t.tr.deleteSelection().scrollIntoView()),!0);function Us(t,e,i=!1){for(let n=t;n;n="start"==e?n.firstChild:n.lastChild){if(n.isTextblock)return!0;if(i&&1!=n.childCount)return!1}return!1}function Ks(t){if(!t.parent.type.spec.isolating)for(let e=t.depth-1;e>=0;e--){if(t.index(e)>0)return t.doc.resolve(t.before(e+1));if(t.node(e).type.spec.isolating)break}return null}function Hs(t){if(!t.parent.type.spec.isolating)for(let e=t.depth-1;e>=0;e--){let i=t.node(e);if(t.index(e)+1<i.childCount)return t.doc.resolve(t.after(e+1));if(i.type.spec.isolating)break}return null}function Vs(t){for(let e=0;e<t.edgeCount;e++){let{type:i}=t.edge(e);if(i.isTextblock&&!i.hasRequiredAttrs())return i}return null}function Gs(t,e,i,n){let r,s,o=e.nodeBefore,h=e.nodeAfter,a=o.type.spec.isolating||h.type.spec.isolating;if(!a&&function(t,e,i){let n=e.nodeBefore,r=e.nodeAfter,s=e.index();return!(!(n&&r&&n.type.compatibleContent(r.type))||(!n.content.size&&e.parent.canReplace(s-1,s)?(i&&i(t.tr.delete(e.pos-n.nodeSize,e.pos).scrollIntoView()),0):!e.parent.canReplace(s,s+1)||!r.isTextblock&&!we(t.doc,e.pos)||(i&&i(t.tr.join(e.pos).scrollIntoView()),0)))}(t,e,i))return!0;let l=!a&&e.parent.canReplace(e.index(),e.index()+1);if(l&&(r=(s=o.contentMatchAt(o.childCount)).findWrapping(h.type))&&s.matchType(r[0]||h.type).validEnd){if(i){let n=e.pos+h.nodeSize,s=U.empty;for(let t=r.length-1;t>=0;t--)s=U.from(r[t].create(null,s));s=U.from(o.copy(s));let a=t.tr.step(new le(e.pos-1,n,e.pos,n,new Y(s,1,0),r.length,!0)),l=a.doc.resolve(n+2*r.length);l.nodeAfter&&l.nodeAfter.type==o.type&&we(a.doc,l.pos)&&a.join(l.pos),i(a.scrollIntoView())}return!0}let u=h.type.spec.isolating||n>0&&a?null:je.findFrom(e,1),c=u&&u.$from.blockRange(u.$to),f=c&&de(c);if(null!=f&&f>=e.depth)return i&&i(t.tr.lift(c,f).scrollIntoView()),!0;if(l&&Us(h,"start",!0)&&Us(o,"end")){let n=o,r=[];for(;r.push(n),!n.isTextblock;)n=n.lastChild;let s=h,a=1;for(;!s.isTextblock;s=s.firstChild)a++;if(n.canReplace(n.childCount,n.childCount,s.content)){if(i){let n=U.empty;for(let t=r.length-1;t>=0;t--)n=U.from(r[t].copy(n));i(t.tr.step(new le(e.pos-r.length,e.pos+h.nodeSize,e.pos+a,e.pos+h.nodeSize-a,new Y(n,r.length,0),0,!0)).scrollIntoView())}return!0}}return!1}function Xs(t){return function(e,i){let n=e.selection,r=t<0?n.$from:n.$to,s=r.depth;for(;r.node(s).isInline;){if(!s)return!1;s--}return!!r.node(s).isTextblock&&(i&&i(e.tr.setSelection(_e.create(e.doc,t<0?r.start(s):r.end(s)))),!0)}}const Ys=Xs(-1),qs=Xs(1);function Js(...t){return function(e,i,n){for(let r=0;r<t.length;r++)if(t[r](e,i,n))return!0;return!1}}let Qs=Js(Ws,((t,e,i)=>{let n=function(t,e){let{$cursor:i}=t.selection;return!i||(e?!e.endOfTextblock("backward",t):i.parentOffset>0)?null:i}(t,i);if(!n)return!1;let r=Ks(n);if(!r){let i=n.blockRange(),r=i&&de(i);return null!=r&&(e&&e(t.tr.lift(i,r).scrollIntoView()),!0)}let s=r.nodeBefore;if(Gs(t,r,e,-1))return!0;if(0==n.parent.content.size&&(Us(s,"end")||Be.isSelectable(s)))for(let i=n.depth;;i--){let o=ve(t.doc,n.before(i),n.after(i),Y.empty);if(o&&o.slice.size<o.to-o.from){if(e){let i=t.tr.step(o);i.setSelection(Us(s,"end")?je.findFrom(i.doc.resolve(i.mapping.map(r.pos,-1)),-1):Be.create(i.doc,r.pos-s.nodeSize)),e(i.scrollIntoView())}return!0}if(1==i||n.node(i-1).childCount>1)break}return!(!s.isAtom||r.depth!=n.depth-1||(e&&e(t.tr.delete(r.pos-s.nodeSize,r.pos).scrollIntoView()),0))}),((t,e,i)=>{let{$head:n,empty:r}=t.selection,s=n;if(!r)return!1;if(n.parent.isTextblock){if(i?!i.endOfTextblock("backward",t):n.parentOffset>0)return!1;s=Ks(n)}let o=s&&s.nodeBefore;return!(!o||!Be.isSelectable(o)||(e&&e(t.tr.setSelection(Be.create(t.doc,s.pos-o.nodeSize)).scrollIntoView()),0))})),Zs=Js(Ws,((t,e,i)=>{let n=function(t,e){let{$cursor:i}=t.selection;return!i||(e?!e.endOfTextblock("forward",t):i.parentOffset<i.parent.content.size)?null:i}(t,i);if(!n)return!1;let r=Hs(n);if(!r)return!1;let s=r.nodeAfter;if(Gs(t,r,e,1))return!0;if(0==n.parent.content.size&&(Us(s,"start")||Be.isSelectable(s))){let i=ve(t.doc,n.before(),n.after(),Y.empty);if(i&&i.slice.size<i.to-i.from){if(e){let n=t.tr.step(i);n.setSelection(Us(s,"start")?je.findFrom(n.doc.resolve(n.mapping.map(r.pos)),1):Be.create(n.doc,n.mapping.map(r.pos))),e(n.scrollIntoView())}return!0}}return!(!s.isAtom||r.depth!=n.depth-1||(e&&e(t.tr.delete(r.pos,r.pos+s.nodeSize).scrollIntoView()),0))}),((t,e,i)=>{let{$head:n,empty:r}=t.selection,s=n;if(!r)return!1;if(n.parent.isTextblock){if(i?!i.endOfTextblock("forward",t):n.parentOffset<n.parent.content.size)return!1;s=Hs(n)}let o=s&&s.nodeAfter;return!(!o||!Be.isSelectable(o)||(e&&e(t.tr.setSelection(Be.create(t.doc,s.pos)).scrollIntoView()),0))}));const to={Enter:Js(((t,e)=>{let{$head:i,$anchor:n}=t.selection;return!(!i.parent.type.spec.code||!i.sameParent(n)||(e&&e(t.tr.insertText("\n").scrollIntoView()),0))}),((t,e)=>{let i=t.selection,{$from:n,$to:r}=i;if(i instanceof Ne||n.parent.inlineContent||r.parent.inlineContent)return!1;let s=Vs(r.parent.contentMatchAt(r.indexAfter()));if(!s||!s.isTextblock)return!1;if(e){let i=(!n.parentOffset&&r.index()<r.parent.childCount?n:r).pos,o=t.tr.insert(i,s.createAndFill());o.setSelection(_e.create(o.doc,i+1)),e(o.scrollIntoView())}return!0}),((t,e)=>{let{$cursor:i}=t.selection;if(!i||i.parent.content.size)return!1;if(i.depth>1&&i.after()!=i.end(-1)){let n=i.before();if(me(t.doc,n))return e&&e(t.tr.split(n).scrollIntoView()),!0}let n=i.blockRange(),r=n&&de(n);return null!=r&&(e&&e(t.tr.lift(n,r).scrollIntoView()),!0)}),((t,e)=>{let{$from:i}=t.selection;if(t.selection instanceof Be&&t.selection.node.isBlock)return!(!i.parentOffset||!me(t.doc,i.pos)||(e&&e(t.tr.split(i.pos).scrollIntoView()),0));if(!i.depth)return!1;let n,r,s=[],o=!1,h=!1;for(let t=i.depth;;t--){if(i.node(t).isBlock){o=i.end(t)==i.pos+(i.depth-t),h=i.start(t)==i.pos-(i.depth-t),r=Vs(i.node(t-1).contentMatchAt(i.indexAfter(t-1))),s.unshift(o&&r?{type:r}:null),n=t;break}if(1==t)return!1;s.unshift(null)}let a=t.tr;(t.selection instanceof _e||t.selection instanceof Ne)&&a.deleteSelection();let l=a.mapping.map(i.pos),u=me(a.doc,l,s.length,s);if(u||(s[0]=r?{type:r}:null,u=me(a.doc,l,s.length,s)),!u)return!1;if(a.split(l,s.length,s),!o&&h&&i.node(n).type!=r){let t=a.mapping.map(i.before(n)),e=a.doc.resolve(t);r&&i.node(n-1).canReplaceWith(e.index(),e.index()+1,r)&&a.setNodeMarkup(a.mapping.map(i.before(n)),r)}return e&&e(a.scrollIntoView()),!0})),"Mod-Enter":(t,e)=>{let{$head:i,$anchor:n}=t.selection;if(!i.parent.type.spec.code||!i.sameParent(n))return!1;let r=i.node(-1),s=i.indexAfter(-1),o=Vs(r.contentMatchAt(s));if(!o||!r.canReplaceWith(s,s,o))return!1;if(e){let n=i.after(),r=t.tr.replaceWith(n,n,o.createAndFill());r.setSelection(je.near(r.doc.resolve(n),1)),e(r.scrollIntoView())}return!0},Backspace:Qs,"Mod-Backspace":Qs,"Shift-Backspace":Qs,Delete:Zs,"Mod-Delete":Zs,"Mod-a":(t,e)=>(e&&e(t.tr.setSelection(new Ne(t.doc))),!0)},eo={"Ctrl-h":to.Backspace,"Alt-Backspace":to["Mod-Backspace"],"Ctrl-d":to.Delete,"Ctrl-Alt-Backspace":to["Mod-Delete"],"Alt-Delete":to["Mod-Delete"],"Alt-d":to["Mod-Delete"],"Ctrl-a":Ys,"Ctrl-e":qs};for(let t in to)eo[t]=to[t];const io=("undefined"!=typeof navigator?/Mac|iP(hone|[oa]d)/.test(navigator.platform):"undefined"!=typeof os&&os.platform&&"darwin"==os.platform())?eo:to;class no extends a{__class__="KritzelText";fontFamily="Arial";fontSize=8;fontColor={light:"#000000",dark:"#ffffff"};initialWidth=1;initialHeight=1;scale=1;scaleFactor=1;isDebugInfoVisible=!0;isEditable=!0;isEditing=!1;isNewlyCreated=!1;editor=null;content=null;_schema=new It({nodes:Ts(ks.spec.nodes,"paragraph block*","block"),marks:ks.spec.marks});uneditedObject=null;rows=1;get isEmpty(){if(!this.editor)return!0;const t=this.editor.state.doc;return 0===t.content.size||0===t.textContent.trim().length}constructor(t){if(super(),this.rotation=l.degreesToRadians(t?.rotation??0),this.editor=this.createEditor(),t){this.translateX=t.translateX||0,this.translateY=t.translateY||0,this.fontSize=t.fontSize||8,this.fontFamily=t.fontFamily||"Arial",this.fontColor=t.fontColor||{light:"#000000",dark:"#ffffff"};const e=this._core?.store?.state?.scale,i=null!=e&&e<0?e:1;this.width=this.initialWidth/i,this.height=1.2*this.fontSize/i,this.scale=t.scale||1,this.scaleFactor=t.scaleX??1,t.text&&this.setContent({type:"doc",content:[{type:"paragraph",content:[{type:"text",text:t.text}]}]})}}static create(t,e,i,n,r){const s=new no;s._core=t,s.id=s.generateId(),s.workspaceId=t.store.state.activeWorkspace.id,s.userId=t.user?.id,s.fontSize=e||8,s.fontFamily=i||"Arial",s.translateX=0,s.translateY=0,s.rotation=l.degreesToRadians(r??0);const o=t.store.state.scale,h=o<0?o:1;return s.width=s.initialWidth/h,s.height=1.2*s.fontSize/h,s.backgroundColor={light:"transparent",dark:"transparent"},s.initialWidth=s.width,s.initialHeight=s.height,s.scaleFactor=1,s.scale=n??o,s.zIndex=t.store.currentZIndex,s}mount(t){null!==t&&!1!==this.isInViewport()&&(t.style.fontFamily=y.resolveCssFontFamily(this.fontFamily),t.style.fontSize=`${this.fontSize}pt`,t.style.color=g.resolveThemeColor(this.fontColor),this.isMounted&&this.elementRef===t&&this.editor.dom.parentElement===t?this._core.store.state.isScaling||this._core.store.state.isPanning||requestAnimationFrame((()=>this.adjustSizeOnInput())):(this.elementRef=t,this.elementRef.style.whiteSpace="pre-wrap",this.elementRef.style.wordWrap="break-word",this.elementRef.innerHTML="",this.elementRef.appendChild(this.editor.dom),this.isMounted=!0,requestAnimationFrame((()=>this.adjustSizeOnInput()))))}createEditor(){const t=this._schema.node("doc",null,[this._schema.node("paragraph")]);return new hs(null,{state:qe.create({doc:t,plugins:[Fs(io)]}),editable:()=>!1,dispatchTransaction:t=>{const e=this.editor.state.apply(t);this.editor.updateState(e),t.docChanged&&(this.content=e.doc.toJSON(),this.adjustSizeOnInput(),t.getMeta("fromRemote")||this._core.store.objects.update(this,{temporary:!0}))}})}setContent(t){if(this.content=t,this.editor&&t){const e=this.editor.state.schema.nodeFromJSON(t),i=this.editor.state.tr.replaceWith(0,this.editor.state.doc.content.size,e.content);i.setMeta("fromRemote",!0),this.editor.dispatch(i)}}adjustSizeOnInput(){const t=this.elementRef;if(t&&this.isMounted&&t.scrollWidth>0){const e=this.totalWidth,i=this.totalHeight,n=t.scrollHeight;if(this.width=t.scrollWidth*this.scaleFactor,this.height=n*this.scaleFactor,0!==this.rotation){const t=(this.totalWidth-e)/2/this.scale,n=(this.totalHeight-i)/2/this.scale;if(0!==t||0!==n){const e=Math.cos(this.rotation),i=Math.sin(this.rotation),r=i*t+e*n;this.translateX+=e*t-i*n-t,this.translateY+=r-n}}}}resize(t,e,i,n){if(i<=1||n<=1)return;const r=this.width/this.scaleFactor,s=this.height/this.scaleFactor;this.scaleFactor=Math.min(i/r,n/s),this.width=r*this.scaleFactor,this.height=s*this.scaleFactor,this.translateX=t,this.translateY=e,this._core.store.objects.update(this)}focus(t){if(this.editor){const e=this.editor.state.doc;if(t.x&&t.y&&!this.isEmpty){const i=this.editor.posAtCoords({left:t.x,top:t.y});if(i)return this.editor.dispatch(this.editor.state.tr.setSelection(_e.create(e,i.pos))),this.editor.focus(),void(v.isIOS()&&this.scrollIntoViewOnIOS())}const i=Math.max(1,e.content.size-1);this.editor.dispatch(this.editor.state.tr.setSelection(_e.create(e,i))),this.editor.focus(),v.isIOS()&&this.scrollIntoViewOnIOS()}}scrollIntoViewOnIOS(){setTimeout((()=>{this.editor&&this.editor.dom&&this.editor.dom.scrollIntoView({behavior:"smooth",block:"center",inline:"nearest"})}),300)}edit(t){_.disableInteractiveWidget(),this.uneditedObject=this.clone(),this._core.store.setState("activeTool",this._core.toolRegistry.getTool("text")),this.editor.setProps({editable:()=>!0}),this.isEditing=!0,this._core.rerender(),this.adjustSizeOnInput(),t?.clientX&&t?.clientY&&this.focus({x:t?.clientX,y:t?.clientY}),_.enableInteractiveWidget()}save(){requestAnimationFrame((()=>this.adjustSizeOnInput())),this.content=this.editor.state.doc.toJSON(),this.editor.setProps({editable:()=>!1}),this.editor.dom.blur(),this.isEditing=!1,this._core.store.objects.consolidateTemporaryItems(),this._core.store.objects.update(this),this._core.engine.emitObjectsChange(),this.isNewlyCreated?(this.isNewlyCreated=!1,this._core.engine.emitObjectsAdded([this])):this._core.engine.emitObjectsUpdated([{object:this,changedProperties:["content"]}])}handleEscape(){if(!this.editor||!this.isEditing)return;const{state:t}=this.editor;if(!t.selection.empty)return this.editor.dispatch(t.tr.setSelection(_e.create(t.doc,t.selection.head))),void this.editor.focus();this._core.resetActiveText(),this._core.clearSelection(),this._core.store.setState("activeTool",this._core.toolRegistry.getTool("selection"))}handlePointerDown(t){this.isEditing&&t.stopPropagation()}handlePointerMove(t){this.isEditing&&(this._core.store.state.pointers.has(t.pointerId)||t.stopPropagation())}handlePointerUp(t){this.isEditing&&(this._core.store.state.pointers.has(t.pointerId)||t.stopPropagation())}copy(){const t=super.copy();return t.editor=t.createEditor(),this.content&&t.setContent(this.content),t}serialize(){const{_core:t,_elementRef:e,_schema:i,element:n,totalWidth:r,totalHeight:s,editor:o,uneditedObject:h,...a}=this,l=structuredClone(a);return n&&"object"==typeof n&&"nodeType"in n&&1===n.nodeType&&(l.element=n.cloneNode(!0)),l}deserialize(t){return super.deserialize(t),t.content&&this.setContent(t.content),this}}const ro="blobs",so="metadata";class oo{type="local";name="IndexedDBAssetProvider";_dbName;_db=null;_urlCache=new Map;_knownIds=new Set;constructor(t){this._dbName=t?.dbName??"kritzel-assets"}static with(t){return{create:()=>new oo(t)}}async init(){this._db||(this._db=await this.openDatabase(),await this.loadKnownIds())}destroy(){for(const t of this._urlCache.values())try{URL.revokeObjectURL(t)}catch{}this._urlCache.clear(),this._knownIds.clear(),this._db&&(this._db.close(),this._db=null)}canResolve(t){return this._knownIds.has(t)}async put(t,e){const i=await this.ensureDb(),n=e.id??this.generateUuid(),r={id:n,kind:e.kind??"file",mimeType:e.mimeType,size:t.size,createdAt:Date.now(),width:e.width,height:e.height,durationMs:e.durationMs,originalFilename:e.originalFilename};return await new Promise(((e,s)=>{const o=i.transaction([ro,so],"readwrite");o.oncomplete=()=>e(),o.onerror=()=>s(o.error),o.onabort=()=>s(o.error),o.objectStore(ro).put(t,n),o.objectStore(so).put(r,n)})),this._knownIds.add(n),r}async resolve(t){const e=this._urlCache.get(t);if(e)return e;const i=await this.fetch(t),n=URL.createObjectURL(i);return this._urlCache.set(t,n),n}async fetch(t){const e=await this.ensureDb(),i=await new Promise(((i,n)=>{const r=e.transaction(ro,"readonly").objectStore(ro).get(t);r.onsuccess=()=>i(r.result),r.onerror=()=>n(r.error)}));if(!i)throw new Error(`[IndexedDBAssetProvider] Asset ${t} not found`);return this._knownIds.add(t),i}async delete(t){const e=await this.ensureDb();await new Promise(((i,n)=>{const r=e.transaction([ro,so],"readwrite");r.oncomplete=()=>i(),r.onerror=()=>n(r.error),r.objectStore(ro).delete(t),r.objectStore(so).delete(t)}));const i=this._urlCache.get(t);if(i){try{URL.revokeObjectURL(i)}catch{}this._urlCache.delete(t)}this._knownIds.delete(t)}async getMetadata(t){const e=await this.ensureDb();return new Promise(((i,n)=>{const r=e.transaction(so,"readonly").objectStore(so).get(t);r.onsuccess=()=>i(r.result),r.onerror=()=>n(r.error)}))}async listAssetsWithPendingRemotes(){const t=await this.ensureDb();return new Promise(((e,i)=>{const n=t.transaction(so,"readonly").objectStore(so).getAll();n.onsuccess=()=>{e((n.result??[]).filter((t=>Array.isArray(t.pendingRemotes)&&t.pendingRemotes.length>0)))},n.onerror=()=>i(n.error)}))}async setPendingRemotes(t,e){const i=await this.ensureDb();await new Promise(((n,r)=>{const s=i.transaction(so,"readwrite");s.oncomplete=()=>n(),s.onerror=()=>r(s.error);const o=s.objectStore(so),h=o.get(t);h.onsuccess=()=>{const i=h.result;if(!i)return;const n={...i};e.length>0?n.pendingRemotes=e:delete n.pendingRemotes,o.put(n,t)}}))}async ensureDb(){return this._db||await this.init(),this._db}openDatabase(){return new Promise(((t,e)=>{const i=indexedDB.open(this._dbName,1);i.onupgradeneeded=()=>{const t=i.result;t.objectStoreNames.contains(ro)||t.createObjectStore(ro),t.objectStoreNames.contains(so)||t.createObjectStore(so)},i.onsuccess=()=>t(i.result),i.onerror=()=>e(i.error)}))}async loadKnownIds(){const t=this._db;t&&await new Promise(((e,i)=>{const n=t.transaction(so,"readonly").objectStore(so).getAllKeys();n.onsuccess=()=>{for(const t of n.result)"string"==typeof t&&this._knownIds.add(t);e()},n.onerror=()=>i(n.error)}))}generateUuid(){if("undefined"!=typeof crypto&&"function"==typeof crypto.randomUUID)return crypto.randomUUID();const t=crypto.getRandomValues(new Uint8Array(16));t[6]=15&t[6]|64,t[8]=63&t[8]|128;const e=Array.from(t,(t=>t.toString(16).padStart(2,"0"))).join("");return`${e.slice(0,8)}-${e.slice(8,12)}-${e.slice(12,16)}-${e.slice(16,20)}-${e.slice(20)}`}}class ho extends Error{assetId;constructor(t,e){super(e??`[KritzelAssetResolver] Asset ${t} not found in any configured provider.`),this.name="AssetNotFoundError",this.assetId=t}}class ao{_providers=[];_local=null;_remoteProviders=[];_initialized=!1;_readyPromise=null;_resolveReady=null;_rejectReady=null;_pending=new Map;_flushTimer=null;_destroyed=!1;_quiet=!0;_resolvePromises=new Map;setShowInfo(t){this._quiet=!t}get hasRemoteProvider(){return this._remoteProviders.length>0}get localProvider(){return this._local}async init(t){if(this._initialized)return;this.getReadyPromise();const e=this.instantiateProviders(t?.providers??[]);e.some((t=>"local"===t.type))||e.unshift(new oo),e.sort(((t,e)=>"local"===t.type&&"local"!==e.type?-1:"local"!==t.type&&"local"===e.type?1:0)),this._providers=e,this._local=e.find((t=>"local"===t.type&&"IndexedDBAssetProvider"===t.name))??null,this._remoteProviders=e.filter((t=>"remote"===t.type)),this._local&&await this._local.init();for(const t of this._remoteProviders)try{await t.init()}catch(e){this.canLogInfo()&&console.warn(`[Kritzel] Asset resolver remote provider "${t.name}" failed to initialize. Assets will be served from the local provider until the remote becomes available.`,e)}await this.recoverPendingUploads(),this._initialized=!0,this._resolveReady&&(this._resolveReady(),this._resolveReady=null,this._rejectReady=null),this.canLogInfo()&&this.logProviderConfiguration(),this._pending.size>0&&this.scheduleFlush(0)}destroy(){this.canLogInfo()&&console.info("[Kritzel] Asset resolver destroyed"),this._destroyed=!0,this._flushTimer&&(clearTimeout(this._flushTimer),this._flushTimer=null);for(const t of this._providers)try{t.destroy()}catch{}this._providers=[],this._local=null,this._remoteProviders=[],this._pending.clear(),this._resolvePromises.clear(),this._initialized=!1,this._rejectReady&&this._rejectReady(new Error("[KritzelAssetResolver] Destroyed before initialization completed.")),this._readyPromise=null,this._resolveReady=null,this._rejectReady=null}async put(t,e){await this.ensureReady();const i=e.id??this.generateUuid(),n={...e,id:i};let r=null;if(this._local&&(r=await this._local.put(t,n)),this._remoteProviders.length>0){const t=this._remoteProviders.map((t=>t.name));this._local&&await this._local.setPendingRemotes(i,t);for(const e of t)this._pending.set(this.pendingKey(i,e),{id:i,providerName:e,attempts:0,nextAttemptAt:Date.now()})}if(!r){if(0===this._remoteProviders.length)throw new Error("[KritzelAssetResolver] No providers configured to store asset.");r=await this._remoteProviders[0].put(t,n)}return this.scheduleFlush(0),r}async resolve(t){await this.ensureReady();const e=this._resolvePromises.get(t);if(e)return e;const i=(async()=>{if(this._local&&this._local.canResolve(t))return this._local.resolve(t);let e,i=0;for(const n of this._providers)if(n!==this._local){i++;try{const e=await n.fetch(t);if(this._local){try{await this._local.put(e,{id:t,mimeType:e.type||"application/octet-stream",kind:"file"})}catch{}return this._local.resolve(t)}return URL.createObjectURL(e)}catch(t){e=t}}if(0===i)throw new ho(t);throw new Error(`[KritzelAssetResolver] Failed to resolve asset ${t}: ${String(e)}`)})();this._resolvePromises.set(t,i);try{return await i}finally{this._resolvePromises.delete(t)}}async fetchBlob(t){let e;await this.ensureReady();let i=!1,n=!1,r=0;const s=this._local?[this._local,...this._providers.filter((t=>t!==this._local))]:this._providers;for(const o of s){o===this._local?i=!0:r++;try{return await o.fetch(t)}catch(t){o===this._local&&(n=!0),e=t}}if(0===r&&(!i||n))throw new ho(t);throw new Error(`[KritzelAssetResolver] Failed to fetch blob for ${t}: ${String(e)}`)}async putDataUrl(t,e){const i=await this.dataUrlToBlob(t);return this.put(i,{...e,mimeType:e.mimeType??i.type??"application/octet-stream"})}logProviderConfiguration(){const t=[`[Kritzel] Asset resolver initialized with ${this._providers.length} provider(s):`];for(const e of this._providers)t.push(` - ${e.name} [${e===this._local?"local (primary write target)":e.type}]`);this._local&&t.push(`Write strategy: local-first (${this._local.name} → immediate, remote → background queue)`),this._remoteProviders.length>0&&t.push(`Remote replication: ${this._remoteProviders.map((t=>t.name)).join(", ")}`),this._pending.size>0&&t.push(`Pending uploads recovered: ${this._pending.size}`),console.info(t.join("\n"))}instantiateProviders(t){return t.map((t=>"function"==typeof t?new t:t.create()))}pendingKey(t,e){return`${t}::${e}`}async recoverPendingUploads(){if(!this._local||0===this._remoteProviders.length)return;const t=await this._local.listAssetsWithPendingRemotes(),e=new Set(this._remoteProviders.map((t=>t.name))),i=Date.now();let n=0;for(const r of t){const t=(r.pendingRemotes??[]).filter((t=>e.has(t)));if(0!==t.length)for(const e of t)this._pending.set(this.pendingKey(r.id,e),{id:r.id,providerName:e,attempts:0,nextAttemptAt:i}),n++;else await this._local.setPendingRemotes(r.id,[])}this.canLogInfo()&&n>0&&console.info(`[Kritzel] Asset resolver recovered ${n} pending upload(s)`)}scheduleFlush(t){this._destroyed||(this._flushTimer&&clearTimeout(this._flushTimer),this._flushTimer=setTimeout((()=>{this._flushTimer=null,this.flushQueue()}),Math.max(0,t)))}async flushQueue(){if(this._destroyed)return;if(!this._local)return;const t=Date.now();let e=Number.POSITIVE_INFINITY;for(const[i,n]of Array.from(this._pending.entries())){if(n.nextAttemptAt>t){e=Math.min(e,n.nextAttemptAt-t);continue}const r=this._remoteProviders.find((t=>t.name===n.providerName));if(!r){this._pending.delete(i);continue}let s,o;try{[s,o]=await Promise.all([this._local.fetch(n.id),this._local.getMetadata(n.id)])}catch{this._pending.delete(i);continue}try{await r.put(s,{id:n.id,mimeType:o?.mimeType??s.type??"application/octet-stream",kind:o?.kind,width:o?.width,height:o?.height,durationMs:o?.durationMs,originalFilename:o?.originalFilename}),this._pending.delete(i),await this.clearPendingRemote(n.id,n.providerName),this.canLogInfo()&&console.info(`[Kritzel] Asset resolver uploaded ${n.id} to ${r.name}`)}catch(t){n.attempts+=1;const i=Math.min(3e5,2e3*Math.pow(2,n.attempts-1));n.nextAttemptAt=Date.now()+i,e=Math.min(e,i),this.canLogInfo()&&console.warn(`[Kritzel] Asset resolver upload to ${r.name} failed for ${n.id} (attempt ${n.attempts}). Retrying in ${Math.round(i/1e3)}s.`,t)}}this._pending.size>0&&Number.isFinite(e)&&this.scheduleFlush(e)}async clearPendingRemote(t,e){if(!this._local)return;const i=await this._local.getMetadata(t);if(!i)return;const n=(i.pendingRemotes??[]).filter((t=>t!==e));await this._local.setPendingRemotes(t,n)}ensureReady(){return this._initialized?Promise.resolve():this._destroyed?Promise.reject(new Error("[KritzelAssetResolver] Resolver was destroyed.")):this.getReadyPromise()}getReadyPromise(){return this._readyPromise||(this._readyPromise=new Promise(((t,e)=>{this._resolveReady=t,this._rejectReady=e}))),this._readyPromise}generateUuid(){if("undefined"!=typeof crypto&&"function"==typeof crypto.randomUUID)return crypto.randomUUID();const t=crypto.getRandomValues(new Uint8Array(16));t[6]=15&t[6]|64,t[8]=63&t[8]|128;const e=Array.from(t,(t=>t.toString(16).padStart(2,"0"))).join("");return`${e.slice(0,8)}-${e.slice(8,12)}-${e.slice(12,16)}-${e.slice(16,20)}-${e.slice(20)}`}async dataUrlToBlob(t){return(await fetch(t)).blob()}canLogInfo(){return!this._quiet}}class lo extends a{__class__="KritzelImage";assetId="";mimeType="";src="";maxWidth=300;maxHeight=300;maxCompressionSize=1200;resolvedSrc;loadState="idle";maxLoadAttempts=3;loadAttempts=0;maxTransientRetryDurationMs=3e4;transientRetryStartedAt=null;constructor(t){super(),this.assetId=t?.assetId||"",this.mimeType=t?.mimeType||"",this.src=t?.src||"",this.x=t?.x||0,this.y=t?.y||0,this.translateX=t?.translateX||0,this.translateY=t?.translateY||0,this.rotation=l.degreesToRadians(t?.rotation??0),this.scale=t?.scale||1,this.width=t?.width||0,this.height=t?.height||0,this.maxWidth=t?.maxWidth??300,this.maxHeight=t?.maxHeight??300,this.maxLoadAttempts=t?.maxLoadAttempts??3}static create(t,e){const i=new lo(e);return i._core=t,i.id=i.generateId(),i.workspaceId=t.store.state.activeWorkspace.id,i.userId=t.user?.id,i.x=e?.x??0,i.y=e?.y??0,i.translateX=e?.translateX??0,i.translateY=e?.translateY??0,i.scale=e?.scale??i._core.store.state.scale,i.rotation=l.degreesToRadians(e?.rotation??0),i.zIndex=t.store.currentZIndex,i}resize(t,e,i,n){if(i<=1||n<=1)return;const r=n/this.height;this.width=this.width*r,this.height=this.height*r,this.translateX=t,this.translateY=e,this._core.store.objects.update(this)}serialize(){const t=super.serialize();return delete t.resolvedSrc,delete t.loadState,delete t.loadAttempts,delete t.transientRetryStartedAt,t}adoptTransientStateFrom(t){t instanceof lo&&t.assetId===this.assetId&&(this.resolvedSrc=t.resolvedSrc,this.loadState=t.loadState,this.loadAttempts=t.loadAttempts,this.transientRetryStartedAt=t.transientRetryStartedAt)}ensureResolved(){if("loading"===this.loadState||"ready"===this.loadState)return;if("error"===this.loadState)return;if(!this.assetId)return;if(!this._core?.assetResolver)return;if(this.loadAttempts>=this.maxLoadAttempts)return void(this.loadState="error");this.loadState="loading";const t=this.loadAttempts;this._core.assetResolver.resolve(this.assetId).then((t=>{this.resolvedSrc=t,this.loadState="ready",this.transientRetryStartedAt=null,this._core?.rerender()})).catch((e=>{if(e instanceof ho){this.loadAttempts+=1,this.transientRetryStartedAt=null;const t=this.loadAttempts>=this.maxLoadAttempts;return console.warn(`[KritzelImage] Asset ${this.assetId} not found (attempt ${this.loadAttempts}/${this.maxLoadAttempts}):`,e),t?(this.loadState="error",void this._core?.rerender()):void this.scheduleRetry(this.loadAttempts)}const i=Date.now();null===this.transientRetryStartedAt&&(this.transientRetryStartedAt=i);const n=i-this.transientRetryStartedAt,r=n>=this.maxTransientRetryDurationMs;if(console.warn(`[KritzelImage] Transient resolve failure for asset ${this.assetId} (elapsed ${Math.round(n/1e3)}s/${Math.round(this.maxTransientRetryDurationMs/1e3)}s):`,e),r)return this.loadState="error",void this._core?.rerender();this.scheduleRetry(t+1)}))}scheduleRetry(t){this.loadState="idle";const e=Math.min(2e3,250*Math.pow(2,Math.max(0,t-1)));setTimeout((()=>{"idle"===this.loadState&&this.ensureResolved()}),e)}migrateLegacyDataUrlIfNeeded(){if(this.assetId)return;if(!this.src||!this.src.startsWith("data:"))return;if(!this._core?.assetResolver)return;const t=this.src;this.resolvedSrc=t,this.loadState="ready",this._core.assetResolver.putDataUrl(t,{kind:"image"}).then((t=>{this.assetId=t.id,this.mimeType=t.mimeType,this.src="",this._core?.store.objects?.update(this)})).catch((t=>{console.warn("[KritzelImage] Failed to migrate legacy data URL to asset storage:",t)}))}ensureLoaded(){this.assetId&&!this.resolvedSrc?this.ensureResolved():!this.assetId&&this.src?.startsWith("data:")&&this.migrateLegacyDataUrlIfNeeded()}async prepareForInsert(){if(this.assetId||!this.src)return;if(!this._core?.assetResolver)return;const t=this.src,e=await fetch(t);if(!e.ok)throw new Error(`Failed to load image source: ${t} (HTTP ${e.status})`);const i=await e.blob(),n=i.type||"image/png",{naturalWidth:r,naturalHeight:s}=await this.measureImageBlob(i),o=await this._core.assetResolver.put(i,{mimeType:n,kind:"image",width:r,height:s});if(this.assetId=o.id,this.mimeType=o.mimeType,this.width<=0||this.height<=0){const{scaledWidth:t,scaledHeight:e}=this.calculateScaledDimensions({width:r,height:s});this.width=t,this.height=e}this.resolvedSrc=await this._core.assetResolver.resolve(o.id),this.loadState="ready",this.src=""}async measureImageBlob(t){const e=URL.createObjectURL(t);try{return await new Promise(((t,i)=>{const n=new Image;n.onload=()=>t({naturalWidth:n.naturalWidth,naturalHeight:n.naturalHeight}),n.onerror=t=>i(t),n.src=e}))}finally{URL.revokeObjectURL(e)}}mount(t){super.mount(t),this.ensureLoaded()}static fromUrl(t,e){return new Promise(((i,n)=>{const r=new Image;r.onload=()=>{const n=new lo({...e,src:t}),{scaledWidth:s,scaledHeight:o}=n.calculateScaledDimensions(r);n.width=s,n.height=o,i(n)},r.onerror=t=>n(t),r.src=t}))}static async fromBlob(t,e,i){const n=URL.createObjectURL(e);try{const r=await new Promise(((t,e)=>{const i=new Image;i.onload=()=>t({naturalWidth:i.naturalWidth,naturalHeight:i.naturalHeight}),i.onerror=t=>e(t),i.src=n})),s=e.type||"image/png",o=await t.assetResolver.put(e,{mimeType:s,kind:"image",width:r.naturalWidth,height:r.naturalHeight}),h=lo.create(t,i);h.assetId=o.id,h.mimeType=o.mimeType;const{scaledWidth:a,scaledHeight:l}=h.calculateScaledDimensions({width:r.naturalWidth,height:r.naturalHeight});return h.width=a,h.height=l,h.resolvedSrc=await t.assetResolver.resolve(o.id),h.loadState="ready",h}finally{URL.revokeObjectURL(n)}}calculateScaledDimensions(t){let e=t.width,i=t.height;if(t.width>this.maxWidth||t.height>this.maxHeight){const n=Math.min(this.maxWidth/t.width,this.maxHeight/t.height);e=t.width*n,i=t.height*n}return{scaledWidth:e,scaledHeight:i}}}class uo{static isInstanceOf(t,e){return!!t&&t.__class__===e}}class co extends a{__class__="KritzelGroup";constructor(t){super(),this.rotation=l.degreesToRadians(t?.rotation??0)}childIds=[];_pendingChildren=[];unchangedChildSnapshots=new Map;snapshotRotation=0;snapshotTranslateX=0;snapshotTranslateY=0;snapshotTotalWidth=0;snapshotTotalHeight=0;snapshotScale=1;get children(){return this._core?this.childIds.map((t=>{const e=this._core.store.objects.filter((e=>e.id===t));return e.length>0?e[0]:null})).filter((t=>null!==t)):this._pendingChildren}get length(){return this.childIds.length}static create(t,e){const i=new co(e);return i._core=t,i.id=i.generateId(),i.workspaceId=t.store.state.activeWorkspace.id,i.userId=t.user?.id,i.scale=t.store.state.scale,i.zIndex=t.store.currentZIndex,i}static createFromObjects(t,e){const i=co.create(t);return e.forEach((t=>{i.childIds.push(t.id)})),i.refreshBoundingBox(),i.captureChildSnapshots(),i}static findParentGroup(t,e){const i=t.store.objects.filter((t=>"KritzelGroup"===t.__class__));for(const t of i)if(t.childIds.includes(e))return t;return null}static collectDescendantIds(t,e=new Set){for(const i of t.children)e.add(i.id),i instanceof co&&co.collectDescendantIds(i,e);return e}addChild(t){if(!this.childIds.includes(t.id)){if(this.childIds.push(t.id),!this._core)return void this._pendingChildren.push(t);this.refreshBoundingBox(),this.captureChildSnapshots()}}removeChild(t){const e=this.childIds.indexOf(t);-1!==e&&(this.childIds.splice(e,1),this.refreshBoundingBox(),this.captureChildSnapshots())}ungroup(){return this.children}finalize(){for(const t of this.children)t instanceof co&&t.finalize();this.refreshBoundingBox(),this.captureChildSnapshots()}centerInViewport(){const{viewportWidth:t,viewportHeight:e,translateX:i,translateY:n,scale:r}=this._core.store.state,{x:s,y:o,width:h,height:a}=this.rotatedBoundingBox,l=(t/2-i)/r-(s+h/2),u=(e/2-n)/r-(o+a/2);this.translateX+=l,this.translateY+=u,this.children.forEach((t=>{t.translateX+=l,t.translateY+=u})),this.captureChildSnapshots()}refreshBoundingBox(){if(0===this.children.length)return this.width=0,this.height=0,this.translateX=0,void(this.translateY=0);if(1===this.children.length){const t=this.children[0];return this.translateX=t.boundingBox.x,this.translateY=t.boundingBox.y,this.width=t.boundingBox.width*this.scale,void(this.height=t.boundingBox.height*this.scale)}const t=this.rotation,e=Math.cos(-t),i=Math.sin(-t);let n=1/0,r=-1/0,s=1/0,o=-1/0;this.children.forEach((t=>{const h=t.rotatedPolygon;[h.topLeft,h.topRight,h.bottomRight,h.bottomLeft].forEach((t=>{const h=t.x*e-t.y*i,a=t.x*i+t.y*e;h<n&&(n=h),h>r&&(r=h),a<s&&(s=a),a>o&&(o=a)}))}));const h=o-s;this.width=(r-n-this.padding)*this.scale,this.height=(h-this.padding)*this.scale;const a=(n+r)/2,l=(s+o)/2,u=Math.cos(t),c=Math.sin(t),f=a*c+l*u;this.translateX=a*u-l*c-(this.width/this.scale+2*this.padding)/2,this.translateY=f-(this.height/this.scale+2*this.padding)/2}captureChildSnapshots(){this.unchangedChildSnapshots.clear(),this.snapshotRotation=this.rotation,this.snapshotTranslateX=this.translateX,this.snapshotTranslateY=this.translateY,this.snapshotTotalWidth=this.totalWidth,this.snapshotTotalHeight=this.totalHeight,this.snapshotScale=this.scale||1,this.children.forEach((t=>{this.unchangedChildSnapshots.set(t.id,{id:t.id,translateX:t.translateX,translateY:t.translateY,rotation:t.rotation,width:t.width,height:t.height,totalWidth:t.totalWidth,totalHeight:t.totalHeight,scale:t.scale})}))}move(t,e,i,n){const r=(t-i)/this._core.store.state.scale,s=(e-n)/this._core.store.state.scale;this.translateX+=r,this.translateY+=s,this._core.store.objects.transaction((()=>{this._core.store.objects.update(this),this.children.forEach((r=>{r.move(t,e,i,n),this._core.anchorManager.updateAnchorsForObject(r.id)}))})),this.unchangedChildSnapshots.forEach((t=>{t.translateX+=r,t.translateY+=s}))}resize(t,e,i,n){const r=this.snapshotTotalWidth>0?this.snapshotTotalWidth-2*this.padding:this.width,s=this.snapshotTotalHeight>0?this.snapshotTotalHeight-2*this.padding:this.height,o=this.snapshotScale||this.scale||1,h=0!==r?i/r:1,a=0!==s?n/s:1,l=this.snapshotTranslateX+(this.snapshotTotalWidth||this.width+2*this.padding)/2/o,u=this.snapshotTranslateY+(this.snapshotTotalHeight||this.height+2*this.padding)/2/o,c=t+(i+2*this.padding)/2/this.scale,f=e+(n+2*this.padding)/2/this.scale,d=this.rotation,p=Math.cos(-d),g=Math.sin(-d),m=Math.cos(d),w=Math.sin(d);this._core.store.objects.transaction((()=>{this.children.forEach((t=>{const e=this.unchangedChildSnapshots.get(t.id),i=e?e.width:t.width,n=e?e.height:t.height,r=(e?e.scale:t.scale)||1,s=(e?e.translateX:t.translateX)+(e?e.totalWidth:t.totalWidth)/2/r-l,o=(e?e.translateY:t.translateY)+(e?e.totalHeight:t.totalHeight)/2/r-u,v=(s*p-o*g)*h,y=(s*g+o*p)*a,b=c+(v*m-y*w),k=f+(v*w+y*m),M=(e?e.rotation:t.rotation)-d,S=Math.cos(M),x=Math.sin(M),A=i*Math.sqrt(Math.pow(h*S,2)+Math.pow(a*x,2)),$=n*Math.sqrt(Math.pow(h*x,2)+Math.pow(a*S,2));t.resize(b-(A+2*t.padding)/2/t.scale,k-($+2*t.padding)/2/t.scale,A,$),this._core.anchorManager.updateAnchorsForObject(t.id)})),this.refreshBoundingBox(),this._core.store.state.isResizing||this.captureChildSnapshots(),this._core.store.objects.update(this)}))}rotate(t){this.rotation=t;const e=this.translateX+this.totalWidth/2/this.scale,i=this.translateY+this.totalHeight/2/this.scale,n=t-this.snapshotRotation,r=Math.cos(n),s=Math.sin(n);this._core.store.objects.transaction((()=>{this._core.store.objects.update(this),this.children.forEach((o=>{const h=this.unchangedChildSnapshots.get(o.id);if(!h)return;const a=this.getOffsetXToCenterFromSnapshot(h),l=this.getOffsetYToCenterFromSnapshot(h),u=s*a+r*l;o.translateX=e+(r*a-s*l)-o.totalWidth/2/o.scale,o.translateY=i+u-o.totalHeight/2/o.scale,o.rotate(1===this.children.length?t:h.rotation+n)}))}))}getOffsetXToCenterFromSnapshot(t){return t.translateX+t.totalWidth/t.scale/2-(this.snapshotTranslateX+this.snapshotTotalWidth/(this.snapshotScale||this.scale||1)/2)}getOffsetYToCenterFromSnapshot(t){return t.translateY+t.totalHeight/t.scale/2-(this.snapshotTranslateY+this.snapshotTotalHeight/(this.snapshotScale||this.scale||1)/2)}hitTest(t,e){return this.children.some((i=>i.hitTest(t,e)))}hitTestPolygon(t){return this.children.some((e=>e.hitTestPolygon(t)))}copy(){const t=co.create(this._core),e=[];return this.children.sort(((t,e)=>t.zIndex-e.zIndex)).forEach((i=>{const n=i.copy();e.push(n),t.childIds.push(n.id)})),t._pendingChildren=e,t.rotation=this.rotation,t.translateX=this.translateX,t.translateY=this.translateY,t.width=this.width,t.height=this.height,t}serialize(){const{_core:t,_elementRef:e,element:i,totalWidth:n,totalHeight:r,unchangedChildSnapshots:s,_pendingChildren:o,...h}=this,a=structuredClone(h);return a.unchangedChildSnapshots=Object.fromEntries(this.unchangedChildSnapshots),a}deserialize(t){return super.deserialize(t),t.unchangedChildSnapshots&&(this.unchangedChildSnapshots=new Map(Object.entries(t.unchangedChildSnapshots))),this}update(){this._core.store.objects.update(this)}updateWorkspaceId(t){this.workspaceId=t,this.children.forEach((e=>{e.workspaceId=t,uo.isInstanceOf(e,"KritzelGroup")&&e.updateWorkspaceId(t)}))}}var fo;!function(t){t.Rectangle="rectangle",t.Ellipse="ellipse",t.Triangle="triangle"}(fo||(fo={}));class po extends a{__class__="KritzelShape";shapeType=fo.Rectangle;fillColor={light:"transparent",dark:"transparent"};strokeColor={light:"#000000",dark:"#ffffff"};strokeWidth=4;fontFamily="Arial";fontSize=16;fontColor={light:"#000000",dark:"#ffffff"};x=0;y=0;scale=1;scaleFactor=1;isDebugInfoVisible=!0;isEditable=!0;isEditing=!1;editor=null;content=null;_schema=new It({nodes:Ts(ks.spec.nodes,"paragraph block*","block"),marks:ks.spec.marks});uneditedObject=null;get viewBox(){return`${this.x} ${this.y} ${this.width} ${this.height}`}constructor(t){super(),this.editor=this.createEditor(),t&&(this.x=t.x??0,this.y=t.y??0,this.translateX=t.translateX??0,this.translateY=t.translateY??0,this.rotation=l.degreesToRadians(t.rotation??0),this.width=t.width??100,this.height=t.height??100,this.shapeType=t.shapeType??fo.Rectangle,this.fillColor=t.fillColor??{light:"transparent",dark:"transparent"},this.strokeColor=t.strokeColor??t.fillColor??{light:"#000000",dark:"#ffffff"},this.strokeWidth=t.strokeWidth??4,this.fontSize=t.fontSize??16,this.fontFamily=t.fontFamily??"Arial",this.fontColor=t.fontColor??g.determineTextColor(this.fillColor),this.scale=t.scale,this.scaleFactor=t.scaleX??1)}static create(t,e){const i=new po;return i._core=t,i.id=i.generateId(),i.workspaceId=t.store.state.activeWorkspace.id,i.userId=t.user?.id,i.x=e?.x??0,i.y=e?.y??0,i.translateX=e?.translateX??0,i.translateY=e?.translateY??0,i.rotation=l.degreesToRadians(e?.rotation??0),i.width=e?.width??100,i.height=e?.height??100,i.shapeType=e?.shapeType??fo.Rectangle,i.fillColor=e?.fillColor??{light:"transparent",dark:"transparent"},i.strokeColor=e?.strokeColor??e?.fillColor??{light:"#000000",dark:"#ffffff"},i.strokeWidth=e?.strokeWidth??4,i.opacity=e?.opacity??1,i.fontSize=e?.fontSize??16,i.fontFamily=e?.fontFamily??"Arial",i.fontColor=e?.fontColor??g.determineTextColor(i.fillColor),i.backgroundColor={light:"transparent",dark:"transparent"},i.scaleFactor=1,i.scale=e?.scale??t.store.state.scale,i.zIndex=t.store.currentZIndex,i.updateDimensions(),i}updateDimensions(){this.translateX=(this.x+this.translateX)/this.scale,this.translateY=(this.y+this.translateY)/this.scale}mount(t){null!==t&&!1!==this.isInViewport()&&(this.isMounted&&this.elementRef===t&&this.editor.dom.parentElement===t||(this.elementRef=t,this.isMounted=!0))}mountTextEditor(t){null!==t&&(t.style.fontFamily=this.fontFamily,t.style.fontSize=`${this.fontSize}pt`,t.style.color=g.resolveThemeColor(this.fontColor),t.style.whiteSpace="pre-wrap",t.style.wordWrap="break-word",this.editor.dom.parentElement!==t&&(t.innerHTML="",t.appendChild(this.editor.dom)))}createEditor(){const t=this._schema.node("doc",null,[this._schema.node("paragraph")]);return new hs(null,{state:qe.create({doc:t,plugins:[Fs(io)]}),editable:()=>!1,dispatchTransaction:t=>{const e=this.editor.state.apply(t);this.editor.updateState(e),t.docChanged&&(this.content=e.doc.toJSON(),t.getMeta("fromRemote")||this._core.store.objects.update(this,{temporary:!0}))}})}setContent(t){if(this.content=t,this.editor&&t){const e=this.editor.state.schema.nodeFromJSON(t),i=this.editor.state.tr.replaceWith(0,this.editor.state.doc.content.size,e.content);i.setMeta("fromRemote",!0),this.editor.dispatch(i)}}resize(t,e,i,n){i<=1||n<=1||(this.width=i,this.height=n,this.translateX=t,this.translateY=e,this._core.store.objects.update(this))}focus(t){if(!this.editor)return;const e=this.editor.state.doc;if(t&&Number.isFinite(t.x)&&Number.isFinite(t.y)){const i=this.editor.posAtCoords({left:t.x,top:t.y});if(i)return this.editor.dispatch(this.editor.state.tr.setSelection(_e.create(e,i.pos))),this.editor.focus(),void(v.isIOS()&&this.scrollIntoViewOnIOS())}const i=Math.max(1,e.content.size-1);this.editor.dispatch(this.editor.state.tr.setSelection(_e.create(e,i))),this.editor.focus(),v.isIOS()&&this.scrollIntoViewOnIOS()}scrollIntoViewOnIOS(){setTimeout((()=>{this.editor&&this.editor.dom&&this.editor.dom.scrollIntoView({behavior:"smooth",block:"center",inline:"nearest"})}),300)}edit(t){_.disableInteractiveWidget(),this.uneditedObject=this.clone();const e="number"==typeof t?.clientX&&"number"==typeof t?.clientY?{x:t.clientX,y:t.clientY}:void 0;this._core.store.setState("activeTool",this._core.toolRegistry.getTool("shape")),this.editor.setProps({editable:()=>!0}),this.isEditing=!0,this._core.rerender(),e&&this.focus(e),v.isIOS()&&e&&requestAnimationFrame((()=>{this.isEditing&&this.focus(e)})),_.enableInteractiveWidget()}save(){this.content=this.editor.state.doc.toJSON(),this.editor.setProps({editable:()=>!1}),this.editor.dom.blur(),this.isEditing=!1,this._core.store.objects.consolidateTemporaryItems(),this._core.store.objects.update(this),this._core.engine.emitObjectsChange()}handleEscape(){if(!this.editor||!this.isEditing)return;const{state:t}=this.editor;if(!t.selection.empty)return this.editor.dispatch(t.tr.setSelection(_e.create(t.doc,t.selection.head))),void this.editor.focus();this._core.resetActiveShape(),this._core.clearSelection(),this._core.store.setState("activeTool",this._core.toolRegistry.getTool("selection"))}handlePointerDown(t){this.isEditing&&(this._core.store.state.pointers.has(t.pointerId)||t.stopPropagation())}handlePointerMove(t){this.isEditing&&(this._core.store.state.pointers.has(t.pointerId)||t.stopPropagation())}handlePointerUp(t){this.isEditing&&(this._core.store.state.pointers.has(t.pointerId)||t.stopPropagation())}copy(){const t=super.copy();return t.editor=t.createEditor(),this.content&&t.setContent(this.content),t}serialize(){const{_core:t,_elementRef:e,_schema:i,element:n,totalWidth:r,totalHeight:s,editor:o,uneditedObject:h,...a}=this,l=structuredClone(a);return n&&"object"==typeof n&&"nodeType"in n&&1===n.nodeType&&(l.element=n.cloneNode(!0)),l}deserialize(t){return super.deserialize(t),t.content&&this.setContent(t.content),this}onAfterUpdate(t){t.includes("fillColor")?(this.fontColor=g.determineTextColor(this.fillColor),this.editor?.dom?.parentElement&&(this.editor.dom.parentElement.style.color=g.resolveThemeColor(this.fontColor))):t.includes("fontColor")&&this.editor?.dom?.parentElement&&(this.editor.dom.parentElement.style.color=g.resolveThemeColor(this.fontColor))}getClipPolygon(){const t=this.totalWidth/this.scale,e=this.totalHeight/this.scale,i=this.translateX+t/2,n=this.translateY+e/2,r=this.strokeWidth/this.scale/2;switch(this.shapeType){case fo.Ellipse:return u.getEllipsePolygonApproximation(i,n,t/2+r,e/2+r,32,this.rotation);case fo.Triangle:const s=(t,e)=>{const s=t-i,o=e-n,h=Math.sqrt(s*s+o*o);if(0===h)return{x:t,y:e};const a=(h+r)/h;return{x:i+s*a,y:n+o*a}},o=this.translateX,h=this.translateY+e,a=this.translateX+t,l=this.translateY+e,c=s(this.translateX+t/2,this.translateY),f=s(a,l),d=s(o,h);if(0!==this.rotation){const t=Math.cos(this.rotation),e=Math.sin(this.rotation),r=r=>{const s=r.x-i,o=r.y-n;return{x:i+s*t-o*e,y:n+s*e+o*t}};return[r(c),r(f),r(d)]}return[c,f,d];default:return null}}getSvgPath(){const t=this.width,e=this.height;switch(this.shapeType){case fo.Rectangle:return`M ${this.x} ${this.y} L ${this.x+t} ${this.y} L ${this.x+t} ${this.y+e} L ${this.x} ${this.y+e} Z`;case fo.Ellipse:const i=this.x+t/2,n=this.y+e/2,r=t/2,s=e/2;return`M ${i-r} ${n} A ${r} ${s} 0 1 0 ${i+r} ${n} A ${r} ${s} 0 1 0 ${i-r} ${n}`;case fo.Triangle:return`M ${this.x+t/2} ${this.y} L ${this.x+t} ${this.y+e} L ${this.x} ${this.y+e} Z`;default:return`M ${this.x} ${this.y} L ${this.x+t} ${this.y} L ${this.x+t} ${this.y+e} L ${this.x} ${this.y+e} Z`}}}const go="__kritzelCustomElementRendererRegistry__";class mo{static get _renderers(){return(()=>{const t=globalThis,e=t[go];if(e)return e;const i={renderers:new Map};return t[go]=i,i})().renderers}static register(t,e){this._renderers.set(t,e)}static get(t){return this._renderers.get(t)}static unregister(t){return this._renderers.delete(t)}}class wo extends a{__class__="KritzelCustomElement";element;rendererKey=null;rendererData;constructor(t){super(),t&&(this.translateX=t.translateX||0,this.translateY=t.translateY||0,this.rotation=l.degreesToRadians(t.rotation??0),this.scale=t.scale||1,this.element=t.element??this.createPlaceholder(),this.height=t.height||0,this.width=t.width||0,this.rendererKey=t.rendererKey??null,this.rendererData=t.rendererData)}static create(t,e){const i=new wo(e);return i._core=t,i.id=i.generateId(),i.workspaceId=t.store.state.activeWorkspace.id,i.userId=t.user?.id,i.zIndex=t.store.currentZIndex,i}mount(t){if(null!==t){if(this.applyInteractiveState(),this.isMounted&&this.elementRef===t){if(this.rendererKey)return;if(this.element.parentElement===t)return}if(this.elementRef=t,this.isMounted=!0,this.rendererKey){const e=mo.get(this.rendererKey);if(e)return t.innerHTML="",e.onMount({object:this,container:t,data:this.rendererData}),void this.applyInteractiveState()}this.elementRef.innerHTML="",this.elementRef.appendChild(this.element),this.applyInteractiveState()}}setIsInteractive(t){const e=this.isInteractive!==t;this.isInteractive=t,this.applyInteractiveState(),e&&!t&&this.blurFocusedDescendant()}applyInteractiveState(){const t=this.isInteractive?"auto":"none",e=this.isInteractive?"auto":"";this.element&&(this.element.style.pointerEvents=t,this.element.style.cursor=e),this.elementRef instanceof HTMLElement&&(this.elementRef.style.pointerEvents="auto",this.elementRef.style.cursor="",Array.from(this.elementRef.children).forEach((i=>{i instanceof HTMLElement&&(i.style.pointerEvents=t,i.style.cursor=e)})))}blurFocusedDescendant(){if(!(this.element||this.elementRef instanceof HTMLElement))return;const t=this.getDeepActiveElement(),e=!!this.element&&this.isNodeInsideHost(t,this.element),i=this.elementRef instanceof HTMLElement&&this.isNodeInsideHost(t,this.elementRef);t&&(e||i)&&t.blur()}hasFocusedInputElement(){if(!this.isInteractive)return!1;const t=this.getFocusHosts();if(t.some((t=>this.hasFocusedInputDescendant(t))))return!0;const e=this.getDeepActiveElement();return!!(e&&this.isInputLikeElement(e)&&t.some((t=>this.isNodeInsideHost(e,t))))}getFocusHosts(){const t=[];if(this.element&&t.push(this.element),this.elementRef instanceof HTMLElement){t.push(this.elementRef);const e=this.elementRef.firstElementChild;e instanceof HTMLElement&&t.push(e)}return t}hasFocusedInputDescendant(t){if(this.isInputLikeElement(t)&&this.matchesFocus(t))return!0;if("function"==typeof t.matches)try{if(!t.matches(":focus-within"))return!1}catch{}return null!==this.findFocusedInputLikeElement(t)}findFocusedInputLikeElement(t){let e=null;try{e=t.querySelector(":focus")}catch{e=null}return e instanceof HTMLElement?this.isInputLikeElement(e)?e:e.shadowRoot?this.findFocusedInputLikeElement(e.shadowRoot):null:null}matchesFocus(t){if("function"!=typeof t.matches)return!1;try{return t.matches(":focus")}catch{return!1}}isInputLikeElement(t){const e=t.tagName;return"INPUT"===e||"TEXTAREA"===e||"SELECT"===e||t.isContentEditable}isNodeInsideHost(t,e){if(!t)return!1;let i=t;for(;i;){if(i===e)return!0;if(i.parentNode){i=i.parentNode;continue}const t=i.getRootNode();if(!(t instanceof ShadowRoot))break;i=t.host}return!1}getDeepActiveElement(t=document){const e=t.activeElement;return e instanceof HTMLElement?e.shadowRoot?this.getDeepActiveElement(e.shadowRoot)??e:e:null}unmount(){if(this.isMounted&&this.elementRef){if(this.rendererKey){const t=mo.get(this.rendererKey);if(t){const e=t.onUnmount({object:this,container:this.elementRef,data:this.rendererData});void 0!==e&&(this.rendererData=e)}}this.isMounted=!1,this.elementRef=null}}isElementScrollable(){return!!$.findScrollableElement(this.element)}createPlaceholder(){const t=document.createElement("div");return t.textContent="[Custom Element]",t.style.border="1px dashed #ccc",t.style.display="flex",t.style.alignItems="center",t.style.justifyContent="center",t.style.backgroundColor="#f9f9f9",t.style.color="#999",t.style.fontSize="12px",t}resize(t,e,i,n){i<=1||n<=1||(this.width=i,this.height=n,this.translateX=t,this.translateY=e,this.element&&(this.element.style.width=`${i}px`,this.element.style.height=`${n}px`),this._core.store.objects.update(this))}copy(){const t=Object.create(Object.getPrototypeOf(this));return Object.assign(t,this),t.id=this.generateId(),t.isMounted=!1,t.isSelected=!1,t.isHovered=!1,t.isInteractive=!1,t.resizing=!1,t.markedForRemoval=!1,t.isVisible=!0,t.element=this.element.cloneNode(!0),t}serialize(){const{_core:t,_elementRef:e,element:i,totalWidth:n,totalHeight:r,isSelected:s,isHovered:o,isMounted:h,isInteractive:a,resizing:l,markedForRemoval:u,isVisible:c,...f}=this,d=structuredClone(f);return d.rendererKey=this.rendererKey,d.rendererData=this.rendererData,d.htmlString=i?i.outerHTML:"",d.serializedWidth=this.width,d.serializedHeight=this.height,d}deserialize(t){if(super.deserialize(t),delete this.allowEmbeddedInteraction,this.rendererKey=t.rendererKey??null,this.rendererData=t.rendererData,t.htmlString)try{const e=document.createElement("div");e.innerHTML=t.htmlString,this.element=e.firstElementChild||this.createPlaceholder()}catch{this.element=this.createPlaceholder()}else this.element=this.createPlaceholder();return this}}class vo{__class__=this.constructor.name;toolType="base";name="base-tool";_core;constructor(t){this._core=t}onActivate(){}onDeactivate(){}handlePointerDown(t){}handlePointerMove(t){}handlePointerUp(t){}handleWheel(t){}serialize(){return{__class__:this.__class__,name:this.name}}deserialize(t){return Object.assign(this,t),this}}class yo{static isRightClick(t){return t.button===o.Right}static isLeftClick(t){return t.button===o.Left}static isPointerEventOnContextMenu(t){return!!t.composedPath().find((t=>t.classList&&t.classList.contains("context-menu")))}static onLongPress(t,e,i){if("touch"!==t.pointerType)return i?.(),()=>{};const n=t.clientX,r=t.clientY,s=t.target;if(!s)return i?.(),()=>{};const o=setTimeout((()=>{c(),e(t)}),400),h=()=>{clearTimeout(o),c(),i?.()},a=t=>{(Math.abs(t.clientX-n)>10||Math.abs(t.clientY-r)>10)&&h()},l=()=>{h()},u=()=>{h()},c=()=>{s.removeEventListener("pointermove",a),s.removeEventListener("pointerup",l),s.removeEventListener("pointercancel",u)};return s.addEventListener("pointermove",a,{passive:!0}),s.addEventListener("pointerup",l,{once:!0}),s.addEventListener("pointercancel",u,{once:!0}),h}}const bo=[4,6,8,12,16,24],ko=[8,10,12,16,20,24];class Mo extends vo{toolType="brush";color=m[0];size=6;opacity=1;palette=[...m];sizes=[...bo];static MIN_POINT_DISTANCE_PX=3;_currentPathId=null;shouldAppendPoint(t,e,i,n){const r=t.points;if(!r||0===r.length)return!0;const s=r[r.length-1],o=e-s[0],h=i-s[1],a=Mo.MIN_POINT_DISTANCE_PX/n;return o*o+h*h>=a*a}constructor(t){super(t)}handlePointerDown(t){if(t.cancelable&&t.preventDefault(),"mouse"===t.pointerType&&yo.isLeftClick(t)){this._core.store.state.isDrawing=!0;const e=this._core.store.state.scale,i=this._core.store.state.lockDrawingScale,n=i?e:1,r=c.create(this._core,{points:[[(t.clientX-this._core.store.offsetX)/n,(t.clientY-this._core.store.offsetY)/n]],translateX:-this._core.store.state.translateX/n,translateY:-this._core.store.state.translateY/n,scale:i?1:e,fill:this.color,strokeWidth:this.size,opacity:this.opacity});r.isCompleted=!1,this._currentPathId=r.id,this._core.store.objects.insert(r),this._core.store.objects?.setActiveDrawingObject(r.id)}if("touch"===t.pointerType||"pen"===t.pointerType){const t=Array.from(this._core.store.state.pointers.values());if(1===t.length){const e=this._core.store.state.scale,i=this._core.store.state.lockDrawingScale,n=i?e:1,r=Math.round((t[0].clientX-this._core.store.offsetX)/n),s=Math.round((t[0].clientY-this._core.store.offsetY)/n);this._core.store.state.isDrawing=!0;const o=c.create(this._core,{points:[[r,s]],translateX:-this._core.store.state.translateX/n,translateY:-this._core.store.state.translateY/n,scale:i?1:e,fill:this.color,strokeWidth:this.size,opacity:this.opacity});o.isCompleted=!1,this._currentPathId=o.id,this._core.store.objects.insert(o),this._core.store.objects?.setActiveDrawingObject(o.id)}}}handlePointerMove(t){if(t.cancelable&&t.preventDefault(),"mouse"===t.pointerType&&this._core.store.state.isDrawing&&this._currentPathId){const e=this._core.store.objects.findById(this._currentPathId);if(e){const i=this._core.store.state.scale,n=this._core.store.state.lockDrawingScale,r=n?i:1,s=(t.clientX-this._core.store.offsetX)/r,o=(t.clientY-this._core.store.offsetY)/r;if(!this.shouldAppendPoint(e,s,o,r))return;const h=c.create(this._core,{points:[...e.points,[s,o]],translateX:-this._core.store.state.translateX/r,translateY:-this._core.store.state.translateY/r,scale:n?1:i,fill:this.color,strokeWidth:this.size,opacity:this.opacity});h.id=e.id,h.workspaceId=e.workspaceId,h.zIndex=e.zIndex,h.isCompleted=!1,this._core.store.objects.update(h)}}if("touch"===t.pointerType||"pen"===t.pointerType){const t=Array.from(this._core.store.state.pointers.values());if(1===t.length&&this._currentPathId){const e=this._core.store.objects.findById(this._currentPathId);if(e){const i=this._core.store.state.scale,n=this._core.store.state.lockDrawingScale,r=n?i:1,s=Math.round((t[0].clientX-this._core.store.offsetX)/r),o=Math.round((t[0].clientY-this._core.store.offsetY)/r);if(!this.shouldAppendPoint(e,s,o,r))return;const h=c.create(this._core,{points:[...e.points,[s,o]],translateX:-this._core.store.state.translateX/r,translateY:-this._core.store.state.translateY/r,scale:n?1:i,fill:this.color,strokeWidth:this.size,opacity:this.opacity});h.id=e.id,h.workspaceId=e.workspaceId,h.zIndex=e.zIndex,h.isCompleted=!1,this._core.store.objects.update(h)}}}}handlePointerUp(t){if(t.cancelable&&t.preventDefault(),"mouse"===t.pointerType&&this._core.store.state.isDrawing&&(this._core.store.state.isDrawing=!1,this._currentPathId)){const t=this._core.store.objects.findById(this._currentPathId);t&&(t.isCompleted=!0,this._core.store.objects.update(t),this._core.engine.emitObjectsChange(),this._core.engine.emitObjectsAdded([t])),this._core.store.objects?.setActiveDrawingObject(null),this._currentPathId=null,this._core.store.objects?.stopUndoCapturing()}if(("touch"===t.pointerType||"pen"===t.pointerType)&&this._core.store.state.isDrawing&&(this._core.store.state.isDrawing=!1,this._currentPathId)){const t=this._core.store.objects.findById(this._currentPathId);t&&(t.isCompleted=!0,this._core.store.objects.update(t),this._core.engine.emitObjectsChange(),this._core.engine.emitObjectsAdded([t])),this._core.store.objects?.setActiveDrawingObject(null),this._currentPathId=null,this._core.store.objects?.stopUndoCapturing()}}}class So extends a{__class__="KritzelSelectionGroup";constructor(t){super(),this.rotation=l.degreesToRadians(t?.rotation??0)}_objectIds=[];_cachedObjects=null;_cachedObjectIdsHash="";unchangedObjectSnapshots=new Map;snapshotRotation=0;snapshotWidth=0;snapshotHeight=0;snapshotTranslateX=0;snapshotTranslateY=0;clientId;minX=0;maxX=0;minY=0;maxY=0;handleColor;handleStrokeColor;handleSize=6;_lastChildPersistTime=0;static CHILD_PERSIST_THROTTLE_MS=100;static DIMENSION_EPSILON=.001;get objectIds(){return this._objectIds}set objectIds(t){this._objectIds=t,this._cachedObjects=null}invalidateObjectsCache(){this._cachedObjects=null}get objects(){const t=this._objectIds.join(",");if(null!==this._cachedObjects&&this._cachedObjectIdsHash===t)return this._cachedObjects;const e=new Set(this._objectIds),i=this._core.store.objects.filter((t=>e.has(t.id))),n=new Map(i.map((t=>[t.id,t])));return this._cachedObjects=this._objectIds.map((t=>n.get(t))).filter((t=>void 0!==t)),this._cachedObjectIdsHash=t,this._cachedObjects}syncChildSelectionState(t){const e=!0===this.isSelected;for(const i of t)i.isSelected=e}shouldSyncChildSelectionState(){const t=this._core.store.objects?.localClientId??null;if(null!=t&&null!=this.clientId)return this.clientId===t;const e=this._core.user?.id??null;return null!=e&&null!=this.userId?this.userId===e:null==this.userId}get length(){return this.objectIds.length}static create(t,e){const i=new So(e);return i._core=t,i.id=i.generateId(),i.workspaceId=t.store.state.activeWorkspace.id,i.userId=t.user?.id,i.clientId=t.store.objects?.localClientId??void 0,i.scale=t.store.state.scale,i.zIndex=99999,i.borderColor=void 0,i.borderWidth=2,i.handleColor=void 0,i.handleStrokeColor=void 0,i.handleSize=6,i}addObjects(t){let e=!1;for(const i of t)this._objectIds.includes(i.id)||(this._objectIds.push(i.id),i.isSelected=!0,e=!0);if(e){this._cachedObjects=null;const t=this.objects;1===t.length?this.rotation=t[0].rotation:t.length>1&&(this.rotation=0),this.captureUnchangedSnapshots(t),this.refreshObjectDimensions(t)}}addOrRemove(t){const e=this._objectIds.findIndex((e=>e===t.id));-1===e?(this._objectIds.push(t.id),t.isSelected=!0):(this._objectIds.splice(e,1),t.isSelected=!1),this._cachedObjects=null;const i=this.objects;1===i.length?this.rotation=i[0].rotation:i.length>1&&(this.rotation=0),this.captureUnchangedSnapshots(i),this.refreshObjectDimensions(i)}beginTransform(){const t=this.objects;this.refreshObjectDimensions(t),this.captureUnchangedSnapshots(t);for(const e of t)uo.isInstanceOf(e,"KritzelGroup")&&e.finalize()}deselectAllChildren(){const t=this.objects,e=new Set;for(const i of t)i.isSelected=!1,uo.isInstanceOf(i,"KritzelGroup")&&co.collectDescendantIds(i,e);if(e.size>0){const t=this._core.store.objects.filter((t=>e.has(t.id)));for(const e of t)e.isSelected=!1}}updateWorkspaceId(t){this.workspaceId=t;const e=this.objects;for(const i of e)i.workspaceId=t}updateZIndices(t){const e=this.objects;for(let i=0;i<e.length;i++)e[i].zIndex=t+i}updatePosition(t,e){const i=this.objects;for(const n of i)n.updatePosition(t+(n.translateX-this.translateX),e+(n.translateY-this.translateY));this.unchangedObjectSnapshots.forEach((i=>{const n=i.translateY-this.translateY;i.translateX=t+(i.translateX-this.translateX),i.translateY=e+n})),this.translateX=t,this.translateY=e,this._core.store.objects.update(this)}captureUnchangedSnapshots(t){this.unchangedObjectSnapshots.clear(),this.snapshotRotation=this.rotation,this.snapshotWidth=this.width,this.snapshotHeight=this.height,this.snapshotTranslateX=this.translateX,this.snapshotTranslateY=this.translateY,(t??this.objects).forEach((t=>{this.unchangedObjectSnapshots.set(t.id,{id:t.id,translateX:t.translateX,translateY:t.translateY,rotation:t.rotation,width:t.width,height:t.height,totalWidth:t.totalWidth,totalHeight:t.totalHeight,scale:t.scale})}))}serialize(){const{_core:t,_elementRef:e,element:i,totalWidth:n,totalHeight:r,unchangedObjectSnapshots:s,_cachedObjects:o,_cachedObjectIdsHash:h,snapshotWidth:a,snapshotHeight:l,snapshotTranslateX:u,snapshotTranslateY:c,snapshotRotation:f,...d}=this,p=structuredClone(d);return p.objectIds=this.objectIds,delete p._objectIds,i&&"object"==typeof i&&"nodeType"in i&&1===i.nodeType&&(p.element=i.cloneNode(!0)),p.unchangedObjectSnapshots=Object.fromEntries(this.unchangedObjectSnapshots),p}deserialize(t){return super.deserialize(t),this.isSelected=!0===t.isSelected,t.objectIds&&(this.objectIds=t.objectIds),t.unchangedObjectSnapshots&&(this.unchangedObjectSnapshots=new Map(Object.entries(t.unchangedObjectSnapshots))),this.shouldSyncChildSelectionState()&&this.syncChildSelectionState(this.objects),this}update(){this._core.store.objects.update(this)}move(t,e,i,n){const r=(t-i)/this._core.store.state.scale,s=(e-n)/this._core.store.state.scale;this.translateX+=r,this.translateY+=s;const o=Date.now();o-this._lastChildPersistTime>=So.CHILD_PERSIST_THROTTLE_MS?(this._core.store.objects.transaction((()=>{this._core.store.objects.update(this);const r=this.objects;for(const s of r)s.move(t,e,i,n),this._core.anchorManager.updateAnchorsForObject(s.id)})),this._lastChildPersistTime=o):(this._core.store.objects.update(this),this._core.store.objects.withLocalUpdatesOnly((()=>{const r=this.objects;for(const s of r)s.move(t,e,i,n),this._core.anchorManager.updateAnchorsForObject(s.id)}))),this.unchangedObjectSnapshots.forEach((t=>{t.translateX+=r,t.translateY+=s}))}persistChildren(){this._core.store.objects.transaction((()=>{const t=this.objects;for(const e of t)this._core.store.objects.update(e)}))}hasExternalAnchoredLineConnections(t){const e=t??this.objects;if(0===e.length)return!1;const i=new Set(e.map((t=>t.id)));for(const t of e){if(!uo.isInstanceOf(t,"KritzelLine"))continue;const e=t;if(e.startAnchor&&!i.has(e.startAnchor.objectId))return!0;if(e.endAnchor&&!i.has(e.endAnchor.objectId))return!0}return!1}resize(t,e,i,n){const r=i/this.snapshotWidth,s=n/this.snapshotHeight,o=this.snapshotTranslateX+(this.snapshotWidth+2*this.padding)/2/this.scale,h=this.snapshotTranslateY+(this.snapshotHeight+2*this.padding)/2/this.scale,a=t+(i+2*this.padding)/2/this.scale,l=e+(n+2*this.padding)/2/this.scale,u=this.rotation,c=Math.cos(-u),f=Math.sin(-u),d=Math.cos(u),p=Math.sin(u);this._core.store.objects.transaction((()=>{const t=this.objects;t.forEach((t=>{const e=this.unchangedObjectSnapshots.get(t.id);if(!e)return;const i=e.translateX+e.totalWidth/2/e.scale-o,n=e.translateY+e.totalHeight/2/e.scale-h,g=(i*c-n*f)*r,m=(i*f+n*c)*s,w=a+(g*d-m*p),v=l+(g*p+m*d),y=e.rotation-u,b=Math.cos(y),k=Math.sin(y),M=Math.sqrt(Math.pow(r*b,2)+Math.pow(s*k,2)),S=Math.sqrt(Math.pow(r*k,2)+Math.pow(s*b,2)),x=e.width*M,A=e.height*S;t.resize(w-(x+2*t.padding)/2/t.scale,v-(A+2*t.padding)/2/t.scale,x,A),this._core.anchorManager.updateAnchorsForObject(t.id)})),this.refreshObjectDimensions(t),this._core.store.objects.update(this)}))}rotate(t){this.rotation=t;const e=this.snapshotTranslateX+(this.snapshotWidth+2*this.padding)/2/this.scale,i=this.snapshotTranslateY+(this.snapshotHeight+2*this.padding)/2/this.scale,n=t-this.snapshotRotation,r=Math.cos(n),s=Math.sin(n),o=this.objects;this._core.store.objects.transaction((()=>{this._core.store.objects.update(this);const h=o.length;for(const a of o){const o=this.unchangedObjectSnapshots.get(a.id);if(!o)continue;const l=this.getOffsetXToCenterFromSnapshot(o),u=this.getOffsetYToCenterFromSnapshot(o),c=s*l+r*u;a.translateX=e+(r*l-s*u)-a.totalWidth/2/a.scale,a.translateY=i+c-a.totalHeight/2/a.scale,a.rotate(1===h?t:o.rotation+n)}const a=new Set;for(const t of o)if(a.add(t.id),uo.isInstanceOf(t,"KritzelLine")){const e=t;e.startAnchor&&a.add(e.startAnchor.objectId),e.endAnchor&&a.add(e.endAnchor.objectId)}let l=!1;for(const t of a)this._core.anchorManager.getLinesAnchoredTo(t).length>0&&(l=!0,this._core.anchorManager.updateAnchorsForObject(t));l&&this.refreshObjectDimensions(o)}))}copy(){const t=So.create(this._core),e=this.objects,i=[...e].sort(((t,e)=>t.zIndex-e.zIndex));for(const e of i){const i=e.copy();t.addOrRemove(i)}return t.captureUnchangedSnapshots(),1===e.length&&(t.rotation=e[0].rotation),t}refreshObjectDimensions(t,e=!1){const i=this.minX,n=this.minY,r=this.maxX,s=this.maxY,o=this.width,h=this.height,a=this.translateX,l=this.translateY,u=t??this.objects;if(1===u.length){const t=u[0];this.minX=t.boundingBox.x/this.scale,this.maxX=t.boundingBox.x/this.scale+t.boundingBox.width,this.minY=t.boundingBox.y/this.scale,this.maxY=t.boundingBox.y/this.scale+t.boundingBox.height,this.translateX=(this.minX-this.padding)*this.scale,this.translateY=(this.minY-this.padding)*this.scale,this.width=(this.maxX-this.minX-this.padding)*this.scale,this.height=(this.maxY-this.minY-this.padding)*this.scale}else{const t=this.rotation,e=Math.cos(-t),i=Math.sin(-t);let n=1/0,r=-1/0,s=1/0,o=-1/0;u.forEach((t=>{const h=t.rotatedPolygon;[h.topLeft,h.topRight,h.bottomRight,h.bottomLeft].forEach((t=>{const h=t.x*e-t.y*i,a=t.x*i+t.y*e;h<n&&(n=h),h>r&&(r=h),a<s&&(s=a),a>o&&(o=a)}))}));const h=o-s;this.width=(r-n-this.padding)*this.scale,this.height=(h-this.padding)*this.scale;const a=(n+r)/2,l=(s+o)/2,c=Math.cos(t),f=Math.sin(t),d=a*f+l*c;this.translateX=a*c-l*f-(this.width/this.scale+2*this.padding)/2,this.translateY=d-(this.height/this.scale+2*this.padding)/2}const c=Math.abs(this.minX-i)>So.DIMENSION_EPSILON||Math.abs(this.minY-n)>So.DIMENSION_EPSILON||Math.abs(this.maxX-r)>So.DIMENSION_EPSILON||Math.abs(this.maxY-s)>So.DIMENSION_EPSILON||Math.abs(this.width-o)>So.DIMENSION_EPSILON||Math.abs(this.height-h)>So.DIMENSION_EPSILON||Math.abs(this.translateX-a)>So.DIMENSION_EPSILON||Math.abs(this.translateY-l)>So.DIMENSION_EPSILON;return!e&&c&&this._core.store.objects.update(this),c}getOffsetXToCenterFromSnapshot(t){return t.translateX+t.totalWidth/t.scale/2-(this.snapshotTranslateX+(this.snapshotWidth+2*this.padding)/this.scale/2)}getOffsetYToCenterFromSnapshot(t){return t.translateY+t.totalHeight/t.scale/2-(this.snapshotTranslateY+(this.snapshotHeight+2*this.padding)/this.scale/2)}hitTest(t,e){const i=this.objects;if(1===i.length&&"KritzelLine"===i[0].__class__)return i[0].hitTest(t,e);const n=this.rotatedPolygon;if(u.isPointInPolygon({x:t,y:e},[n.topLeft,n.topRight,n.bottomRight,n.bottomLeft]))return!0;for(const n of i)if(n.hitTest(t,e))return!0;return!1}}class xo extends vo{toolType="line";color=m[0];size=4;opacity=1;palette=[...m];sizes=[...bo];arrows;_startX=0;_startY=0;_currentLineId=null;constructor(t){super(t)}handlePointerDown(t){if(t.cancelable&&t.preventDefault(),"mouse"===t.pointerType&&yo.isLeftClick(t)){this._core.store.state.isDrawing=!0;const e=this._core.store.state.scale,i=this._core.store.state.lockDrawingScale,n=i?e:1,r=(t.clientX-this._core.store.offsetX)/n,s=(t.clientY-this._core.store.offsetY)/n;this._startX=r,this._startY=s;const o=f.create(this._core,{startX:r,startY:s,endX:r,endY:s,translateX:-this._core.store.state.translateX/n,translateY:-this._core.store.state.translateY/n,scale:i?1:e,stroke:this.color,strokeWidth:this.size,opacity:this.opacity,arrows:this.arrows});o.isCompleted=!1,this._currentLineId=o.id,this._core.store.objects.insert(o),this._core.store.objects?.setActiveDrawingObject(o.id)}if("touch"===t.pointerType||"pen"===t.pointerType){const t=Array.from(this._core.store.state.pointers.values());if(1===t.length){const e=this._core.store.state.scale,i=this._core.store.state.lockDrawingScale,n=i?e:1,r=Math.round((t[0].clientX-this._core.store.offsetX)/n),s=Math.round((t[0].clientY-this._core.store.offsetY)/n);this._core.store.state.isDrawing=!0,this._startX=r,this._startY=s;const o=f.create(this._core,{startX:r,startY:s,endX:r,endY:s,translateX:-this._core.store.state.translateX/n,translateY:-this._core.store.state.translateY/n,scale:i?1:e,stroke:this.color,strokeWidth:this.size,opacity:this.opacity,arrows:this.arrows});o.isCompleted=!1,this._currentLineId=o.id,this._core.store.objects.insert(o),this._core.store.objects?.setActiveDrawingObject(o.id)}}}handlePointerMove(t){if(t.cancelable&&t.preventDefault(),"mouse"===t.pointerType&&this._core.store.state.isDrawing&&this._currentLineId){const e=this._core.store.objects.findById(this._currentLineId);if(e){const i=this._core.store.state.scale,n=this._core.store.state.lockDrawingScale,r=n?i:1,s=f.create(this._core,{startX:this._startX,startY:this._startY,endX:(t.clientX-this._core.store.offsetX)/r,endY:(t.clientY-this._core.store.offsetY)/r,translateX:-this._core.store.state.translateX/r,translateY:-this._core.store.state.translateY/r,scale:n?1:i,stroke:this.color,strokeWidth:this.size,opacity:this.opacity,arrows:this.arrows});s.id=e.id,s.workspaceId=e.workspaceId,s.zIndex=e.zIndex,s.isCompleted=!1,this._core.store.objects.update(s)}}if("touch"===t.pointerType||"pen"===t.pointerType){const t=Array.from(this._core.store.state.pointers.values());if(1===t.length&&this._currentLineId){const e=this._core.store.objects.findById(this._currentLineId);if(e){const i=this._core.store.state.scale,n=this._core.store.state.lockDrawingScale,r=n?i:1,s=Math.round((t[0].clientX-this._core.store.offsetX)/r),o=Math.round((t[0].clientY-this._core.store.offsetY)/r),h=f.create(this._core,{startX:this._startX,startY:this._startY,endX:s,endY:o,translateX:-this._core.store.state.translateX/r,translateY:-this._core.store.state.translateY/r,scale:n?1:i,stroke:this.color,strokeWidth:this.size,opacity:this.opacity,arrows:this.arrows});h.id=e.id,h.workspaceId=e.workspaceId,h.zIndex=e.zIndex,h.isCompleted=!1,this._core.store.objects.update(h)}}}}handlePointerUp(t){if(t.cancelable&&t.preventDefault(),"mouse"===t.pointerType&&this._core.store.state.isDrawing&&(this._core.store.state.isDrawing=!1,this._currentLineId)){const t=this._core.store.objects.findById(this._currentLineId);t&&(t.isCompleted=!0,this._core.store.objects.update(t),this._core.engine.emitObjectsChange(),this._core.engine.emitObjectsAdded([t]),this.selectLineAndSwitchTool(t)),this._core.store.objects?.setActiveDrawingObject(null),this._currentLineId=null,this._core.store.objects?.stopUndoCapturing()}if(("touch"===t.pointerType||"pen"===t.pointerType)&&this._core.store.state.isDrawing&&(this._core.store.state.isDrawing=!1,this._currentLineId)){const t=this._core.store.objects.findById(this._currentLineId);t&&(t.isCompleted=!0,this._core.store.objects.update(t),this._core.engine.emitObjectsChange(),this._core.engine.emitObjectsAdded([t]),this.selectLineAndSwitchTool(t)),this._core.store.objects?.setActiveDrawingObject(null),this._currentLineId=null,this._core.store.objects?.stopUndoCapturing()}}selectLineAndSwitchTool(t){const e=So.create(this._core);e.addOrRemove(t),e.isSelected=!0,e.rotation=t.rotation,this._core.addSelectionGroup(e),this._core.store.setState("activeTool",this._core.toolRegistry.getTool("selection")),this._core.rerender()}}class Ao extends vo{toolType="eraser";touchStartTimeout=null;constructor(t){super(t)}handlePointerDown(t){"mouse"===t.pointerType&&yo.isLeftClick(t)&&(this._core.store.state.isErasing=!0),"touch"!==t.pointerType&&"pen"!==t.pointerType||(this.touchStartTimeout=setTimeout((()=>{1!==this._core.store.state.pointers.size||this._core.store.state.isScaling||(this._core.store.state.isErasing=!0)}),80))}handlePointerMove(t){if("mouse"===t.pointerType&&this._core.store.state.isErasing){const e=this._core.getObjectsFromPointerEvent(t,".object");if(0===e.length)return;const i=this._core.store.state.pointerX,n=this._core.store.state.pointerY;e.forEach((t=>{t.markedForRemoval=t.hitTest(i,n)})),this._core.rerender()}if(("touch"===t.pointerType||"pen"===t.pointerType)&&1===this._core.store.state.pointers.size&&this._core.store.state.isErasing){const e=this._core.store.state.host?.shadowRoot;if(!e)return;const i=this._core.getObjectsFromPointerEvent(t,".object");if(0===i.length)return;const n=this._core.store.state.pointerX,r=this._core.store.state.pointerY;i.forEach((t=>{t.markedForRemoval=t.hitTest(n,r)})),this._core.rerender()}}handlePointerUp(t){if("mouse"===t.pointerType&&this._core.store.state.isErasing){const t=this._core.store.allObjects.filter((t=>t.markedForRemoval));t.length>0&&(this._core.store.objects.stopUndoCapturing(),this._core.store.objects.transaction((()=>{t.forEach((t=>{t.markedForRemoval=!1,this._core.removeObject(t)}))})),this._core.rerender()),this._core.store.state.isErasing=!1,this._core.engine.emitObjectsChange(),t.length>0&&(this._core.engine.emitObjectsRemoved(t),this._core.store.objects.stopUndoCapturing())}if(("touch"===t.pointerType||"pen"===t.pointerType)&&(clearTimeout(this.touchStartTimeout),this._core.store.state.isErasing)){const t=this._core.store.allObjects.filter((t=>t.markedForRemoval));t.length>0&&(this._core.store.objects.stopUndoCapturing(),this._core.store.objects.transaction((()=>{t.forEach((t=>{t.markedForRemoval=!1,this._core.removeObject(t)}))})),this._core.rerender()),this._core.store.state.isErasing=!1,this._core.engine.emitObjectsChange(),t.length>0&&(this._core.engine.emitObjectsRemoved(t),this._core.store.objects.stopUndoCapturing())}}}function $o(t,e){return new Promise((function(i,n){let r;return zo(t).then((function(t){try{return r=t,i(new Blob([e.slice(0,2),r,e.slice(2)],{type:"image/jpeg"}))}catch(t){return n(t)}}),n)}))}const zo=t=>new Promise(((e,i)=>{const n=new FileReader;n.addEventListener("load",(({target:{result:t}})=>{const n=new DataView(t);let r=0;if(65496!==n.getUint16(r))return i("not a valid JPEG");for(r+=2;;){const s=n.getUint16(r);if(65498===s)break;const o=n.getUint16(r+2);if(65505===s&&1165519206===n.getUint32(r+4)){const s=r+10;let h;switch(n.getUint16(s)){case 18761:h=!0;break;case 19789:h=!1;break;default:return i("TIFF header contains invalid endian")}if(42!==n.getUint16(s+2,h))return i("TIFF header contains invalid version");const a=n.getUint32(s+4,h),l=s+a+2+12*n.getUint16(s+a,h);for(let t=s+a+2;t<l;t+=12)if(274==n.getUint16(t,h)){if(3!==n.getUint16(t+2,h))return i("Orientation data type is invalid");if(1!==n.getUint32(t+4,h))return i("Orientation data count is invalid");n.setUint16(t+8,1,h);break}return e(t.slice(r,r+2+o))}r+=2+o}return e(new Blob)})),n.readAsArrayBuffer(t)}));var Co={},To={get exports(){return Co},set exports(t){Co=t}};!function(){var t,e,i={};To.exports=i,i.parse=function(t,e){for(var n=i.bin.readUshort,r=i.bin.readUint,s=0,o={},h=new Uint8Array(t),a=h.length-4;101010256!=r(h,a);)a--;s=a,s+=4;var l=n(h,s+=4);n(h,s+=2);var u=r(h,s+=2),c=r(h,s+=4);s+=4,s=c;for(var f=0;f<l;f++){r(h,s),s+=4,s+=4,s+=4,r(h,s+=4),u=r(h,s+=4);var d=r(h,s+=4),p=n(h,s+=4),g=n(h,s+2),m=n(h,s+4);s+=6;var w=r(h,s+=8);s+=4,s+=p+g+m,i._readLocal(h,w,o,u,d,e)}return o},i._readLocal=function(t,e,n,r,s,o){var h=i.bin.readUshort,a=i.bin.readUint;a(t,e),h(t,e+=4),h(t,e+=2);var l=h(t,e+=2);a(t,e+=2),a(t,e+=4),e+=4;var u=h(t,e+=8),c=h(t,e+=2),f=i.bin.readUTF8(t,e+=2,u);if(e+=u,e+=c,o)n[f]={size:s,csize:r};else{var d=new Uint8Array(t.buffer,e);if(0==l)n[f]=new Uint8Array(d.buffer.slice(e,e+r));else{if(8!=l)throw"unknown compression method: "+l;var p=new Uint8Array(s);i.inflateRaw(d,p),n[f]=p}}},i.inflateRaw=function(t,e){return i.F.inflate(t,e)},i.inflate=function(t,e){return i.inflateRaw(new Uint8Array(t.buffer,t.byteOffset+2,t.length-6),e)},i.deflate=function(t,e){null==e&&(e={level:6});var n=0,r=new Uint8Array(50+Math.floor(1.1*t.length));r[n]=120,r[n+1]=156,n=i.F.deflateRaw(t,r,n+=2,e.level);var s=i.adler(t,0,t.length);return r[n+0]=s>>>24&255,r[n+1]=s>>>16&255,r[n+2]=s>>>8&255,r[n+3]=s>>>0&255,new Uint8Array(r.buffer,0,n+4)},i.deflateRaw=function(t,e){null==e&&(e={level:6});var n=new Uint8Array(50+Math.floor(1.1*t.length)),r=i.F.deflateRaw(t,n,r,e.level);return new Uint8Array(n.buffer,0,r)},i.encode=function(t,e){null==e&&(e=!1);var n=0,r=i.bin.writeUint,s=i.bin.writeUshort,o={};for(var h in t){var a=!i._noNeed(h)&&!e,l=t[h],u=i.crc.crc(l,0,l.length);o[h]={cpr:a,usize:l.length,crc:u,file:a?i.deflateRaw(l):l}}for(var h in o)n+=o[h].file.length+30+46+2*i.bin.sizeUTF8(h);n+=22;var c=new Uint8Array(n),f=0,d=[];for(var h in o){var p=o[h];d.push(f),f=i._writeHeader(c,f,h,p,0)}var g=0,m=f;for(var h in o)p=o[h],d.push(f),f=i._writeHeader(c,f,h,p,1,d[g++]);var w=f-m;return r(c,f,101010256),f+=4,s(c,f+=4,g),s(c,f+=2,g),r(c,f+=2,w),r(c,f+=4,m),f+=4,f+=2,c.buffer},i._noNeed=function(t){var e=t.split(".").pop().toLowerCase();return-1!="png,jpg,jpeg,zip".indexOf(e)},i._writeHeader=function(t,e,n,r,s,o){var h=i.bin.writeUint,a=i.bin.writeUshort,l=r.file;return h(t,e,0==s?67324752:33639248),e+=4,1==s&&(e+=2),a(t,e,20),a(t,e+=2,0),a(t,e+=2,r.cpr?8:0),h(t,e+=2,0),h(t,e+=4,r.crc),h(t,e+=4,l.length),h(t,e+=4,r.usize),a(t,e+=4,i.bin.sizeUTF8(n)),a(t,e+=2,0),e+=2,1==s&&(e+=2,e+=2,h(t,e+=6,o),e+=4),e+=i.bin.writeUTF8(t,e,n),0==s&&(t.set(l,e),e+=l.length),e},i.crc={table:function(){for(var t=new Uint32Array(256),e=0;e<256;e++){for(var i=e,n=0;n<8;n++)1&i?i=3988292384^i>>>1:i>>>=1;t[e]=i}return t}(),update:function(t,e,n,r){for(var s=0;s<r;s++)t=i.crc.table[255&(t^e[n+s])]^t>>>8;return t},crc:function(t,e,n){return 4294967295^i.crc.update(4294967295,t,e,n)}},i.adler=function(t,e,i){for(var n=1,r=0,s=e,o=e+i;s<o;){for(var h=Math.min(s+5552,o);s<h;)r+=n+=t[s++];n%=65521,r%=65521}return r<<16|n},i.bin={readUshort:function(t,e){return t[e]|t[e+1]<<8},writeUshort:function(t,e,i){t[e]=255&i,t[e+1]=i>>8&255},readUint:function(t,e){return 16777216*t[e+3]+(t[e+2]<<16|t[e+1]<<8|t[e])},writeUint:function(t,e,i){t[e]=255&i,t[e+1]=i>>8&255,t[e+2]=i>>16&255,t[e+3]=i>>24&255},readASCII:function(t,e,i){for(var n="",r=0;r<i;r++)n+=String.fromCharCode(t[e+r]);return n},writeASCII:function(t,e,i){for(var n=0;n<i.length;n++)t[e+n]=i.charCodeAt(n)},pad:function(t){return t.length<2?"0"+t:t},readUTF8:function(t,e,n){for(var r,s="",o=0;o<n;o++)s+="%"+i.bin.pad(t[e+o].toString(16));try{r=decodeURIComponent(s)}catch(r){return i.bin.readASCII(t,e,n)}return r},writeUTF8:function(t,e,i){for(var n=i.length,r=0,s=0;s<n;s++){var o=i.charCodeAt(s);if(4294967168&o)if(4294965248&o)if(4294901760&o){if(4292870144&o)throw"e";t[e+r]=240|o>>18,t[e+r+1]=128|o>>12&63,t[e+r+2]=128|o>>6&63,t[e+r+3]=128|63&o,r+=4}else t[e+r]=224|o>>12,t[e+r+1]=128|o>>6&63,t[e+r+2]=128|63&o,r+=3;else t[e+r]=192|o>>6,t[e+r+1]=128|63&o,r+=2;else t[e+r]=o,r++}return r},sizeUTF8:function(t){for(var e=t.length,i=0,n=0;n<e;n++){var r=t.charCodeAt(n);if(4294967168&r)if(4294965248&r)if(4294901760&r){if(4292870144&r)throw"e";i+=4}else i+=3;else i+=2;else i++}return i}},i.F={},i.F.deflateRaw=function(t,e,n,r){var s=[[0,0,0,0,0],[4,4,8,4,0],[4,5,16,8,0],[4,6,16,16,0],[4,10,16,32,0],[8,16,32,32,0],[8,16,128,128,0],[8,32,128,256,0],[32,128,258,1024,1],[32,258,258,4096,1]][r],o=i.F.U,h=i.F._goodIndex,a=i.F._putsE,l=0,u=n<<3,c=0,f=t.length;if(0==r){for(;l<f;)a(e,u,l+(x=Math.min(65535,f-l))==f?1:0),u=i.F._copyExact(t,l,x,e,u+8),l+=x;return u>>>3}var d=o.lits,p=o.strt,g=o.prev,m=0,w=0,v=0,y=0,b=0,k=0;for(f>2&&(p[k=i.F._hash(t,0)]=0),l=0;l<f;l++){if(b=k,l+1<f-2){k=i.F._hash(t,l+1);var M=l+1&32767;g[M]=p[k],p[k]=M}if(c<=l){(m>14e3||w>26697)&&f-l>100&&(c<l&&(d[m]=l-c,m+=2,c=l),u=i.F._writeBlock(l==f-1||c==f?1:0,d,m,y,t,v,l-v,e,u),m=w=y=0,v=l);var S=0;l<f-2&&(S=i.F._bestMatch(t,l,g,b,Math.min(s[2],f-l),s[3]));var x=S>>>16,A=65535&S;if(0!=S){A=65535&S;var $=h(x=S>>>16,o.of0);o.lhst[257+$]++;var z=h(A,o.df0);o.dhst[z]++,y+=o.exb[$]+o.dxb[z],d[m]=x<<23|l-c,d[m+1]=A<<16|$<<8|z,m+=2,c=l+x}else o.lhst[t[l]]++;w++}}for(v==l&&0!=t.length||(c<l&&(d[m]=l-c,m+=2,c=l),u=i.F._writeBlock(1,d,m,y,t,v,l-v,e,u),m=0,w=0,m=w=y=0,v=l);7&u;)u++;return u>>>3},i.F._bestMatch=function(t,e,n,r,s,o){var h=32767&e,a=n[h],l=h-a+32768&32767;if(a==h||r!=i.F._hash(t,e-l))return 0;for(var u=0,c=0,f=Math.min(32767,e);l<=f&&0!=--o&&a!=h;){if(0==u||t[e+u]==t[e+u-l]){var d=i.F._howLong(t,e,l);if(d>u){if(c=l,(u=d)>=s)break;l+2<d&&(d=l+2);for(var p=0,g=0;g<d-2;g++){var m=e-l+g+32768&32767,w=m-n[m]+32768&32767;w>p&&(p=w,a=m)}}}l+=(h=a)-(a=n[h])+32768&32767}return u<<16|c},i.F._howLong=function(t,e,i){if(t[e]!=t[e-i]||t[e+1]!=t[e+1-i]||t[e+2]!=t[e+2-i])return 0;var n=e,r=Math.min(t.length,e+258);for(e+=3;e<r&&t[e]==t[e-i];)e++;return e-n},i.F._hash=function(t,e){return(t[e]<<8|t[e+1])+(t[e+2]<<4)&65535},i.saved=0,i.F._writeBlock=function(t,e,n,r,s,o,h,a,l){var u,c,f,d,p,g,m,w,v,y=i.F.U,b=i.F._putsF,k=i.F._putsE;y.lhst[256]++,c=(u=i.F.getTrees())[0],f=u[1],d=u[2],p=u[3],g=u[4],m=u[5],w=u[6],v=u[7];var M=32+(l+3&7?8-(l+3&7):0)+(h<<3),S=r+i.F.contSize(y.fltree,y.lhst)+i.F.contSize(y.fdtree,y.dhst),x=r+i.F.contSize(y.ltree,y.lhst)+i.F.contSize(y.dtree,y.dhst);x+=14+3*m+i.F.contSize(y.itree,y.ihst)+(2*y.ihst[16]+3*y.ihst[17]+7*y.ihst[18]);for(var A=0;A<286;A++)y.lhst[A]=0;for(A=0;A<30;A++)y.dhst[A]=0;for(A=0;A<19;A++)y.ihst[A]=0;var $=M<S&&M<x?0:S<x?1:2;if(b(a,l,t),b(a,l+1,$),l+=3,0==$){for(;7&l;)l++;l=i.F._copyExact(s,o,h,a,l)}else{var z,C;if(1==$&&(z=y.fltree,C=y.fdtree),2==$){i.F.makeCodes(y.ltree,c),i.F.revCodes(y.ltree,c),i.F.makeCodes(y.dtree,f),i.F.revCodes(y.dtree,f),i.F.makeCodes(y.itree,d),i.F.revCodes(y.itree,d),z=y.ltree,C=y.dtree,k(a,l,p-257),k(a,l+=5,g-1),k(a,l+=5,m-4),l+=4;for(var T=0;T<m;T++)k(a,l+3*T,y.itree[1+(y.ordr[T]<<1)]);l=i.F._codeTiny(w,y.itree,a,l+=3*m),l=i.F._codeTiny(v,y.itree,a,l)}for(var E=o,O=0;O<n;O+=2){for(var I=e[O],j=I>>>23,P=E+(8388607&I);E<P;)l=i.F._writeLit(s[E++],z,a,l);if(0!=j){var R=e[O+1],D=R>>16,_=R>>8&255,L=255&R;k(a,l=i.F._writeLit(257+_,z,a,l),j-y.of0[_]),b(a,l=i.F._writeLit(L,C,a,l+=y.exb[_]),D-y.df0[L]),l+=y.dxb[L],E+=j}}l=i.F._writeLit(256,z,a,l)}return l},i.F._copyExact=function(t,e,i,n,r){var s=r>>>3;return n[s]=i,n[s+1]=i>>>8,n[s+2]=255-n[s],n[s+3]=255-n[s+1],s+=4,n.set(new Uint8Array(t.buffer,e,i),s),r+(i+4<<3)},i.F.getTrees=function(){for(var t=i.F.U,e=i.F._hufTree(t.lhst,t.ltree,15),n=i.F._hufTree(t.dhst,t.dtree,15),r=[],s=i.F._lenCodes(t.ltree,r),o=[],h=i.F._lenCodes(t.dtree,o),a=0;a<r.length;a+=2)t.ihst[r[a]]++;for(a=0;a<o.length;a+=2)t.ihst[o[a]]++;for(var l=i.F._hufTree(t.ihst,t.itree,7),u=19;u>4&&0==t.itree[1+(t.ordr[u-1]<<1)];)u--;return[e,n,l,s,h,u,r,o]},i.F.getSecond=function(t){for(var e=[],i=0;i<t.length;i+=2)e.push(t[i+1]);return e},i.F.nonZero=function(t){for(var e="",i=0;i<t.length;i+=2)0!=t[i+1]&&(e+=(i>>1)+",");return e},i.F.contSize=function(t,e){for(var i=0,n=0;n<e.length;n++)i+=e[n]*t[1+(n<<1)];return i},i.F._codeTiny=function(t,e,n,r){for(var s=0;s<t.length;s+=2){var o=t[s],h=t[s+1];r=i.F._writeLit(o,e,n,r);var a=16==o?2:17==o?3:7;o>15&&(i.F._putsE(n,r,h,a),r+=a)}return r},i.F._lenCodes=function(t,e){for(var i=t.length;2!=i&&0==t[i-1];)i-=2;for(var n=0;n<i;n+=2){var r=t[n+1],s=n+3<i?t[n+3]:-1,o=n+5<i?t[n+5]:-1,h=0==n?-1:t[n-1];if(0==r&&s==r&&o==r){for(var a=n+5;a+2<i&&t[a+2]==r;)a+=2;(l=Math.min(a+1-n>>>1,138))<11?e.push(17,l-3):e.push(18,l-11),n+=2*l-2}else if(r==h&&s==r&&o==r){for(a=n+5;a+2<i&&t[a+2]==r;)a+=2;var l=Math.min(a+1-n>>>1,6);e.push(16,l-3),n+=2*l-2}else e.push(r,0)}return i>>>1},i.F._hufTree=function(t,e,n){var r=[],s=t.length,o=e.length,h=0;for(h=0;h<o;h+=2)e[h]=0,e[h+1]=0;for(h=0;h<s;h++)0!=t[h]&&r.push({lit:h,f:t[h]});var a=r.length,l=r.slice(0);if(0==a)return 0;if(1==a){var u=r[0].lit;return l=0==u?1:0,e[1+(u<<1)]=1,e[1+(l<<1)]=1,1}r.sort((function(t,e){return t.f-e.f}));var c=r[0],f=r[1],d=0,p=1,g=2;for(r[0]={lit:-1,f:c.f+f.f,l:c,r:f,d:0};p!=a-1;)c=d!=p&&(g==a||r[d].f<r[g].f)?r[d++]:r[g++],f=d!=p&&(g==a||r[d].f<r[g].f)?r[d++]:r[g++],r[p++]={lit:-1,f:c.f+f.f,l:c,r:f};var m=i.F.setDepth(r[p-1],0);for(m>n&&(i.F.restrictDepth(l,n,m),m=n),h=0;h<a;h++)e[1+(l[h].lit<<1)]=l[h].d;return m},i.F.setDepth=function(t,e){return-1!=t.lit?(t.d=e,e):Math.max(i.F.setDepth(t.l,e+1),i.F.setDepth(t.r,e+1))},i.F.restrictDepth=function(t,e,i){var n=0,r=1<<i-e,s=0;for(t.sort((function(t,e){return e.d==t.d?t.f-e.f:e.d-t.d})),n=0;n<t.length&&t[n].d>e;n++){var o=t[n].d;t[n].d=e,s+=r-(1<<i-o)}for(s>>>=i-e;s>0;)(o=t[n].d)<e?(t[n].d++,s-=1<<e-o-1):n++;for(;n>=0;n--)t[n].d==e&&s<0&&(t[n].d--,s++);0!=s&&console.log("debt left")},i.F._goodIndex=function(t,e){var i=0;return e[16|i]<=t&&(i|=16),e[8|i]<=t&&(i|=8),e[4|i]<=t&&(i|=4),e[2|i]<=t&&(i|=2),e[1|i]<=t&&(i|=1),i},i.F._writeLit=function(t,e,n,r){return i.F._putsF(n,r,e[t<<1]),r+e[1+(t<<1)]},i.F.inflate=function(t,e){var n=Uint8Array;if(3==t[0]&&0==t[1])return e||new n(0);var r=i.F,s=r._bitsF,o=r._bitsE,h=r._decodeTiny,a=r.makeCodes,l=r.codes2map,u=r._get17,c=r.U,f=null==e;f&&(e=new n(t.length>>>2<<3));for(var d,p,g=0,m=0,w=0,v=0,y=0,b=0,k=0,M=0,S=0;0==g;)if(g=s(t,S,1),m=s(t,S+1,2),S+=3,0!=m){if(f&&(e=i.F._check(e,M+(1<<17))),1==m&&(d=c.flmap,p=c.fdmap,b=511,k=31),2==m){w=o(t,S,5)+257,v=o(t,S+5,5)+1,y=o(t,S+10,4)+4,S+=14;for(var x=0;x<38;x+=2)c.itree[x]=0,c.itree[x+1]=0;var A=1;for(x=0;x<y;x++){var $=o(t,S+3*x,3);c.itree[1+(c.ordr[x]<<1)]=$,$>A&&(A=$)}S+=3*y,a(c.itree,A),l(c.itree,A,c.imap),d=c.lmap,p=c.dmap,S=h(c.imap,(1<<A)-1,w+v,t,S,c.ttree);var z=r._copyOut(c.ttree,0,w,c.ltree);b=(1<<z)-1;var C=r._copyOut(c.ttree,w,v,c.dtree);k=(1<<C)-1,a(c.ltree,z),l(c.ltree,z,d),a(c.dtree,C),l(c.dtree,C,p)}for(;;){var T=d[u(t,S)&b];S+=15&T;var E=T>>>4;if(E>>>8==0)e[M++]=E;else{if(256==E)break;var O=M+E-254;if(E>264){var I=c.ldef[E-257];O=M+(I>>>3)+o(t,S,7&I),S+=7&I}var j=p[u(t,S)&k],P=c.ddef[j>>>4],R=(P>>>4)+s(t,S+=15&j,15&P);for(S+=15&P,f&&(e=i.F._check(e,M+(1<<17)));M<O;)e[M]=e[M++-R],e[M]=e[M++-R],e[M]=e[M++-R],e[M]=e[M++-R];M=O}}}else{7&S&&(S+=8-(7&S));var D=4+(S>>>3),_=t[D-4]|t[D-3]<<8;f&&(e=i.F._check(e,M+_)),e.set(new n(t.buffer,t.byteOffset+D,_),M),S=D+_<<3,M+=_}return e.length==M?e:e.slice(0,M)},i.F._check=function(t,e){var i=t.length;if(e<=i)return t;var n=new Uint8Array(Math.max(i<<1,e));return n.set(t,0),n},i.F._decodeTiny=function(t,e,n,r,s,o){for(var h=i.F._bitsE,a=i.F._get17,l=0;l<n;){var u=t[a(r,s)&e];s+=15&u;var c=u>>>4;if(c<=15)o[l]=c,l++;else{var f=0,d=0;16==c?(d=3+h(r,s,2),s+=2,f=o[l-1]):17==c?(d=3+h(r,s,3),s+=3):18==c&&(d=11+h(r,s,7),s+=7);for(var p=l+d;l<p;)o[l]=f,l++}}return s},i.F._copyOut=function(t,e,i,n){for(var r=0,s=0,o=n.length>>>1;s<i;){var h=t[s+e];n[s<<1]=0,n[1+(s<<1)]=h,h>r&&(r=h),s++}for(;s<o;)n[s<<1]=0,n[1+(s<<1)]=0,s++;return r},i.F.makeCodes=function(t,e){for(var n,r,s,o,h=i.F.U,a=t.length,l=h.bl_count,u=0;u<=e;u++)l[u]=0;for(u=1;u<a;u+=2)l[t[u]]++;var c=h.next_code;for(n=0,l[0]=0,r=1;r<=e;r++)c[r]=n=n+l[r-1]<<1;for(s=0;s<a;s+=2)0!=(o=t[s+1])&&(t[s]=c[o],c[o]++)},i.F.codes2map=function(t,e,n){for(var r=t.length,s=i.F.U.rev15,o=0;o<r;o+=2)if(0!=t[o+1])for(var h=t[o+1],a=o>>1<<4|h,l=e-h,u=t[o]<<l,c=u+(1<<l);u!=c;)n[s[u]>>>15-e]=a,u++},i.F.revCodes=function(t,e){for(var n=i.F.U.rev15,r=15-e,s=0;s<t.length;s+=2)t[s]=n[t[s]<<e-t[s+1]]>>>r},i.F._putsE=function(t,e,i){var n=e>>>3;t[n]|=i<<=7&e,t[n+1]|=i>>>8},i.F._putsF=function(t,e,i){var n=e>>>3;t[n]|=i<<=7&e,t[n+1]|=i>>>8,t[n+2]|=i>>>16},i.F._bitsE=function(t,e,i){return(t[e>>>3]|t[1+(e>>>3)]<<8)>>>(7&e)&(1<<i)-1},i.F._bitsF=function(t,e,i){return(t[e>>>3]|t[1+(e>>>3)]<<8|t[2+(e>>>3)]<<16)>>>(7&e)&(1<<i)-1},i.F._get17=function(t,e){return(t[e>>>3]|t[1+(e>>>3)]<<8|t[2+(e>>>3)]<<16)>>>(7&e)},i.F._get25=function(t,e){return(t[e>>>3]|t[1+(e>>>3)]<<8|t[2+(e>>>3)]<<16|t[3+(e>>>3)]<<24)>>>(7&e)},i.F.U=(t=Uint16Array,e=Uint32Array,{next_code:new t(16),bl_count:new t(16),ordr:[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],of0:[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,999,999,999],exb:[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0],ldef:new t(32),df0:[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,65535,65535],dxb:[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0],ddef:new e(32),flmap:new t(512),fltree:[],fdmap:new t(32),fdtree:[],lmap:new t(32768),ltree:[],ttree:[],dmap:new t(32768),dtree:[],imap:new t(512),itree:[],rev15:new t(32768),lhst:new e(286),dhst:new e(30),ihst:new e(19),lits:new e(15e3),strt:new t(65536),prev:new t(32768)}),function(){for(var t=i.F.U,e=0;e<32768;e++){var n=e;n=(4278255360&(n=(4042322160&(n=(3435973836&(n=(2863311530&n)>>>1|(1431655765&n)<<1))>>>2|(858993459&n)<<2))>>>4|(252645135&n)<<4))>>>8|(16711935&n)<<8,t.rev15[e]=(n>>>16|n<<16)>>>17}function r(t,e,i){for(;0!=e--;)t.push(0,i)}for(e=0;e<32;e++)t.ldef[e]=t.of0[e]<<3|t.exb[e],t.ddef[e]=t.df0[e]<<4|t.dxb[e];r(t.fltree,144,8),r(t.fltree,112,9),r(t.fltree,24,7),r(t.fltree,8,8),i.F.makeCodes(t.fltree,9),i.F.codes2map(t.fltree,9,t.flmap),i.F.revCodes(t.fltree,9),r(t.fdtree,32,5),i.F.makeCodes(t.fdtree,5),i.F.codes2map(t.fdtree,5,t.fdmap),i.F.revCodes(t.fdtree,5),r(t.itree,19,0),r(t.ltree,286,0),r(t.dtree,30,0),r(t.ttree,320,0)}()}();var Eo=function(t,e){return e.forEach((function(e){e&&"string"!=typeof e&&!Array.isArray(e)&&Object.keys(e).forEach((function(i){if("default"!==i&&!(i in t)){var n=Object.getOwnPropertyDescriptor(e,i);Object.defineProperty(t,i,n.get?n:{enumerable:!0,get:function(){return e[i]}})}}))})),Object.freeze(t)}({__proto__:null,default:Co},[Co]);const Oo=function(){var t={nextZero(t,e){for(;0!=t[e];)e++;return e},readUshort:(t,e)=>t[e]<<8|t[e+1],writeUshort(t,e,i){t[e]=i>>8&255,t[e+1]=255&i},readUint:(t,e)=>16777216*t[e]+(t[e+1]<<16|t[e+2]<<8|t[e+3]),writeUint(t,e,i){t[e]=i>>24&255,t[e+1]=i>>16&255,t[e+2]=i>>8&255,t[e+3]=255&i},readASCII(t,e,i){let n="";for(let r=0;r<i;r++)n+=String.fromCharCode(t[e+r]);return n},writeASCII(t,e,i){for(let n=0;n<i.length;n++)t[e+n]=i.charCodeAt(n)},readBytes(t,e,i){const n=[];for(let r=0;r<i;r++)n.push(t[e+r]);return n},pad:t=>t.length<2?`0${t}`:t,readUTF8(e,i,n){let r,s="";for(let r=0;r<n;r++)s+=`%${t.pad(e[i+r].toString(16))}`;try{r=decodeURIComponent(s)}catch(r){return t.readASCII(e,i,n)}return r}};function e(e,i,n,r){const o=i*n,h=s(r),a=Math.ceil(i*h/8),l=new Uint8Array(4*o),u=new Uint32Array(l.buffer),{ctype:c}=r,{depth:f}=r,d=t.readUshort;if(6==c){const t=o<<2;if(8==f)for(var p=0;p<t;p+=4)l[p]=e[p],l[p+1]=e[p+1],l[p+2]=e[p+2],l[p+3]=e[p+3];if(16==f)for(p=0;p<t;p++)l[p]=e[p<<1]}else if(2==c){const t=r.tabs.tRNS;if(null==t){if(8==f)for(p=0;p<o;p++){var g=3*p;u[p]=255<<24|e[g+2]<<16|e[g+1]<<8|e[g]}if(16==f)for(p=0;p<o;p++)u[p]=255<<24|e[4+(g=6*p)]<<16|e[g+2]<<8|e[g]}else{var m=t[0];const i=t[1],n=t[2];if(8==f)for(p=0;p<o;p++){var w=p<<2;u[p]=255<<24|e[2+(g=3*p)]<<16|e[g+1]<<8|e[g],e[g]==m&&e[g+1]==i&&e[g+2]==n&&(l[w+3]=0)}if(16==f)for(p=0;p<o;p++)w=p<<2,u[p]=255<<24|e[4+(g=6*p)]<<16|e[g+2]<<8|e[g],d(e,g)==m&&d(e,g+2)==i&&d(e,g+4)==n&&(l[w+3]=0)}}else if(3==c){const t=r.tabs.PLTE,s=r.tabs.tRNS,h=s?s.length:0;if(1==f)for(var v=0;v<n;v++){var y=v*a,b=v*i;for(p=0;p<i;p++){var k=3*(M=e[y+(p>>3)]>>7-(7&p)&1);l[w=b+p<<2]=t[k],l[w+1]=t[k+1],l[w+2]=t[k+2],l[w+3]=M<h?s[M]:255}}if(2==f)for(v=0;v<n;v++)for(y=v*a,b=v*i,p=0;p<i;p++)k=3*(M=e[y+(p>>2)]>>6-((3&p)<<1)&3),l[w=b+p<<2]=t[k],l[w+1]=t[k+1],l[w+2]=t[k+2],l[w+3]=M<h?s[M]:255;if(4==f)for(v=0;v<n;v++)for(y=v*a,b=v*i,p=0;p<i;p++)k=3*(M=e[y+(p>>1)]>>4-((1&p)<<2)&15),l[w=b+p<<2]=t[k],l[w+1]=t[k+1],l[w+2]=t[k+2],l[w+3]=M<h?s[M]:255;if(8==f)for(p=0;p<o;p++){var M;k=3*(M=e[p]),l[w=p<<2]=t[k],l[w+1]=t[k+1],l[w+2]=t[k+2],l[w+3]=M<h?s[M]:255}}else if(4==c){if(8==f)for(p=0;p<o;p++){var S=e[x=p<<1];l[w=p<<2]=S,l[w+1]=S,l[w+2]=S,l[w+3]=e[x+1]}if(16==f)for(p=0;p<o;p++){var x;S=e[x=p<<2],l[w=p<<2]=S,l[w+1]=S,l[w+2]=S,l[w+3]=e[x+2]}}else if(0==c)for(m=r.tabs.tRNS?r.tabs.tRNS:-1,v=0;v<n;v++){const t=v*a,n=v*i;if(1==f)for(var A=0;A<i;A++){var $=(S=255*(e[t+(A>>>3)]>>>7-(7&A)&1))==255*m?0:255;u[n+A]=$<<24|S<<16|S<<8|S}else if(2==f)for(A=0;A<i;A++)$=(S=85*(e[t+(A>>>2)]>>>6-((3&A)<<1)&3))==85*m?0:255,u[n+A]=$<<24|S<<16|S<<8|S;else if(4==f)for(A=0;A<i;A++)$=(S=17*(e[t+(A>>>1)]>>>4-((1&A)<<2)&15))==17*m?0:255,u[n+A]=$<<24|S<<16|S<<8|S;else if(8==f)for(A=0;A<i;A++)$=(S=e[t+A])==m?0:255,u[n+A]=$<<24|S<<16|S<<8|S;else if(16==f)for(A=0;A<i;A++)S=e[t+(A<<1)],$=d(e,t+(A<<1))==m?0:255,u[n+A]=$<<24|S<<16|S<<8|S}return l}function i(t,e,i,h){const a=s(t),l=Math.ceil(i*a/8),u=new Uint8Array((l+1+t.interlace)*h);return e=t.tabs.CgBI?r(e,u):n(e,u),0==t.interlace?e=o(e,t,0,i,h):1==t.interlace&&(e=function(t,e){const i=e.width,n=e.height,r=s(e),h=r>>3,a=Math.ceil(i*r/8),l=new Uint8Array(n*a);let u=0;const c=[0,0,4,0,2,0,1],f=[0,4,0,2,0,1,0],d=[8,8,8,4,4,2,2],p=[8,8,4,4,2,2,1];let g=0;for(;g<7;){const s=d[g],w=p[g];let v=0,y=0,b=c[g];for(;b<n;)b+=s,y++;let k=f[g];for(;k<i;)k+=w,v++;const M=Math.ceil(v*r/8);o(t,e,u,v,y);let S=0,x=c[g];for(;x<n;){let e=f[g],n=u+S*M<<3;for(;e<i;){var m;if(1==r&&(m=(m=t[n>>3])>>7-(7&n)&1,l[x*a+(e>>3)]|=m<<7-(7&e)),2==r&&(m=(m=t[n>>3])>>6-(7&n)&3,l[x*a+(e>>2)]|=m<<6-((3&e)<<1)),4==r&&(m=(m=t[n>>3])>>4-(7&n)&15,l[x*a+(e>>1)]|=m<<4-((1&e)<<2)),r>=8){const i=x*a+e*h;for(let e=0;e<h;e++)l[i+e]=t[(n>>3)+e]}n+=r,e+=w}S++,x+=s}v*y!=0&&(u+=y*(1+M)),g+=1}return l}(e,t)),e}function n(t,e){return r(new Uint8Array(t.buffer,2,t.length-6),e)}var r=function(){const t={H:{}};return t.H.N=function(e,i){const n=Uint8Array;let r,s,o=0,h=0,a=0,l=0,u=0,c=0,f=0,d=0,p=0;if(3==e[0]&&0==e[1])return i||new n(0);const g=t.H,m=g.b,w=g.e,v=g.R,y=g.n,b=g.A,k=g.Z,M=g.m,S=null==i;for(S&&(i=new n(e.length>>>2<<5));0==o;)if(o=m(e,p,1),h=m(e,p+1,2),p+=3,0!=h){if(S&&(i=t.H.W(i,d+(1<<17))),1==h&&(r=M.J,s=M.h,c=511,f=31),2==h){a=w(e,p,5)+257,l=w(e,p+5,5)+1,u=w(e,p+10,4)+4,p+=14;let t=1;for(var x=0;x<38;x+=2)M.Q[x]=0,M.Q[x+1]=0;for(x=0;x<u;x++){const i=w(e,p+3*x,3);M.Q[1+(M.X[x]<<1)]=i,i>t&&(t=i)}p+=3*u,y(M.Q,t),b(M.Q,t,M.u),r=M.w,s=M.d,p=v(M.u,(1<<t)-1,a+l,e,p,M.v);const i=g.V(M.v,0,a,M.C);c=(1<<i)-1;const n=g.V(M.v,a,l,M.D);f=(1<<n)-1,y(M.C,i),b(M.C,i,r),y(M.D,n),b(M.D,n,s)}for(;;){const t=r[k(e,p)&c];p+=15&t;const n=t>>>4;if(n>>>8==0)i[d++]=n;else{if(256==n)break;{let t=d+n-254;if(n>264){const i=M.q[n-257];t=d+(i>>>3)+w(e,p,7&i),p+=7&i}const r=s[k(e,p)&f];p+=15&r;const o=M.c[r>>>4],h=(o>>>4)+m(e,p,15&o);for(p+=15&o;d<t;)i[d]=i[d++-h],i[d]=i[d++-h],i[d]=i[d++-h],i[d]=i[d++-h];d=t}}}}else{7&p&&(p+=8-(7&p));const r=4+(p>>>3),s=e[r-4]|e[r-3]<<8;S&&(i=t.H.W(i,d+s)),i.set(new n(e.buffer,e.byteOffset+r,s),d),p=r+s<<3,d+=s}return i.length==d?i:i.slice(0,d)},t.H.W=function(t,e){const i=t.length;if(e<=i)return t;const n=new Uint8Array(i<<1);return n.set(t,0),n},t.H.R=function(e,i,n,r,s,o){const h=t.H.e,a=t.H.Z;let l=0;for(;l<n;){const t=e[a(r,s)&i];s+=15&t;const n=t>>>4;if(n<=15)o[l]=n,l++;else{let t=0,e=0;16==n?(e=3+h(r,s,2),s+=2,t=o[l-1]):17==n?(e=3+h(r,s,3),s+=3):18==n&&(e=11+h(r,s,7),s+=7);const i=l+e;for(;l<i;)o[l]=t,l++}}return s},t.H.V=function(t,e,i,n){let r=0,s=0;const o=n.length>>>1;for(;s<i;){const i=t[s+e];n[s<<1]=0,n[1+(s<<1)]=i,i>r&&(r=i),s++}for(;s<o;)n[s<<1]=0,n[1+(s<<1)]=0,s++;return r},t.H.n=function(e,i){const n=t.H.m,r=e.length;let s,o,h,a;const l=n.j;for(var u=0;u<=i;u++)l[u]=0;for(u=1;u<r;u+=2)l[e[u]]++;const c=n.K;for(s=0,l[0]=0,o=1;o<=i;o++)s=s+l[o-1]<<1,c[o]=s;for(h=0;h<r;h+=2)a=e[h+1],0!=a&&(e[h]=c[a],c[a]++)},t.H.A=function(e,i,n){const r=e.length,s=t.H.m.r;for(let t=0;t<r;t+=2)if(0!=e[t+1]){const r=e[t+1],o=t>>1<<4|r,h=i-r;let a=e[t]<<h;const l=a+(1<<h);for(;a!=l;)n[s[a]>>>15-i]=o,a++}},t.H.l=function(e,i){const n=t.H.m.r,r=15-i;for(let t=0;t<e.length;t+=2)e[t]=n[e[t]<<i-e[t+1]]>>>r},t.H.M=function(t,e,i){const n=e>>>3;t[n]|=i<<=7&e,t[n+1]|=i>>>8},t.H.I=function(t,e,i){const n=e>>>3;t[n]|=i<<=7&e,t[n+1]|=i>>>8,t[n+2]|=i>>>16},t.H.e=function(t,e,i){return(t[e>>>3]|t[1+(e>>>3)]<<8)>>>(7&e)&(1<<i)-1},t.H.b=function(t,e,i){return(t[e>>>3]|t[1+(e>>>3)]<<8|t[2+(e>>>3)]<<16)>>>(7&e)&(1<<i)-1},t.H.Z=function(t,e){return(t[e>>>3]|t[1+(e>>>3)]<<8|t[2+(e>>>3)]<<16)>>>(7&e)},t.H.i=function(t,e){return(t[e>>>3]|t[1+(e>>>3)]<<8|t[2+(e>>>3)]<<16|t[3+(e>>>3)]<<24)>>>(7&e)},t.H.m=function(){const t=Uint16Array,e=Uint32Array;return{K:new t(16),j:new t(16),X:[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],S:[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,999,999,999],T:[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0],q:new t(32),p:[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,65535,65535],z:[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0],c:new e(32),J:new t(512),_:[],h:new t(32),$:[],w:new t(32768),C:[],v:[],d:new t(32768),D:[],u:new t(512),Q:[],r:new t(32768),s:new e(286),Y:new e(30),a:new e(19),t:new e(15e3),k:new t(65536),g:new t(32768)}}(),function(){const e=t.H.m;for(var i=0;i<32768;i++){let t=i;t=(2863311530&t)>>>1|(1431655765&t)<<1,t=(3435973836&t)>>>2|(858993459&t)<<2,t=(4042322160&t)>>>4|(252645135&t)<<4,t=(4278255360&t)>>>8|(16711935&t)<<8,e.r[i]=(t>>>16|t<<16)>>>17}function n(t,e,i){for(;0!=e--;)t.push(0,i)}for(i=0;i<32;i++)e.q[i]=e.S[i]<<3|e.T[i],e.c[i]=e.p[i]<<4|e.z[i];n(e._,144,8),n(e._,112,9),n(e._,24,7),n(e._,8,8),t.H.n(e._,9),t.H.A(e._,9,e.J),t.H.l(e._,9),n(e.$,32,5),t.H.n(e.$,5),t.H.A(e.$,5,e.h),t.H.l(e.$,5),n(e.Q,19,0),n(e.C,286,0),n(e.D,30,0),n(e.v,320,0)}(),t.H.N}();function s(t){return[1,null,3,1,2,null,4][t.ctype]*t.depth}function o(t,e,i,n,r){let o=s(e);const a=Math.ceil(n*o/8);let l,u;o=Math.ceil(o/8);let c=t[i],f=0;if(c>1&&(t[i]=[0,0,1][c-2]),3==c)for(f=o;f<a;f++)t[f+1]=t[f+1]+(t[f+1-o]>>>1)&255;for(let e=0;e<r;e++)if(l=i+e*a,u=l+e+1,c=t[u-1],f=0,0==c)for(;f<a;f++)t[l+f]=t[u+f];else if(1==c){for(;f<o;f++)t[l+f]=t[u+f];for(;f<a;f++)t[l+f]=t[u+f]+t[l+f-o]}else if(2==c)for(;f<a;f++)t[l+f]=t[u+f]+t[l+f-a];else if(3==c){for(;f<o;f++)t[l+f]=t[u+f]+(t[l+f-a]>>>1);for(;f<a;f++)t[l+f]=t[u+f]+(t[l+f-a]+t[l+f-o]>>>1)}else{for(;f<o;f++)t[l+f]=t[u+f]+h(0,t[l+f-a],0);for(;f<a;f++)t[l+f]=t[u+f]+h(t[l+f-o],t[l+f-a],t[l+f-o-a])}return t}function h(t,e,i){const n=t+e-i,r=n-t,s=n-e,o=n-i;return r*r<=s*s&&r*r<=o*o?t:s*s<=o*o?e:i}function a(e,i,n){n.width=t.readUint(e,i),n.height=t.readUint(e,i+=4),n.depth=e[i+=4],i++,n.ctype=e[i],i++,n.compress=e[i],i++,n.filter=e[i],i++,n.interlace=e[i],i++}function l(t,e,i,n,r,s,o,h,a){const l=Math.min(e,r),u=Math.min(i,s);let c=0,f=0;for(let i=0;i<u;i++)for(let s=0;s<l;s++)if(o>=0&&h>=0?(c=i*e+s<<2,f=(h+i)*r+o+s<<2):(c=(-h+i)*e-o+s<<2,f=i*r+s<<2),0==a)n[f]=t[c],n[f+1]=t[c+1],n[f+2]=t[c+2],n[f+3]=t[c+3];else if(1==a){var d=t[c+3]*(1/255),p=t[c]*d,g=t[c+1]*d,m=t[c+2]*d,w=n[f+3]*(1/255),v=n[f]*w,y=n[f+1]*w,b=n[f+2]*w;const e=1-d,i=d+w*e,r=0==i?0:1/i;n[f+3]=255*i,n[f+0]=(p+v*e)*r,n[f+1]=(g+y*e)*r,n[f+2]=(m+b*e)*r}else if(2==a)p=t[c],g=t[c+1],m=t[c+2],v=n[f],y=n[f+1],b=n[f+2],(d=t[c+3])==(w=n[f+3])&&p==v&&g==y&&m==b?(n[f]=0,n[f+1]=0,n[f+2]=0,n[f+3]=0):(n[f]=p,n[f+1]=g,n[f+2]=m,n[f+3]=d);else if(3==a){if(p=t[c],g=t[c+1],m=t[c+2],v=n[f],y=n[f+1],b=n[f+2],(d=t[c+3])==(w=n[f+3])&&p==v&&g==y&&m==b)continue;if(d<220&&w>20)return!1}return!0}return{decode:function(e){const s=new Uint8Array(e);let o=8;const h=t,l=h.readUshort,u=h.readUint,c={tabs:{},frames:[]},f=new Uint8Array(s.length);let d,p=0,g=0;const m=[137,80,78,71,13,10,26,10];for(var w=0;w<8;w++)if(s[w]!=m[w])throw"The input is not a PNG file!";for(;o<s.length;){const t=h.readUint(s,o);o+=4;const e=h.readASCII(s,o,4);if(o+=4,"IHDR"==e)a(s,o,c);else if("iCCP"==e){for(var v=o;0!=s[v];)v++;h.readASCII(s,o,v-o);const i=s.slice(v+2,o+t);let a=null;try{a=n(i)}catch(t){a=r(i)}c.tabs[e]=a}else if("CgBI"==e)c.tabs[e]=s.slice(o,o+4);else if("IDAT"==e){for(w=0;w<t;w++)f[p+w]=s[o+w];p+=t}else if("acTL"==e)c.tabs[e]={num_frames:u(s,o),num_plays:u(s,o+4)},d=new Uint8Array(s.length);else if("fcTL"==e){0!=g&&((x=c.frames[c.frames.length-1]).data=i(c,d.slice(0,g),x.rect.width,x.rect.height),g=0);const t={x:u(s,o+12),y:u(s,o+16),width:u(s,o+4),height:u(s,o+8)};let e=l(s,o+22);e=l(s,o+20)/(0==e?100:e);const n={rect:t,delay:Math.round(1e3*e),dispose:s[o+24],blend:s[o+25]};c.frames.push(n)}else if("fdAT"==e){for(w=0;w<t-4;w++)d[g+w]=s[o+w+4];g+=t-4}else if("pHYs"==e)c.tabs[e]=[h.readUint(s,o),h.readUint(s,o+4),s[o+8]];else if("cHRM"==e)for(c.tabs[e]=[],w=0;w<8;w++)c.tabs[e].push(h.readUint(s,o+4*w));else if("tEXt"==e||"zTXt"==e){null==c.tabs[e]&&(c.tabs[e]={});var y=h.nextZero(s,o),b=h.readASCII(s,o,y-o),k=o+t-y-1;if("tEXt"==e)S=h.readASCII(s,y+1,k);else{var M=n(s.slice(y+2,y+2+k));S=h.readUTF8(M,0,M.length)}c.tabs[e][b]=S}else if("iTXt"==e){null==c.tabs[e]&&(c.tabs[e]={}),y=0,y=h.nextZero(s,v=o),b=h.readASCII(s,v,y-v);const i=s[v=y+1];var S;y=h.nextZero(s,v+=2),h.readASCII(s,v,y-v),y=h.nextZero(s,v=y+1),h.readUTF8(s,v,y-v),k=t-((v=y+1)-o),0==i?S=h.readUTF8(s,v,k):(M=n(s.slice(v,v+k)),S=h.readUTF8(M,0,M.length)),c.tabs[e][b]=S}else if("PLTE"==e)c.tabs[e]=h.readBytes(s,o,t);else if("hIST"==e){const t=c.tabs.PLTE.length/3;for(c.tabs[e]=[],w=0;w<t;w++)c.tabs[e].push(l(s,o+2*w))}else if("tRNS"==e)3==c.ctype?c.tabs[e]=h.readBytes(s,o,t):0==c.ctype?c.tabs[e]=l(s,o):2==c.ctype&&(c.tabs[e]=[l(s,o),l(s,o+2),l(s,o+4)]);else if("gAMA"==e)c.tabs[e]=h.readUint(s,o)/1e5;else if("sRGB"==e)c.tabs[e]=s[o];else if("bKGD"==e)0==c.ctype||4==c.ctype?c.tabs[e]=[l(s,o)]:2==c.ctype||6==c.ctype?c.tabs[e]=[l(s,o),l(s,o+2),l(s,o+4)]:3==c.ctype&&(c.tabs[e]=s[o]);else if("IEND"==e)break;o+=t,h.readUint(s,o),o+=4}var x;return 0!=g&&((x=c.frames[c.frames.length-1]).data=i(c,d.slice(0,g),x.rect.width,x.rect.height)),c.data=i(c,f,c.width,c.height),delete c.compress,delete c.interlace,delete c.filter,c},toRGBA8:function(t){const i=t.width,n=t.height;if(null==t.tabs.acTL)return[e(t.data,i,n,t).buffer];const r=[];null==t.frames[0].data&&(t.frames[0].data=t.data);const s=i*n*4,o=new Uint8Array(s),h=new Uint8Array(s),a=new Uint8Array(s);for(let c=0;c<t.frames.length;c++){const f=t.frames[c],d=f.rect.x,p=f.rect.y,g=f.rect.width,m=f.rect.height,w=e(f.data,g,m,t);if(0!=c)for(var u=0;u<s;u++)a[u]=o[u];if(0==f.blend?l(w,g,m,o,i,n,d,p,0):1==f.blend&&l(w,g,m,o,i,n,d,p,1),r.push(o.buffer.slice(0)),0==f.dispose);else if(1==f.dispose)l(h,g,m,o,i,n,d,p,0);else if(2==f.dispose)for(u=0;u<s;u++)o[u]=a[u]}return r},_paeth:h,_copyTile:l,_bin:t}}();!function(){const{_copyTile:t}=Oo,{_bin:e}=Oo,i=Oo._paeth;var n={table:function(){const t=new Uint32Array(256);for(let e=0;e<256;e++){let i=e;for(let t=0;t<8;t++)1&i?i=3988292384^i>>>1:i>>>=1;t[e]=i}return t}(),update(t,e,i,r){for(let s=0;s<r;s++)t=n.table[255&(t^e[i+s])]^t>>>8;return t},crc:(t,e,i)=>4294967295^n.update(4294967295,t,e,i)};function r(t,e,i,n){e[i]+=t[0]*n>>4,e[i+1]+=t[1]*n>>4,e[i+2]+=t[2]*n>>4,e[i+3]+=t[3]*n>>4}function s(t){return Math.max(0,Math.min(255,t))}function o(t,e){const i=t[0]-e[0],n=t[1]-e[1],r=t[2]-e[2],s=t[3]-e[3];return i*i+n*n+r*r+s*s}function h(t,e,i,n,h,a,l){null==l&&(l=1);const u=n.length,c=[];for(var f=0;f<u;f++){const t=n[f];c.push([t>>>0&255,t>>>8&255,t>>>16&255,t>>>24&255])}for(f=0;f<u;f++){let t=4294967295;for(var d=0,p=0;p<u;p++){var g=o(c[f],c[p]);p!=f&&g<t&&(t=g,d=p)}}const m=new Uint32Array(h.buffer),w=new Int16Array(e*i*4),v=[0,8,2,10,12,4,14,6,3,11,1,9,15,7,13,5];for(f=0;f<v.length;f++)v[f]=255*((v[f]+.5)/16-.5);for(let h=0;h<i;h++)for(let b=0;b<e;b++){var y;f=4*(h*e+b),y=2!=l?[s(t[f]+w[f]),s(t[f+1]+w[f+1]),s(t[f+2]+w[f+2]),s(t[f+3]+w[f+3])]:[s(t[f]+(g=v[4*(3&h)+(3&b)])),s(t[f+1]+g),s(t[f+2]+g),s(t[f+3]+g)],d=0;let k=16777215;for(p=0;p<u;p++){const t=o(y,c[p]);t<k&&(k=t,d=p)}const M=c[d],S=[y[0]-M[0],y[1]-M[1],y[2]-M[2],y[3]-M[3]];1==l&&(b!=e-1&&r(S,w,f+4,7),h!=i-1&&(0!=b&&r(S,w,f+4*e-4,3),r(S,w,f+4*e,5),b!=e-1&&r(S,w,f+4*e+4,1))),a[f>>2]=d,m[f>>2]=n[d]}}function a(t,i,r,s,o){null==o&&(o={});const{crc:h}=n,a=e.writeUint,l=e.writeUshort,u=e.writeASCII;let c=8;const f=t.frames.length>1;let d,p=!1,g=33+(f?20:0);if(null!=o.sRGB&&(g+=13),null!=o.pHYs&&(g+=21),null!=o.iCCP&&(d=pako.deflate(o.iCCP),g+=21+d.length+4),3==t.ctype){for(var m=t.plte.length,w=0;w<m;w++)t.plte[w]>>>24!=255&&(p=!0);g+=8+3*m+4+(p?8+1*m+4:0)}for(var v=0;v<t.frames.length;v++)f&&(g+=38),g+=(M=t.frames[v]).cimg.length+12,0!=v&&(g+=4);g+=12;const y=new Uint8Array(g),b=[137,80,78,71,13,10,26,10];for(w=0;w<8;w++)y[w]=b[w];if(a(y,c,13),c+=4,u(y,c,"IHDR"),c+=4,a(y,c,i),c+=4,a(y,c,r),c+=4,y[c]=t.depth,c++,y[c]=t.ctype,c++,y[c]=0,c++,y[c]=0,c++,y[c]=0,c++,a(y,c,h(y,c-17,17)),c+=4,null!=o.sRGB&&(a(y,c,1),c+=4,u(y,c,"sRGB"),c+=4,y[c]=o.sRGB,c++,a(y,c,h(y,c-5,5)),c+=4),null!=o.iCCP){const t=13+d.length;a(y,c,t),c+=4,u(y,c,"iCCP"),c+=4,u(y,c,"ICC profile"),c+=11,c+=2,y.set(d,c),c+=d.length,a(y,c,h(y,c-(t+4),t+4)),c+=4}if(null!=o.pHYs&&(a(y,c,9),c+=4,u(y,c,"pHYs"),c+=4,a(y,c,o.pHYs[0]),c+=4,a(y,c,o.pHYs[1]),c+=4,y[c]=o.pHYs[2],c++,a(y,c,h(y,c-13,13)),c+=4),f&&(a(y,c,8),c+=4,u(y,c,"acTL"),c+=4,a(y,c,t.frames.length),c+=4,a(y,c,null!=o.loop?o.loop:0),c+=4,a(y,c,h(y,c-12,12)),c+=4),3==t.ctype){for(a(y,c,3*(m=t.plte.length)),c+=4,u(y,c,"PLTE"),c+=4,w=0;w<m;w++){const e=3*w,i=t.plte[w],n=i>>>8&255,r=i>>>16&255;y[c+e+0]=255&i,y[c+e+1]=n,y[c+e+2]=r}if(c+=3*m,a(y,c,h(y,c-3*m-4,3*m+4)),c+=4,p){for(a(y,c,m),c+=4,u(y,c,"tRNS"),c+=4,w=0;w<m;w++)y[c+w]=t.plte[w]>>>24&255;c+=m,a(y,c,h(y,c-m-4,m+4)),c+=4}}let k=0;for(v=0;v<t.frames.length;v++){var M=t.frames[v];f&&(a(y,c,26),c+=4,u(y,c,"fcTL"),c+=4,a(y,c,k++),c+=4,a(y,c,M.rect.width),c+=4,a(y,c,M.rect.height),c+=4,a(y,c,M.rect.x),c+=4,a(y,c,M.rect.y),c+=4,l(y,c,s[v]),c+=2,l(y,c,1e3),c+=2,y[c]=M.dispose,c++,y[c]=M.blend,c++,a(y,c,h(y,c-30,30)),c+=4);const e=M.cimg;a(y,c,(m=e.length)+(0==v?0:4)),c+=4;const i=c;u(y,c,0==v?"IDAT":"fdAT"),c+=4,0!=v&&(a(y,c,k++),c+=4),y.set(e,c),c+=m,a(y,c,h(y,i,c-i)),c+=4}return a(y,c,0),c+=4,u(y,c,"IEND"),c+=4,a(y,c,h(y,c-4,4)),c+=4,y.buffer}function l(t,e,i){for(let n=0;n<t.frames.length;n++){const r=t.frames[n],s=r.rect.height,o=new Uint8Array(s*r.bpl+s);r.cimg=d(r.img,s,r.bpp,r.bpl,o,e,i)}}function u(e,i,n,r,s){const o=s[0],a=s[1],l=s[2],u=s[3],d=s[4],p=s[5];let m=6,w=8,v=255;for(var y=0;y<e.length;y++){const t=new Uint8Array(e[y]);for(var b=t.length,k=0;k<b;k+=4)v&=t[k+3]}const M=255!=v,S=function(e,i,n,r,s,o){const h=[];for(var a=0;a<e.length;a++){const c=new Uint8Array(e[a]),d=new Uint32Array(c.buffer);var l;let g=0,m=0,w=i,v=n,y=r?1:0;if(0!=a){const b=o||r||1==a||0!=h[a-2].dispose?1:2;let k=0,M=1e9;for(let t=0;t<b;t++){var u=new Uint8Array(e[a-1-t]);const r=new Uint32Array(e[a-1-t]);let o=i,h=n,l=-1,c=-1;for(let t=0;t<n;t++)for(let e=0;e<i;e++)d[p=t*i+e]!=r[p]&&(e<o&&(o=e),e>l&&(l=e),t<h&&(h=t),t>c&&(c=t));-1==l&&(o=h=l=c=0),s&&(!(1&~o)&&o--,!(1&~h)&&h--);const f=(l-o+1)*(c-h+1);f<M&&(M=f,k=t,g=o,m=h,w=l-o+1,v=c-h+1)}u=new Uint8Array(e[a-1-k]),1==k&&(h[a-1].dispose=2),l=new Uint8Array(w*v*4),t(u,i,n,l,w,v,-g,-m,0),y=t(c,i,n,l,w,v,-g,-m,3)?1:0,1==y?f(c,i,n,l,{x:g,y:m,width:w,height:v}):t(c,i,n,l,w,v,-g,-m,0)}else l=c.slice(0);h.push({rect:{x:g,y:m,width:w,height:v},img:l,blend:y,dispose:0})}if(r)for(a=0;a<h.length;a++){if(1==(g=h[a]).blend)continue;const t=g.rect,r=h[a-1].rect,o=Math.min(t.x,r.x),l=Math.min(t.y,r.y),u={x:o,y:l,width:Math.max(t.x+t.width,r.x+r.width)-o,height:Math.max(t.y+t.height,r.y+r.height)-l};h[a-1].dispose=1,a-1!=0&&c(e,i,n,h,a-1,u,s),c(e,i,n,h,a,u,s)}let d=0;if(1!=e.length)for(var p=0;p<h.length;p++){var g;d+=(g=h[p]).rect.width*g.rect.height}return h}(e,i,n,o,a,l),x={},A=[],$=[];if(0!=r){const t=[];for(k=0;k<S.length;k++)t.push(S[k].img.buffer);const e=function(t){let e=0;for(var i=0;i<t.length;i++)e+=t[i].byteLength;const n=new Uint8Array(e);let r=0;for(i=0;i<t.length;i++){const e=new Uint8Array(t[i]),s=e.length;for(let t=0;t<s;t+=4){let i=e[t],s=e[t+1],o=e[t+2];const h=e[t+3];0==h&&(i=s=o=0),n[r+t]=i,n[r+t+1]=s,n[r+t+2]=o,n[r+t+3]=h}r+=s}return n.buffer}(t),i=g(e,r);for(k=0;k<i.plte.length;k++)A.push(i.plte[k].est.rgba);let n=0;for(k=0;k<S.length;k++){const t=(C=S[k]).img.length;var z=new Uint8Array(i.inds.buffer,n>>2,t>>2);$.push(z);const e=new Uint8Array(i.abuf,n,t);p&&h(C.img,C.rect.width,C.rect.height,A,e,z),C.img.set(e),n+=t}}else for(y=0;y<S.length;y++){var C=S[y];const t=new Uint32Array(C.img.buffer);var T=C.rect.width;for(b=t.length,z=new Uint8Array(b),$.push(z),k=0;k<b;k++){const e=t[k];if(0!=k&&e==t[k-1])z[k]=z[k-1];else if(k>T&&e==t[k-T])z[k]=z[k-T];else{let t=x[e];if(null==t&&(x[e]=t=A.length,A.push(e),A.length>=300))break;z[k]=t}}}const E=A.length;for(E<=256&&0==d&&(w=E<=2?1:E<=4?2:E<=16?4:8,w=Math.max(w,u)),y=0;y<S.length;y++){const t=(C=S[y]).rect.height;let e=C.img,i=4*(T=C.rect.width),n=4;if(E<=256&&0==d){i=Math.ceil(w*T/8);var O=new Uint8Array(i*t);const r=$[y];for(let e=0;e<t;e++){k=e*i;const t=e*T;if(8==w)for(var I=0;I<T;I++)O[k+I]=r[t+I];else if(4==w)for(I=0;I<T;I++)O[k+(I>>1)]|=r[t+I]<<4-4*(1&I);else if(2==w)for(I=0;I<T;I++)O[k+(I>>2)]|=r[t+I]<<6-2*(3&I);else if(1==w)for(I=0;I<T;I++)O[k+(I>>3)]|=r[t+I]<<7-1*(7&I)}e=O,m=3,n=1}else if(0==M&&1==S.length){O=new Uint8Array(T*t*3);const r=T*t;for(k=0;k<r;k++){const t=3*k,i=4*k;O[t]=e[i],O[t+1]=e[i+1],O[t+2]=e[i+2]}e=O,m=2,n=3,i=3*T}C.img=e,C.bpl=i,C.bpp=n}return{ctype:m,depth:w,plte:A,frames:S}}function c(e,i,n,r,s,o,h){const a=Uint8Array,l=Uint32Array,u=new a(e[s-1]),c=new l(e[s-1]),d=s+1<e.length?new a(e[s+1]):null,p=new a(e[s]),g=new l(p.buffer);let m=i,w=n,v=-1,y=-1;for(let t=0;t<o.height;t++)for(let e=0;e<o.width;e++){const n=o.x+e,h=o.y+t,a=h*i+n,l=g[a];0==l||0==r[s-1].dispose&&c[a]==l&&(null==d||0!=d[4*a+3])||(n<m&&(m=n),n>v&&(v=n),h<w&&(w=h),h>y&&(y=h))}-1==v&&(m=w=v=y=0),h&&(!(1&~m)&&m--,!(1&~w)&&w--);const b=r[s];b.rect=o={x:m,y:w,width:v-m+1,height:y-w+1},b.blend=1,b.img=new Uint8Array(o.width*o.height*4),0==r[s-1].dispose?(t(u,i,n,b.img,o.width,o.height,-o.x,-o.y,0),f(p,i,n,b.img,o)):t(p,i,n,b.img,o.width,o.height,-o.x,-o.y,0)}function f(e,i,n,r,s){t(e,i,n,r,s.width,s.height,-s.x,-s.y,2)}function d(t,e,i,n,r,s,o){const h=[];let a,l=[0,1,2,3,4];-1!=s?l=[s]:(e*n>5e5||1==i)&&(l=[0]),o&&(a={level:0});const u=Eo;for(var c=0;c<l.length;c++){for(let s=0;s<e;s++)p(r,t,s,n,i,l[c]);h.push(u.deflate(r,a))}let f,d=1e9;for(c=0;c<h.length;c++)h[c].length<d&&(f=c,d=h[c].length);return h[f]}function p(t,e,n,r,s,o){const h=n*r;let a=h+n;if(t[a]=o,a++,0==o)if(r<500)for(var l=0;l<r;l++)t[a+l]=e[h+l];else t.set(new Uint8Array(e.buffer,h,r),a);else if(1==o){for(l=0;l<s;l++)t[a+l]=e[h+l];for(l=s;l<r;l++)t[a+l]=e[h+l]-e[h+l-s]+256&255}else if(0==n){for(l=0;l<s;l++)t[a+l]=e[h+l];if(2==o)for(l=s;l<r;l++)t[a+l]=e[h+l];if(3==o)for(l=s;l<r;l++)t[a+l]=e[h+l]-(e[h+l-s]>>1)+256&255;if(4==o)for(l=s;l<r;l++)t[a+l]=e[h+l]-i(e[h+l-s],0,0)+256&255}else{if(2==o)for(l=0;l<r;l++)t[a+l]=e[h+l]+256-e[h+l-r]&255;if(3==o){for(l=0;l<s;l++)t[a+l]=e[h+l]+256-(e[h+l-r]>>1)&255;for(l=s;l<r;l++)t[a+l]=e[h+l]+256-(e[h+l-r]+e[h+l-s]>>1)&255}if(4==o){for(l=0;l<s;l++)t[a+l]=e[h+l]+256-i(0,e[h+l-r],0)&255;for(l=s;l<r;l++)t[a+l]=e[h+l]+256-i(e[h+l-s],e[h+l-r],e[h+l-s-r])&255}}}function g(t,e){const i=new Uint8Array(t),n=i.slice(0),r=new Uint32Array(n.buffer),s=m(n,e),o=s[0],h=s[1],a=i.length,l=new Uint8Array(a>>2);let u;if(i.length<2e7)for(var c=0;c<a;c+=4)u=w(o,f=i[c]*(1/255),d=i[c+1]*(1/255),p=i[c+2]*(1/255),g=i[c+3]*(1/255)),l[c>>2]=u.ind,r[c>>2]=u.est.rgba;else for(c=0;c<a;c+=4){var f=i[c]*(1/255),d=i[c+1]*(1/255),p=i[c+2]*(1/255),g=i[c+3]*(1/255);for(u=o;u.left;)u=v(u.est,f,d,p,g)<=0?u.left:u.right;l[c>>2]=u.ind,r[c>>2]=u.est.rgba}return{abuf:n.buffer,inds:l,plte:h}}function m(t,e,i){null==i&&(i=1e-4);const n=new Uint32Array(t.buffer),r={i0:0,i1:t.length,bst:null,est:null,tdst:0,left:null,right:null};r.bst=k(t,r.i0,r.i1),r.est=M(r.bst);const s=[r];for(;s.length<e;){let e=0,r=0;for(var o=0;o<s.length;o++)s[o].est.L>e&&(e=s[o].est.L,r=o);if(e<i)break;const h=s[r],a=y(t,n,h.i0,h.i1,h.est.e,h.est.eMq255);if(h.i0>=a||h.i1<=a){h.est.L=0;continue}const l={i0:h.i0,i1:a,bst:null,est:null,tdst:0,left:null,right:null};l.bst=k(t,l.i0,l.i1),l.est=M(l.bst);const u={i0:a,i1:h.i1,bst:null,est:null,tdst:0,left:null,right:null};for(u.bst={R:[],m:[],N:h.bst.N-l.bst.N},o=0;o<16;o++)u.bst.R[o]=h.bst.R[o]-l.bst.R[o];for(o=0;o<4;o++)u.bst.m[o]=h.bst.m[o]-l.bst.m[o];u.est=M(u.bst),h.left=l,h.right=u,s[r]=l,s.push(u)}for(s.sort(((t,e)=>e.bst.N-t.bst.N)),o=0;o<s.length;o++)s[o].ind=o;return[r,s]}function w(t,e,i,n,r){if(null==t.left)return t.tdst=function(t,e,i,n,r){const s=e-t[0],o=i-t[1],h=n-t[2],a=r-t[3];return s*s+o*o+h*h+a*a}(t.est.q,e,i,n,r),t;const s=v(t.est,e,i,n,r);let o=t.left,h=t.right;s>0&&(o=t.right,h=t.left);const a=w(o,e,i,n,r);if(a.tdst<=s*s)return a;const l=w(h,e,i,n,r);return l.tdst<a.tdst?l:a}function v(t,e,i,n,r){const{e:s}=t;return s[0]*e+s[1]*i+s[2]*n+s[3]*r-t.eMq}function y(t,e,i,n,r,s){for(n-=4;i<n;){for(;b(t,i,r)<=s;)i+=4;for(;b(t,n,r)>s;)n-=4;if(i>=n)break;const o=e[i>>2];e[i>>2]=e[n>>2],e[n>>2]=o,i+=4,n-=4}for(;b(t,i,r)>s;)i-=4;return i+4}function b(t,e,i){return t[e]*i[0]+t[e+1]*i[1]+t[e+2]*i[2]+t[e+3]*i[3]}function k(t,e,i){const n=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],r=[0,0,0,0],s=i-e>>2;for(let s=e;s<i;s+=4){const e=t[s]*(1/255),i=t[s+1]*(1/255),o=t[s+2]*(1/255),h=t[s+3]*(1/255);r[0]+=e,r[1]+=i,r[2]+=o,r[3]+=h,n[0]+=e*e,n[1]+=e*i,n[2]+=e*o,n[3]+=e*h,n[5]+=i*i,n[6]+=i*o,n[7]+=i*h,n[10]+=o*o,n[11]+=o*h,n[15]+=h*h}return n[4]=n[1],n[8]=n[2],n[9]=n[6],n[12]=n[3],n[13]=n[7],n[14]=n[11],{R:n,m:r,N:s}}function M(t){const{R:e}=t,{m:i}=t,{N:n}=t,r=i[0],s=i[1],o=i[2],h=i[3],a=0==n?0:1/n,l=[e[0]-r*r*a,e[1]-r*s*a,e[2]-r*o*a,e[3]-r*h*a,e[4]-s*r*a,e[5]-s*s*a,e[6]-s*o*a,e[7]-s*h*a,e[8]-o*r*a,e[9]-o*s*a,e[10]-o*o*a,e[11]-o*h*a,e[12]-h*r*a,e[13]-h*s*a,e[14]-h*o*a,e[15]-h*h*a],u=l,c=S;let f=[Math.random(),Math.random(),Math.random(),Math.random()],d=0,p=0;if(0!=n)for(let t=0;t<16&&(f=c.multVec(u,f),p=Math.sqrt(c.dot(f,f)),f=c.sml(1/p,f),!(0!=t&&Math.abs(p-d)<1e-9));t++)d=p;const g=[r*a,s*a,o*a,h*a];return{Cov:l,q:g,e:f,L:d,eMq255:c.dot(c.sml(255,g),f),eMq:c.dot(f,g),rgba:(Math.round(255*g[3])<<24|Math.round(255*g[2])<<16|Math.round(255*g[1])<<8|Math.round(255*g[0]))>>>0}}var S={multVec:(t,e)=>[t[0]*e[0]+t[1]*e[1]+t[2]*e[2]+t[3]*e[3],t[4]*e[0]+t[5]*e[1]+t[6]*e[2]+t[7]*e[3],t[8]*e[0]+t[9]*e[1]+t[10]*e[2]+t[11]*e[3],t[12]*e[0]+t[13]*e[1]+t[14]*e[2]+t[15]*e[3]],dot:(t,e)=>t[0]*e[0]+t[1]*e[1]+t[2]*e[2]+t[3]*e[3],sml:(t,e)=>[t*e[0],t*e[1],t*e[2],t*e[3]]};Oo.encode=function(t,e,i,n,r,s,o){null==n&&(n=0),null==o&&(o=!1);const h=u(t,e,i,n,[!1,!1,!1,0,o,!1]);return l(h,-1),a(h,e,i,r,s)},Oo.encodeLL=function(t,e,i,n,r,s,o,h){const u={ctype:0+(1==n?0:2)+(0==r?0:4),depth:s,frames:[]},c=(n+r)*s,f=c*e;for(let n=0;n<t.length;n++)u.frames.push({rect:{x:0,y:0,width:e,height:i},img:new Uint8Array(t[n]),blend:0,dispose:1,bpp:Math.ceil(c/8),bpl:Math.ceil(f/8)});return l(u,0,!0),a(u,e,i,o,h)},Oo.encode.compress=u,Oo.encode.dither=h,Oo.quantize=g,Oo.quantize.getKDtree=m,Oo.quantize.getNearest=w}();const Io={toArrayBuffer(t,e){const i=t.width,n=t.height,r=i<<2,s=t.getContext("2d").getImageData(0,0,i,n),o=new Uint32Array(s.data.buffer),h=(32*i+31)/32<<2,a=h*n,l=122+a,u=new ArrayBuffer(l),c=new DataView(u),f=1<<20;let d,p,g,m,w=f,v=0,y=0,b=0;function k(t){c.setUint16(y,t,!0),y+=2}function M(t){c.setUint32(y,t,!0),y+=4}function S(t){y+=t}k(19778),M(l),S(4),M(122),M(108),M(i),M(-n>>>0),k(1),k(32),M(3),M(a),M(2835),M(2835),S(8),M(16711680),M(65280),M(255),M(4278190080),M(1466527264),function t(){for(;v<n&&w>0;){for(m=122+v*h,d=0;d<r;)w--,p=o[b++],g=p>>>24,c.setUint32(m+d,p<<8|g),d+=4;v++}b<o.length?(w=f,setTimeout(t,Io._dly)):e(u)}()},toBlob(t,e){this.toArrayBuffer(t,(t=>{e(new Blob([t],{type:"image/bmp"}))}))},_dly:9};var jo={CHROME:"CHROME",FIREFOX:"FIREFOX",DESKTOP_SAFARI:"DESKTOP_SAFARI",IE:"IE",IOS:"IOS",ETC:"ETC"},Po={[jo.CHROME]:16384,[jo.FIREFOX]:11180,[jo.DESKTOP_SAFARI]:16384,[jo.IE]:8192,[jo.IOS]:4096,[jo.ETC]:8192};const Ro="undefined"!=typeof window,Do="undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope,_o=Ro&&window.cordova&&window.cordova.require&&window.cordova.require("cordova/modulemapper"),Lo=(Ro||Do)&&(_o&&_o.getOriginalSymbol(window,"File")||"undefined"!=typeof File&&File),Bo=(Ro||Do)&&(_o&&_o.getOriginalSymbol(window,"FileReader")||"undefined"!=typeof FileReader&&FileReader);function Fo(t,e,i=Date.now()){return new Promise((n=>{const r=t.split(","),s=r[0].match(/:(.*?);/)[1],o=globalThis.atob(r[1]);let h=o.length;const a=new Uint8Array(h);for(;h--;)a[h]=o.charCodeAt(h);const l=new Blob([a],{type:s});l.name=e,l.lastModified=i,n(l)}))}function No(t){return new Promise(((e,i)=>{const n=new Bo;n.onload=()=>e(n.result),n.onerror=t=>i(t),n.readAsDataURL(t)}))}function Wo(t){return new Promise(((e,i)=>{const n=new Image;n.onload=()=>e(n),n.onerror=t=>i(t),n.src=t}))}function Uo(){if(void 0!==Uo.cachedResult)return Uo.cachedResult;let t=jo.ETC;const{userAgent:e}=navigator;return/Chrom(e|ium)/i.test(e)?t=jo.CHROME:/iP(ad|od|hone)/i.test(e)&&/WebKit/i.test(e)?t=jo.IOS:/Safari/i.test(e)?t=jo.DESKTOP_SAFARI:/Firefox/i.test(e)?t=jo.FIREFOX:(/MSIE/i.test(e)||1==!!document.documentMode)&&(t=jo.IE),Uo.cachedResult=t}function Ko(t,e){const i=Uo(),n=Po[i];let r=t,s=e,o=r*s;const h=r>s?s/r:r/s;for(;o>n*n;){const t=(n+r)/2,e=(n+s)/2;t<e?(s=e,r=e*h):(s=t*h,r=t),o=r*s}return{width:r,height:s}}function Ho(t,e){let i,n;try{if(i=new OffscreenCanvas(t,e),n=i.getContext("2d"),null===n)throw new Error("getContext of OffscreenCanvas returns null")}catch(t){i=document.createElement("canvas"),n=i.getContext("2d")}return i.width=t,i.height=e,[i,n]}function Vo(t,e){const{width:i,height:n}=Ko(t.width,t.height),[r,s]=Ho(i,n);return e&&/jpe?g/.test(e)&&(s.fillStyle="white",s.fillRect(0,0,r.width,r.height)),s.drawImage(t,0,0,r.width,r.height),r}function Go(){return void 0!==Go.cachedResult||(Go.cachedResult=["iPad Simulator","iPhone Simulator","iPod Simulator","iPad","iPhone","iPod"].includes(navigator.platform)||navigator.userAgent.includes("Mac")&&"undefined"!=typeof document&&"ontouchend"in document),Go.cachedResult}function Xo(t,e={}){return new Promise((function(i,n){let r,s;var o=function(){try{return s=Vo(r,e.fileType||t.type),i([r,s])}catch(t){return n(t)}},h=function(){try{var e=function(t){try{throw t}catch(t){return n(t)}};try{let i;return No(t).then((function(t){try{return i=t,Wo(i).then((function(t){try{return r=t,function(){try{return o()}catch(t){return n(t)}}()}catch(t){return e(t)}}),e)}catch(t){return e(t)}}),e)}catch(t){e(t)}}catch(t){return n(t)}};try{if(Go()||[jo.DESKTOP_SAFARI,jo.MOBILE_SAFARI].includes(Uo()))throw new Error("Skip createImageBitmap on IOS and Safari");return createImageBitmap(t).then((function(t){try{return r=t,o()}catch(t){return h()}}),h)}catch(t){h()}}))}function Yo(t,e,i,n,r=1){return new Promise((function(s,o){let h;if("image/png"===e){let l,u,c;return l=t.getContext("2d"),({data:u}=l.getImageData(0,0,t.width,t.height)),c=Oo.encode([u.buffer],t.width,t.height,4096*r),h=new Blob([c],{type:e}),h.name=i,h.lastModified=n,a.call(this)}{if("image/bmp"===e)return new Promise((e=>Io.toBlob(t,e))).then(function(t){try{return h=t,h.name=i,h.lastModified=n,f.call(this)}catch(t){return o(t)}}.bind(this),o);{if("function"==typeof OffscreenCanvas&&t instanceof OffscreenCanvas)return t.convertToBlob({type:e,quality:r}).then(function(t){try{return h=t,h.name=i,h.lastModified=n,d.call(this)}catch(t){return o(t)}}.bind(this),o);{let p;return p=t.toDataURL(e,r),Fo(p,i,n).then(function(t){try{return h=t,d.call(this)}catch(t){return o(t)}}.bind(this),o)}function d(){return f.call(this)}}function f(){return a.call(this)}}function a(){return s(h)}}))}function qo(t){t.width=0,t.height=0}function Jo(){return new Promise((function(t,e){let i,n,r,s;return void 0!==Jo.cachedResult?t(Jo.cachedResult):Fo("data:image/jpeg;base64,/9j/4QAiRXhpZgAATU0AKgAAAAgAAQESAAMAAAABAAYAAAAAAAD/2wCEAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAf/AABEIAAEAAgMBEQACEQEDEQH/xABKAAEAAAAAAAAAAAAAAAAAAAALEAEAAAAAAAAAAAAAAAAAAAAAAQEAAAAAAAAAAAAAAAAAAAAAEQEAAAAAAAAAAAAAAAAAAAAA/9oADAMBAAIRAxEAPwA/8H//2Q==","test.jpg",Date.now()).then((function(o){try{return i=o,Xo(i).then((function(o){try{return n=o[1],Yo(n,i.type,i.name,i.lastModified).then((function(i){try{return r=i,qo(n),Xo(r).then((function(i){try{return s=i[0],t(Jo.cachedResult=1===s.width&&2===s.height)}catch(t){return e(t)}}),e)}catch(t){return e(t)}}),e)}catch(t){return e(t)}}),e)}catch(t){return e(t)}}),e)}))}function Qo(t){return new Promise(((e,i)=>{const n=new Bo;n.onload=t=>{const i=new DataView(t.target.result);if(65496!=i.getUint16(0,!1))return e(-2);const n=i.byteLength;let r=2;for(;r<n;){if(i.getUint16(r+2,!1)<=8)return e(-1);const t=i.getUint16(r,!1);if(r+=2,65505==t){if(1165519206!=i.getUint32(r+=2,!1))return e(-1);const t=18761==i.getUint16(r+=6,!1);r+=i.getUint32(r+4,t);const n=i.getUint16(r,t);r+=2;for(let s=0;s<n;s++)if(274==i.getUint16(r+12*s,t))return e(i.getUint16(r+12*s+8,t))}else{if(65280&~t)break;r+=i.getUint16(r,!1)}}return e(-1)},n.onerror=t=>i(t),n.readAsArrayBuffer(t)}))}function Zo(t,e){const{width:i}=t,{height:n}=t,{maxWidthOrHeight:r}=e;let s,o=t;return isFinite(r)&&(i>r||n>r)&&([o,s]=Ho(i,n),i>n?(o.width=r,o.height=n/i*r):(o.width=i/n*r,o.height=r),s.drawImage(t,0,0,o.width,o.height),qo(t)),o}function th(t,e){const{width:i}=t,{height:n}=t,[r,s]=Ho(i,n);switch(e>4&&e<9?(r.width=n,r.height=i):(r.width=i,r.height=n),e){case 2:s.transform(-1,0,0,1,i,0);break;case 3:s.transform(-1,0,0,-1,i,n);break;case 4:s.transform(1,0,0,-1,0,n);break;case 5:s.transform(0,1,1,0,0,0);break;case 6:s.transform(0,1,-1,0,n,0);break;case 7:s.transform(0,-1,-1,0,n,i);break;case 8:s.transform(0,-1,1,0,0,i)}return s.drawImage(t,0,0,i,n),qo(t),r}function eh(t,e,i=0){return new Promise((function(n,r){let s,o,h,a,l,u,c,f,d,p,g,m,w,v,y,b,k,M,S,x;function A(t=5){if(e.signal&&e.signal.aborted)throw e.signal.reason;s+=t,e.onProgress(Math.min(s,100))}function $(t){if(e.signal&&e.signal.aborted)throw e.signal.reason;s=Math.min(Math.max(t,s),100),e.onProgress(s)}return s=i,o=e.maxIteration||10,h=1024*e.maxSizeMB*1024,A(),Xo(t,e).then(function(i){try{return[,a]=i,A(),l=Zo(a,e),A(),new Promise((function(i,n){var r;if(!(r=e.exifOrientation))return Qo(t).then(function(t){try{return r=t,s.call(this)}catch(t){return n(t)}}.bind(this),n);function s(){return i(r)}return s.call(this)})).then(function(i){try{return u=i,A(),Jo().then(function(i){try{return c=i?l:th(l,u),A(),f=e.initialQuality||1,d=e.fileType||t.type,Yo(c,d,t.name,t.lastModified,f).then(function(i){try{{if(p=i,A(),g=p.size>h,m=p.size>t.size,!g&&!m)return $(100),n(p);var s;function u(){if(o--&&(y>h||y>w)){let e,i;return e=x?.95*S.width:S.width,i=x?.95*S.height:S.height,[k,M]=Ho(e,i),M.drawImage(S,0,0,e,i),f*="image/png"===d?.85:.95,Yo(k,d,t.name,t.lastModified,f).then((function(t){try{return b=t,qo(S),S=k,y=b.size,$(Math.min(99,Math.floor((v-y)/(v-h)*100))),u}catch(t){return r(t)}}),r)}return[1]}return w=t.size,v=p.size,y=v,S=c,x=!e.alwaysKeepResolution&&g,(s=function(t){for(;t;){if(t.then)return void t.then(s,r);try{if(t.pop){if(t.length)return t.pop()?z.call(this):t;t=u}else t=t.call(this)}catch(t){return r(t)}}}.bind(this))(u);function z(){return qo(S),qo(k),qo(l),qo(c),qo(a),$(100),n(b)}}}catch(C){return r(C)}}.bind(this),r)}catch(t){return r(t)}}.bind(this),r)}catch(t){return r(t)}}.bind(this),r)}catch(t){return r(t)}}.bind(this),r)}))}let ih;function nh(t,e){return new Promise(((i,n)=>{ih||(ih=function(){const t=[];return t.push("\nlet scriptImported = false\nself.addEventListener('message', async (e) => {\n const { file, id, imageCompressionLibUrl, options } = e.data\n options.onProgress = (progress) => self.postMessage({ progress, id })\n try {\n if (!scriptImported) {\n // console.log('[worker] importScripts', imageCompressionLibUrl)\n self.importScripts(imageCompressionLibUrl)\n scriptImported = true\n }\n // console.log('[worker] self', self)\n const compressedFile = await imageCompression(file, options)\n self.postMessage({ file: compressedFile, id })\n } catch (e) {\n // console.error('[worker] error', e)\n self.postMessage({ error: e.message + '\\n' + e.stack, id })\n }\n})\n"),URL.createObjectURL(new Blob(t))}());const r=new Worker(ih);r.addEventListener("message",(function(t){if(e.signal&&e.signal.aborted)r.terminate();else if(void 0===t.data.progress){if(t.data.error)return n(new Error(t.data.error)),void r.terminate();i(t.data.file),r.terminate()}else e.onProgress(t.data.progress)})),r.addEventListener("error",n),e.signal&&e.signal.addEventListener("abort",(()=>{n(e.signal.reason),r.terminate()})),r.postMessage({file:t,imageCompressionLibUrl:e.libURL,options:{...e,onProgress:void 0,signal:void 0}})}))}function rh(t,e){return new Promise((function(i,n){let r,s,o,h,a,l;if(r={...e},o=0,({onProgress:h}=r),r.maxSizeMB=r.maxSizeMB||Number.POSITIVE_INFINITY,a="boolean"!=typeof r.useWebWorker||r.useWebWorker,delete r.useWebWorker,r.onProgress=t=>{o=t,"function"==typeof h&&h(o)},!(t instanceof Blob||t instanceof Lo))return n(new Error("The file given is not an instance of Blob or File"));if(!/^image/.test(t.type))return n(new Error("The file given is not an image"));if(l="undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope,!a||"function"!=typeof Worker||l)return eh(t,r).then(function(t){try{return s=t,f.call(this)}catch(t){return n(t)}}.bind(this),n);var u=function(){try{return f.call(this)}catch(t){return n(t)}}.bind(this),c=function(){try{return eh(t,r).then((function(t){try{return s=t,u()}catch(t){return n(t)}}),n)}catch(t){return n(t)}};try{return r.libURL=r.libURL||"https://cdn.jsdelivr.net/npm/browser-image-compression@2.0.2/dist/browser-image-compression.js",nh(t,r).then((function(t){try{return s=t,u()}catch(t){return c()}}),c)}catch(t){c()}function f(){try{s.name=t.name,s.lastModified=t.lastModified}catch(t){}try{r.preserveExif&&"image/jpeg"===t.type&&(!r.fileType||r.fileType&&r.fileType===t.type)&&(s=$o(t,s))}catch(t){}return i(s)}}))}rh.getDataUrlFromFile=No,rh.getFilefromDataUrl=Fo,rh.loadImage=Wo,rh.drawImageInCanvas=Vo,rh.drawFileInCanvas=Xo,rh.canvasToFile=Yo,rh.getExifOrientation=Qo,rh.handleMaxWidthOrHeight=Zo,rh.followExifOrientation=th,rh.cleanupCanvasMemory=qo,rh.isAutoOrientationInBrowser=Jo,rh.approximateBelowMaximumCanvasSizeOfBrowser=Ko,rh.copyExifWithoutOrientation=$o,rh.getBrowserName=Uo,rh.version="2.0.2";class sh{static isGifFile(t){const e=t.type.trim().toLowerCase();return"image/gif"===e||""===e&&t.name.toLowerCase().endsWith(".gif")}}class oh extends vo{toolType="image";fileInput=null;maxCompressionSize=1200;multiImportOffset=20;constructor(t){super(t),this.setupFileInput()}onActivate(){this.openFilePicker()}openFilePicker(){this._core.store.isDisabled||this.fileInput?.click()}setupFileInput(){this.fileInput=document.createElement("input"),this.fileInput.type="file",this.fileInput.accept="image/*",this.fileInput.multiple=!0,this.fileInput.style.display="none",this.fileInput.addEventListener("change",this.handleFileSelect.bind(this)),this.fileInput.addEventListener("cancel",this.handleCancel.bind(this)),document.body.appendChild(this.fileInput)}handleFileSelect(t){const e=t.target,i=e.files?Array.from(e.files):[];if(0===i.length)return console.info("File selection cancelled by user."),this.handleCancel(),void(e&&(e.value=""));const n=i.map((async t=>{const e=await this.prepareImageFile(t);return lo.fromBlob(this._core,e)}));Promise.allSettled(n).then((t=>{const e=[];for(const i of t)"fulfilled"===i.status?e.push(i.value):console.error("Error during image compression or processing:",i.reason);0!==e.length?this.addImagesToStore(e):this.handleCancel()})),e&&(e.value="")}async prepareImageFile(t){return sh.isGifFile(t)?t:rh(t,{maxWidthOrHeight:this.maxCompressionSize})}addImagesToStore(t){const e=this._core.store.currentZIndex;t.forEach(((t,i)=>{if(t.zIndex=e+i,t.centerInViewport(),i>0){const e=i*this.multiImportOffset;t.updatePosition(t.translateX+e,t.translateY+e)}this._core.addObject(t)})),this._core.store.setState("activeTool",this._core.toolRegistry.getTool("selection")),this._core.selectObjects(t),this._core.engine.emitObjectsChange(),this._core.engine.emitObjectsAdded(t)}handleCancel(){this._core.store.setState("activeTool",this._core.toolRegistry.getTool("selection"))}}class hh extends vo{toolType="text";_fontFamily="Arial";_fontSize=16;_fontColor=m[0];_opacity=1;get fontFamily(){return this._core?.store?.activeText?.fontFamily??this._fontFamily}set fontFamily(t){this._fontFamily=t,this.applyToActiveText({fontFamily:t})}get fontSize(){return this._core?.store?.activeText?.fontSize??this._fontSize}set fontSize(t){this._fontSize=t,this.applyToActiveText({fontSize:t})}get fontColor(){return this._core?.store?.activeText?.fontColor??this._fontColor}set fontColor(t){this._fontColor=t,this.applyToActiveText({fontColor:t})}get opacity(){return this._core?.store?.activeText?.opacity??this._opacity}set opacity(t){this._opacity=t,this.applyToActiveText({opacity:t})}palette=[...m];sizes=[...ko];availableFonts;constructor(t){super(t)}applyToActiveText(t){const e=this._core?.store?.activeText;e&&(this._core.updateObject(e,t),this._core.rerender())}handlePointerDown(t){if(t.cancelable&&t.preventDefault(),"mouse"===t.pointerType){const e=t.composedPath().slice(1).find((t=>t.classList&&t.classList.contains("object"))),i=e?.id?this._core.findObjectById(e.id):null,n=this._core.store.activeText;if(null===n&&i instanceof no)return void i.edit(t);if(null!==n&&i instanceof no)return n.save(),void i.edit(t);if(null!==n&&i instanceof no==0)return this._core.resetActiveText(),void this._core.store.setState("activeTool",this._core.toolRegistry.getTool("selection"));if(!1===yo.isLeftClick(t))return;const r=t.clientX-this._core.store.offsetX,s=t.clientY-this._core.store.offsetY,o=this._core.store.state.scale,h=no.create(this._core,this.fontSize,this.fontFamily,this._core.store.state.lockDrawingScale?1:o);h.fontColor=this.fontColor,h.opacity=this.opacity,h.translateX=(r-this._core.store.state.translateX)/o,h.translateY=(s-this._core.store.state.translateY)/o,h.zIndex=this._core.store.currentZIndex,h.isNewlyCreated=!0,this._core.store.objects.insert(h),this._core.rerender(),h.edit(t)}if("touch"===t.pointerType||"pen"===t.pointerType){const e=Array.from(this._core.store.state.pointers.values()),i=t.composedPath().slice(1).find((t=>t.classList&&t.classList.contains("object"))),n=i?.id?this._core.findObjectById(i.id):null,r=this._core.store.activeText;if(null===r&&n instanceof no)return void n.edit(t);if(null!==r&&n instanceof no)return r.save(),void n.edit(t);if(null!==r&&n instanceof no==0)return this._core.resetActiveText(),void this._core.store.setState("activeTool",this._core.toolRegistry.getTool("selection"));if(e.length>1)return;const s=Math.round(e[0].clientX-this._core.store.offsetX),o=Math.round(e[0].clientY-this._core.store.offsetY),h=this._core.store.state.scale,a=no.create(this._core,this.fontSize,this.fontFamily,this._core.store.state.lockDrawingScale?1:h);a.fontColor=this.fontColor,a.opacity=this.opacity,a.translateX=(s-this._core.store.state.translateX)/h,a.translateY=(o-this._core.store.state.translateY)/h,a.zIndex=this._core.store.currentZIndex,a.isNewlyCreated=!0,this._core.store.objects.insert(a),this._core.rerender(),a.edit(t)}}handlePointerUp(t){const e=this._core.store.activeText;e&&e.isMounted&&!e.editor?.hasFocus()&&e.focus({x:t.clientX,y:t.clientY})}}class ah extends vo{toolType="shape";shapeType=fo.Rectangle;fillColor={light:"transparent",dark:"transparent"};strokeColor=m[0];strokeWidth=4;opacity=1;fontFamily="Arial";fontSize=16;fontColor=m[0];palette=[...m];sizes=[...bo];startX=0;startY=0;isDrawing=!1;currentShape=null;constructor(t){super(t)}handlePointerDown(t){if(t.cancelable&&t.preventDefault(),"mouse"===t.pointerType){const e=t.composedPath().slice(1).find((t=>t.classList&&t.classList.contains("object"))),i=this._core.findObjectById(e?.id),n=this._core.store.activeShape;if(null===n&&i instanceof po)return void i.edit(t);if(null!==n&&i instanceof po)return n.save(),void i.edit(t);if(null!==n&&i instanceof po==0)return this._core.resetActiveShape(),void this._core.store.setState("activeTool",this._core.toolRegistry.getTool("selection"));if(!1===yo.isLeftClick(t))return;this.startDrawing(t.clientX,t.clientY)}if("touch"===t.pointerType||"pen"===t.pointerType){const e=Array.from(this._core.store.state.pointers.values()),i=t.composedPath().slice(1).find((t=>t.classList&&t.classList.contains("object"))),n=this._core.findObjectById(i?.id),r=this._core.store.activeShape;if(null===r&&n instanceof po)return void n.edit(t);if(null!==r&&n instanceof po)return r.save(),void n.edit(t);if(null!==r&&n instanceof po==0)return this._core.resetActiveShape(),void this._core.store.setState("activeTool",this._core.toolRegistry.getTool("selection"));if(e.length>1)return;const s=Math.round(e[0].clientX),o=Math.round(e[0].clientY);this.startDrawing(s,o)}}handlePointerMove(t){if(t.cancelable&&t.preventDefault(),this.isDrawing&&this.currentShape&&("mouse"===t.pointerType&&this.updateShapeSize(t.clientX,t.clientY),"touch"===t.pointerType||"pen"===t.pointerType)){const t=Array.from(this._core.store.state.pointers.values());if(1===t.length){const e=Math.round(t[0].clientX),i=Math.round(t[0].clientY);this.updateShapeSize(e,i)}}}handlePointerUp(t){t.cancelable&&t.preventDefault(),this.isDrawing&&this.currentShape&&this.finishDrawing()}startDrawing(t,e){const i=this._core.store.state.scale,n=this._core.store.state.lockDrawingScale,r=n?i:1;this.startX=(t-this._core.store.offsetX)/r,this.startY=(e-this._core.store.offsetY)/r,this.isDrawing=!0,this.currentShape=po.create(this._core,{x:this.startX,y:this.startY,translateX:-this._core.store.state.translateX/r,translateY:-this._core.store.state.translateY/r,width:1,height:1,shapeType:this.shapeType,fillColor:this.fillColor,strokeColor:this.strokeColor,strokeWidth:this.strokeWidth,opacity:this.opacity,fontSize:this.fontSize,fontFamily:this.fontFamily,scale:n?1:i}),this._core.store.objects.insert(this.currentShape),this._core.store.objects?.setActiveDrawingObject(this.currentShape.id),this._core.rerender()}updateShapeSize(t,e){if(!this.currentShape)return;const i=this._core.store.state.lockDrawingScale?this._core.store.state.scale:1,n=(t-this._core.store.offsetX)/i,r=(e-this._core.store.offsetY)/i,s=Math.min(this.startX,n),o=Math.min(this.startY,r),h=Math.abs(n-this.startX),a=Math.abs(r-this.startY);this.currentShape.x=s,this.currentShape.y=o,this.currentShape.width=Math.max(1,h),this.currentShape.height=Math.max(1,a),this.currentShape.translateX=-this._core.store.state.translateX/i,this.currentShape.translateY=-this._core.store.state.translateY/i,this.currentShape.updateDimensions(),this._core.store.objects.update(this.currentShape)}finishDrawing(){if(this.currentShape){if(this.currentShape.width<10&&this.currentShape.height<10){const t=this.currentShape.id;this._core.store.objects.remove((e=>e.id===t))}else this.currentShape.zIndex=this._core.store.currentZIndex,this._core.store.objects.update(this.currentShape),this._core.engine.emitObjectsChange(),this._core.engine.emitObjectsAdded([this.currentShape]),this._core.selectObjects([this.currentShape]),this._core.store.setState("activeTool",this._core.toolRegistry.getTool("selection"));this.isDrawing=!1,this._core.store.objects?.setActiveDrawingObject(null),this.currentShape=null,this._core.store.objects?.stopUndoCapturing(),this._core.rerender()}}}class lh{static _pointerCursor=null;static getPointerCursor(){return this._pointerCursor||(this._pointerCursor=this.getCursor({iconName:"pointer"})),this._pointerCursor}static getCursor(t){const e="default"===t.iconName?"mouse-pointer":t.iconName,i=j.get(e);if(!i)return console.warn(`Icon "${e}" not found in registry.`),"auto";const n=t.size||24,r=t.rotation||0,s=t.color||"black",o=t.hotspot||("default"===t.iconName?{x:4,y:4}:{x:n/2,y:n/2});let h=i.replace(/width="\d+"/,`width="${n}"`).replace(/height="\d+"/,`height="${n}"`).replace(/currentColor/g,s);const a=n/2;return`url('data:image/svg+xml;charset=utf-8,${encodeURIComponent(`\n <svg xmlns="http://www.w3.org/2000/svg" width="${n}" height="${n}" viewBox="0 0 ${n} ${n}">\n <g transform="rotate(${r} ${a} ${a})">\n ${h}\n </g>\n </svg>\n `.replace(/\s+/g," ").trim()).replace(/'/g,"%27").replace(/"/g,"%22")}') ${o.x} ${o.y}, auto`}}class uh{_core;constructor(t){this._core=t}}class ch extends uh{dragStartX=0;dragStartY=0;startX=0;startY=0;endX=0;endY=0;initialDragX=0;initialDragY=0;disconnectedLineIds=new Set;hasMoved=!1;trackedPointerId=null;constructor(t){super(t)}reset(){this.dragStartX=0,this.dragStartY=0,this.startX=0,this.startY=0,this.endX=0,this.endY=0,this.initialDragX=0,this.initialDragY=0,this.disconnectedLineIds.clear(),this.hasMoved=!1,this.trackedPointerId=null}cancelPendingDrag(){this._core.store.state.isDragging=!1,this.reset()}handlePointerDown(t){if("mouse"===t.pointerType)if(yo.isLeftClick(t)){const e=this._core.store.selectionGroup,i=t.shiftKey||t.ctrlKey;if(!e?.isSelected||this._core.store.state.isResizeHandleSelected||this._core.store.state.isRotationHandleSelected||this._core.store.state.isLineHandleSelected||i)this.trackedPointerId=null;else{const e=t.clientX-this._core.store.offsetX,i=t.clientY-this._core.store.offsetY;this._core.store.state.isDragging=!0,this.dragStartX=e,this.dragStartY=i,this.startX=this.dragStartX,this.startY=this.dragStartY,this.initialDragX=e,this.initialDragY=i,this.disconnectedLineIds.clear(),this.trackedPointerId=t.pointerId}}else this.trackedPointerId=null;if("touch"===t.pointerType||"pen"===t.pointerType){const e=Array.from(this._core.store.state.pointers.values());if(1===this._core.store.state.pointers.size){if(this._core.store.state.isScaling)return void(this.trackedPointerId=null);const i=this._core.store.selectionGroup,n=t.shiftKey||t.ctrlKey;if(!i?.isSelected||this._core.store.state.isResizeHandleSelected||this._core.store.state.isRotationHandleSelected||this._core.store.state.isLineHandleSelected||n)this.trackedPointerId=null;else{const i=Math.round(e[0].clientX-this._core.store.offsetX),n=Math.round(e[0].clientY-this._core.store.offsetY);this.dragStartX=i,this.dragStartY=n,this.startX=i,this.startY=n,this.initialDragX=i,this.initialDragY=n,this.disconnectedLineIds.clear(),this.trackedPointerId=t.pointerId}}}}handlePointerMove(t){if(null!==this.trackedPointerId&&this.trackedPointerId===t.pointerId){if("mouse"===t.pointerType){const e=this._core.store.selectionGroup;if(this._core.store.state.isDragging&&e){const i=t.clientX-this._core.store.offsetX,n=t.clientY-this._core.store.offsetY;this.endX=i,this.endY=n;const r=Math.abs(i-this.startX),s=Math.abs(n-this.startY),o=5;(this.hasMoved||r>o||s>o)&&(this.checkAndDisconnectAnchors(i,n),e.move(i,n,this.dragStartX,this.dragStartY),this.dragStartX=i,this.dragStartY=n,this.hasMoved=!0)}}if("touch"===t.pointerType||"pen"===t.pointerType){const t=Array.from(this._core.store.state.pointers.values()),e=this._core.store.selectionGroup;if(1===this._core.store.state.pointers.size&&e&&!this._core.store.state.isResizeHandleSelected&&!this._core.store.state.isRotationHandleSelected&&!this._core.store.state.isScaling){const i=Math.round(t[0].clientX-this._core.store.offsetX),n=Math.round(t[0].clientY-this._core.store.offsetY);this._core.store.state.isDragging=!0,this.endX=i,this.endY=n;const r=Math.abs(i-this.startX),s=Math.abs(n-this.startY),o=5;if(this.hasMoved||r>o||s>o){const t=this._core.store.state.longTouchTimeout;t&&globalThis.clearTimeout?.(t),this.checkAndDisconnectAnchors(i,n),e.move(i,n,this.dragStartX,this.dragStartY),this.dragStartX=i,this.dragStartY=n,this.hasMoved=!0}}}}}handlePointerUp(t){null!==this.trackedPointerId&&this.trackedPointerId===t.pointerId&&("mouse"===t.pointerType&&this._core.store.state.isDragging&&(this._core.store.state.isDragging=!1,this.hasMoved&&(this._core.store.selectionGroup.persistChildren(),this._core.store.selectionGroup.refreshObjectDimensions(void 0,!1),this._core.store.selectionGroup.update(),this._core.engine.emitObjectsChange(),this._core.store.state.hasObjectsChanged=!0,this._core.store.objects.stopUndoCapturing())),"touch"!==t.pointerType&&"pen"!==t.pointerType||this._core.store.state.isDragging&&(this._core.store.state.isDragging=!1,this.hasMoved&&(this._core.store.selectionGroup.persistChildren(),this._core.store.selectionGroup.refreshObjectDimensions(void 0,!1),this._core.store.selectionGroup.update(),this._core.engine.emitObjectsChange(),this._core.store.state.hasObjectsChanged=!0,this._core.store.objects.stopUndoCapturing())),this.reset())}checkAndDisconnectAnchors(t,e){const i=t-this.initialDragX,n=e-this.initialDragY;if(Math.sqrt(i*i+n*n)<30)return;const r=this._core.store.selectionGroup;if(!r)return;const s=r.objects;if(s.every((t=>t instanceof f)))for(const t of s)if(!this.disconnectedLineIds.has(t.id)&&t instanceof f){const e=t;(e.startAnchor||e.endAnchor)&&(e.startAnchor&&this._core.anchorManager.removeAnchor(e.id,"start"),e.endAnchor&&this._core.anchorManager.removeAnchor(e.id,"end"),this.disconnectedLineIds.add(e.id),this._core.store.objects.update(e))}}}var fh;!function(t){t.TopLeft="top-left",t.TopRight="top-right",t.BottomLeft="bottom-left",t.BottomRight="bottom-right"}(fh||(fh={}));class dh extends uh{initialMouseX=0;initialMouseY=0;initialSize={x:0,y:0,width:0,height:0};newSize={x:0,y:0,width:0,height:0};hasResized=!1;constructor(t){super(t)}reset(){this.initialMouseX=0,this.initialMouseY=0,this.initialSize={x:0,y:0,width:0,height:0},this.newSize={x:0,y:0,width:0,height:0},this.hasResized=!1}rebaseResizeBaseline(t,e,i){this.initialMouseX=e,this.initialMouseY=i,this.initialSize.width=t.width,this.initialSize.height=t.height,this.initialSize.x=t.translateX,this.initialSize.y=t.translateY}shouldRebaseResizeBaseline(t){return!0===t.hasExternalAnchoredLineConnections?.()}handlePointerDown(t){if("mouse"===t.pointerType&&yo.isLeftClick(t)){const e=this._core.store.selectionGroup;if(e&&this._core.store.state.isResizeHandleSelected){e.beginTransform();const i=t.clientX-this._core.store.offsetX,n=t.clientY-this._core.store.offsetY;this._core.store.state.isResizing=!0,this.initialMouseX=i,this.initialMouseY=n,this.initialSize.width=e.width,this.initialSize.height=e.height,this.initialSize.x=e.translateX,this.initialSize.y=e.translateY}}if("touch"===t.pointerType||"pen"===t.pointerType){const t=Array.from(this._core.store.state.pointers.values()),e=t[0];if(!e)return;if(1===t.length){const t=this._core.store.selectionGroup;if(t&&this._core.store.state.isResizeHandleSelected){t.beginTransform();const i=Math.round(e.clientX-this._core.store.offsetX),n=Math.round(e.clientY-this._core.store.offsetY);this._core.store.state.isResizing=!0,this.initialMouseX=i,this.initialMouseY=n,this.initialSize.width=t.width,this.initialSize.height=t.height,this.initialSize.x=t.translateX,this.initialSize.y=t.translateY;const r=this._core.store.state.longTouchTimeout;r&&globalThis.clearTimeout?.(r)}}}}handlePointerMove(t){if("mouse"===t.pointerType){const e=this._core.store.selectionGroup;if(this._core.store.state.isResizing&&e){const i=t.clientX-this._core.store.offsetX,n=t.clientY-this._core.store.offsetY,r=i-this.initialMouseX,s=n-this.initialMouseY,o=Math.abs(r),h=Math.abs(s),a=5;if((o>a||h>a)&&(this.hasResized=!0),!this.hasResized)return;const l=e.rotation,u=Math.sin(l),c=Math.cos(l),f=e.scale||1,d=this._core.store.state.scale,p=(r*c+s*u)/d,g=(-r*u+s*c)/d,m=this.initialSize.x+this.initialSize.width/f/2+r/d/2,w=this.initialSize.y+this.initialSize.height/f/2+s/d/2;switch(this._core.store.state.resizeHandleType){case fh.TopLeft:this.newSize.width=this.initialSize.width-p*f,this.newSize.height=this.initialSize.height-g*f;break;case fh.TopRight:this.newSize.width=this.initialSize.width+p*f,this.newSize.height=this.initialSize.height-g*f;break;case fh.BottomLeft:this.newSize.width=this.initialSize.width-p*f,this.newSize.height=this.initialSize.height+g*f;break;case fh.BottomRight:this.newSize.width=this.initialSize.width+p*f,this.newSize.height=this.initialSize.height+g*f}t.shiftKey&&this.constrainToAspectRatio(),this.newSize.x=m-this.newSize.width/f/2,this.newSize.y=w-this.newSize.height/f/2,e.resize(this.newSize.x,this.newSize.y,this.newSize.width,this.newSize.height),this.shouldRebaseResizeBaseline(e)&&this.rebaseResizeBaseline(e,i,n)}}if("touch"===t.pointerType||"pen"===t.pointerType){const t=Array.from(this._core.store.state.pointers.values())[0];if(!t)return;const e=this._core.store.selectionGroup;if(this._core.store.state.isResizing&&e){const i=Math.round(t.clientX-this._core.store.offsetX),n=Math.round(t.clientY-this._core.store.offsetY),r=i-this.initialMouseX,s=n-this.initialMouseY,o=Math.abs(r),h=Math.abs(s),a=5;if(o>a||h>a){const t=this._core.store.state.longTouchTimeout;t&&globalThis.clearTimeout?.(t),this.hasResized=!0}if(!this.hasResized)return;const l=e.rotation,u=Math.sin(l),c=Math.cos(l),f=e.scale||1,d=this._core.store.state.scale,p=(r*c+s*u)/d,g=(-r*u+s*c)/d,m=this.initialSize.x+this.initialSize.width/f/2+r/d/2,w=this.initialSize.y+this.initialSize.height/f/2+s/d/2;switch(this._core.store.state.resizeHandleType){case fh.TopLeft:this.newSize.width=this.initialSize.width-p*f,this.newSize.height=this.initialSize.height-g*f;break;case fh.TopRight:this.newSize.width=this.initialSize.width+p*f,this.newSize.height=this.initialSize.height-g*f;break;case fh.BottomLeft:this.newSize.width=this.initialSize.width-p*f,this.newSize.height=this.initialSize.height+g*f;break;case fh.BottomRight:this.newSize.width=this.initialSize.width+p*f,this.newSize.height=this.initialSize.height+g*f}this.newSize.x=m-this.newSize.width/f/2,this.newSize.y=w-this.newSize.height/f/2,e.resize(this.newSize.x,this.newSize.y,this.newSize.width,this.newSize.height),this.shouldRebaseResizeBaseline(e)&&this.rebaseResizeBaseline(e,i,n)}}}constrainToAspectRatio(){const t=this.initialSize.width,e=this.initialSize.height;if(0===t||0===e)return;const i=t/e,n=this.newSize.height/e;Math.abs(this.newSize.width/t-1)>Math.abs(n-1)?this.newSize.height=this.newSize.width/i:this.newSize.width=this.newSize.height*i}handlePointerUp(t){if("mouse"===t.pointerType&&this._core.store.state.isResizing&&(this._core.store.state.isResizing=!1,this.hasResized&&(this._core.store.selectionGroup.update(),this._core.engine.emitObjectsChange(),this._core.store.state.hasObjectsChanged=!0,this._core.store.objects.stopUndoCapturing()),this.reset()),("touch"===t.pointerType||"pen"===t.pointerType)&&this._core.store.state.isResizing){this._core.store.state.isResizing=!1,this.hasResized&&(this._core.store.selectionGroup.update(),this._core.engine.emitObjectsChange(),this._core.store.state.hasObjectsChanged=!0,this._core.store.objects.stopUndoCapturing()),this.reset();const t=this._core.store.state.longTouchTimeout;t&&globalThis.clearTimeout?.(t)}}}class ph extends uh{initialRotation=0;rotation=0;initialSelectionGroupRotation=0;initialCenterX=0;initialCenterY=0;constructor(t){super(t)}reset(){this.initialRotation=0,this.rotation=0,this.initialCenterX=0,this.initialCenterY=0}handlePointerDown(t){if("mouse"===t.pointerType&&yo.isLeftClick(t)){const e=this._core.store.selectionGroup;if(e&&this._core.store.state.isRotationHandleSelected){e.beginTransform();const i=t.clientX-this._core.store.offsetX,n=t.clientY-this._core.store.offsetY;this._core.store.state.isRotating=!0;const r=e.scale||1,s=e.translateX+e.width/2/r,o=e.translateY+e.height/2/r;this.initialCenterX=s,this.initialCenterY=o;const h=(i-this._core.store.state.translateX)/this._core.store.state.scale,a=(n-this._core.store.state.translateY)/this._core.store.state.scale;this.initialSelectionGroupRotation=e.rotation,this.initialRotation=Math.atan2(o-a,s-h)-e.rotation}}if("touch"===t.pointerType||"pen"===t.pointerType){const t=Array.from(this._core.store.state.pointers.values()),e=t[0];if(!e)return;if(1===t.length){const t=this._core.store.selectionGroup;if(t&&this._core.store.state.isRotationHandleSelected){t.beginTransform();const i=Math.round(e.clientX-this._core.store.offsetX),n=Math.round(e.clientY-this._core.store.offsetY);this._core.store.state.isRotating=!0;const r=t.scale||1,s=t.translateX+t.width/2/r,o=t.translateY+t.height/2/r;this.initialCenterX=s,this.initialCenterY=o;const h=(i-this._core.store.state.translateX)/this._core.store.state.scale,a=(n-this._core.store.state.translateY)/this._core.store.state.scale;this.initialSelectionGroupRotation=t.rotation,this.initialRotation=Math.atan2(o-a,s-h)-t.rotation;const l=this._core.store.state.longTouchTimeout;l&&globalThis.clearTimeout?.(l)}}}}handlePointerMove(t){if("mouse"===t.pointerType){const e=this._core.store.selectionGroup;if(this._core.store.state.isRotating&&e){const i=Math.atan2(this.initialCenterY-(t.clientY-this._core.store.offsetY-this._core.store.state.translateY)/this._core.store.state.scale,this.initialCenterX-(t.clientX-this._core.store.offsetX-this._core.store.state.translateX)/this._core.store.state.scale);this.rotation=i-this.initialRotation,e.rotate(this.rotation)}}if("touch"===t.pointerType||"pen"===t.pointerType){const t=Array.from(this._core.store.state.pointers.values())[0];if(!t)return;const e=this._core.store.selectionGroup;if(this._core.store.state.isRotating&&e){const i=Math.round(t.clientX-this._core.store.offsetX),n=Math.round(t.clientY-this._core.store.offsetY),r=Math.atan2(this.initialCenterY-(n-this._core.store.state.translateY)/this._core.store.state.scale,this.initialCenterX-(i-this._core.store.state.translateX)/this._core.store.state.scale);this.rotation=r-this.initialRotation,e.rotate(this.rotation);const s=this._core.store.state.longTouchTimeout;s&&globalThis.clearTimeout?.(s)}}}handlePointerUp(t){if("mouse"===t.pointerType&&this._core.store.state.isRotating&&(this._core.store.selectionGroup.update(),this._core.engine.emitObjectsChange(),this._core.store.state.isRotating=!1,this._core.store.state.hasObjectsChanged=!0,this._core.store.objects.stopUndoCapturing(),this.reset()),("touch"===t.pointerType||"pen"===t.pointerType)&&this._core.store.state.isRotating){this._core.store.selectionGroup.update(),this._core.engine.emitObjectsChange(),this._core.store.state.isRotating=!1,this._core.store.state.hasObjectsChanged=!0,this._core.store.objects.stopUndoCapturing(),this.reset();const t=this._core.store.state.longTouchTimeout;t&&globalThis.clearTimeout?.(t)}}}class gh extends a{__class__="KritzelSelectionBox";static create(t){const e=new gh;return e._core=t,e.id=e.generateId(),e.workspaceId=t.store.state.activeWorkspace.id,e.userId=t.user?.id,e.scale=t.store.state.scale,e.zIndex=99999,e.backgroundColor={light:"var(--kritzel-selection-box-background-color)",dark:"var(--kritzel-selection-box-background-color)"},e.borderColor={light:"var(--kritzel-selection-box-border-color)",dark:"var(--kritzel-selection-box-border-color)"},e.borderWidth=2,e.height=0,e.width=0,e}}class mh extends uh{startX=0;startY=0;touchStartX=0;touchStartY=0;touchStartTimeout=null;_previouslySelectedObjects=new Set;get isSelectionClick(){const t=this._core.store.selectionBox;return t&&0===t.width&&0===t.height}get isSelectionDrag(){const t=this._core.store.selectionBox;return t&&(t.width>0||t.height>0)}constructor(t){super(t)}handlePointerDown(t){if(this._core.store.state.isResizeHandleSelected||this._core.store.state.isRotationHandleSelected)return;const e=t.shiftKey||t.ctrlKey;"mouse"===t.pointerType&&(!yo.isLeftClick(t)||this._core.store.selectionGroup&&!e||this.startMouseSelection(t,e)),"touch"!==t.pointerType&&"pen"!==t.pointerType||(this.touchStartTimeout=setTimeout((()=>{1!==this._core.store.state.pointers.size||this._core.store.state.isScaling||this._core.store.selectionGroup&&!e||(this.startTouchSelection(t,e),this.updateTouchSelection())}),80))}handlePointerMove(t){if("mouse"===t.pointerType&&this._core.store.state.isSelecting&&this.updateMouseSelection(t),"touch"===t.pointerType||"pen"===t.pointerType){const t=Array.from(this._core.store.state.pointers.values()),e=Math.round(t[0].clientX-this._core.store.offsetX),i=Math.round(t[0].clientY-this._core.store.offsetY),n=Math.abs(e-this.touchStartX),r=Math.abs(i-this.touchStartY),s=5;if((n>s||r>s)&&this._core.store.state.isSelecting){this.updateTouchSelection();const t=this._core.store.state.longTouchTimeout;t&&globalThis.clearTimeout?.(t)}}}handlePointerUp(t){if("mouse"===t.pointerType&&yo.isLeftClick(t)){const e=this._core.store.state.hasObjectsChanged,i=this._core.store.selectionGroup,n=t.shiftKey||t.ctrlKey;if(1!==i?.objects.length||!1!==e||n||i.objects[0].edit(t),this._core.store.state.hasObjectsChanged=!1,this._core.store.state.isSelecting){if(this.isSelectionClick&&this.handleSelectionClick(t),this.isSelectionDrag){const e=t.shiftKey||t.ctrlKey;this.updateMouseSelection(t),this.addSelectedObjectsToSelectionGroup(e),this.removeSelectionBox()}this._core.engine.emitObjectsChange()}}if("touch"===t.pointerType||"pen"===t.pointerType){clearTimeout(this.touchStartTimeout);const e=this._core.store.state.hasObjectsChanged,i=this._core.store.selectionGroup,n=t.shiftKey||t.ctrlKey;if(1!==i?.objects.length||!1!==e||n||i.objects[0].edit(t),this._core.store.state.hasObjectsChanged=!1,this._core.store.state.isSelecting){if(this.isSelectionClick&&this.handleSelectionClick(t),this.isSelectionDrag){const e=t.shiftKey||t.ctrlKey;this.updateTouchSelection(),this.addSelectedObjectsToSelectionGroup(e),this.removeSelectionBox()}this._core.engine.emitObjectsChange(),this._core.store.state.skipContextMenu=!1}}}removeSelectionBox(){this._core.store.state.isSelecting=!1,this._core.store.objects.remove((t=>t instanceof gh)),this._core.store.setSelectionBox(null),this._core.store.objects.clearLocalSelectionBox()}startMouseSelection(t,e=!1){let i,n;i=t.clientX-this._core.store.offsetX,n=t.clientY-this._core.store.offsetY;const r=gh.create(this._core);this.startX=(i-this._core.store.state.translateX)/this._core.store.state.scale,this.startY=(n-this._core.store.state.translateY)/this._core.store.state.scale,r.translateX=this.startX,r.translateY=this.startY,this._core.store.state.isSelecting=!0,this._core.removeSelectionBox(),e||this._core.removeSelectionGroup(),this._core.store.objects.insert(r),this._core.store.setSelectionBox(r)}startTouchSelection(t,e=!1){const i=Array.from(this._core.store.state.pointers.values())[0];if(!i)return;let n,r;n=Math.round(i.clientX-this._core.store.offsetX),r=Math.round(i.clientY-this._core.store.offsetY),this.touchStartX=n,this.touchStartY=r;const s=gh.create(this._core);this.startX=(n-this._core.store.state.translateX)/this._core.store.state.scale,this.startY=(r-this._core.store.state.translateY)/this._core.store.state.scale,s.translateX=this.startX,s.translateY=this.startY,this._core.store.state.isSelecting=!0,this._core.removeSelectionBox(),e||this._core.removeSelectionGroup(),this._core.store.objects.insert(s),this._core.store.setSelectionBox(s)}updateMouseSelection(t){let e,i;e=t.clientX-this._core.store.offsetX,i=t.clientY-this._core.store.offsetY;const n=this._core.store.selectionBox;if(n){const t=(e-this._core.store.state.translateX)/n.scale,r=(i-this._core.store.state.translateY)/n.scale,s=Math.abs(t-this.startX)*n.scale,o=Math.abs(r-this.startY)*n.scale;n.width=s,n.height=o,n.translateX=Math.min(t,this.startX),n.translateY=Math.min(r,this.startY),this._core.store.objects.setLocalSelectionBox({x:n.translateX,y:n.translateY,width:s/n.scale,height:o/n.scale}),s>0||o>0?this.updateSelectedObjects():this.clearSelectionPreview()}}updateTouchSelection(){const t=Array.from(this._core.store.state.pointers.values())[0];if(!t)return;let e,i;e=Math.round(t.clientX-this._core.store.offsetX),i=Math.round(t.clientY-this._core.store.offsetY);const n=this._core.store.selectionBox;if(n){const t=(e-this._core.store.state.translateX)/n.scale,r=(i-this._core.store.state.translateY)/n.scale,s=Math.abs(t-this.startX)*n.scale,o=Math.abs(r-this.startY)*n.scale;n.width=s,n.height=o,n.translateX=Math.min(t,this.startX),n.translateY=Math.min(r,this.startY),this._core.store.objects.setLocalSelectionBox({x:n.translateX,y:n.translateY,width:s/n.scale,height:o/n.scale}),s>0||o>0?this.updateSelectedObjects():this.clearSelectionPreview()}}updateSelectedObjects(){const t=this._core.store.selectionBox;if(!t)return;const e=t.rotatedPolygon,i=[e.topLeft.x,e.topRight.x,e.bottomRight.x,e.bottomLeft.x],n=[e.topLeft.y,e.topRight.y,e.bottomRight.y,e.bottomLeft.y],r=Math.min(...i),s=Math.max(...i),o=Math.min(...n),h=Math.max(...n),a=this._core.store.objects.query({x:r,y:o,z:t.scale,width:s-r,height:h-o}),l=new Set;for(const t of a){if(t instanceof gh||t instanceof So)continue;const i=t.hitTestPolygon(e);t.isSelected=i,i&&l.add(t)}for(const t of this._previouslySelectedObjects)l.has(t)||(t.isSelected=!1);this._previouslySelectedObjects=l}handleSelectionClick(t){const e=this.getTopmostHitObject(t),i=t.shiftKey||t.ctrlKey;this.clearSelectionPreview(),e&&this.addObjectToSelectionGroup(e,i),this.removeSelectionBox()}getTopmostHitObject(t){const e=this._core.store.state.pointerX,i=this._core.store.state.pointerY,n=this._core.getObjectsFromPointerEvent(t,".object");for(const t of n)if(!(t instanceof gh||t instanceof So)&&t.hitTest(e,i))return t;return null}clearSelectionPreview(){const t=new Set(this._core.store.selectionGroup?.objectIds??[]);for(const e of this._previouslySelectedObjects)t.has(e.id)||(e.isSelected=!1);this._previouslySelectedObjects.clear()}addObjectToSelectionGroup(t,e=!1){if(!t)return;const i=co.findParentGroup(this._core,t.id),n=i||t;i&&(t.isSelected=!1);const r=this._core.store.selectionGroup;if(e&&r)r.addOrRemove(n),this.removeDescendantsOfSelectedGroups(r),0===r.objects.length?this._core.removeSelectionGroup():this._core.rerender();else{const t=So.create(this._core);t.addOrRemove(n),t.isSelected=!0,this._core.addSelectionGroup(t),this._core.rerender()}}addSelectedObjectsToSelectionGroup(t=!1){const e=this._core.store.selectedObjects;if(0===e.length)return;const i=this._core.store.objects.filter((t=>"KritzelGroup"===t.__class__)),n=new Map;for(const t of i)for(const e of t.childIds)n.set(e,t);const r=new Map;for(const t of e){const e=n.get(t.id);e?(t.isSelected=!1,r.set(e.id,e)):r.set(t.id,t)}const s=Array.from(r.values()),o=this.filterDescendantsOfSelectedGroups(s),h=this._core.store.selectionGroup;if(t&&h)h.addObjects(o),this.removeDescendantsOfSelectedGroups(h),this._previouslySelectedObjects.clear(),this._core.rerender();else{const t=So.create(this._core);t.objectIds=o.map((t=>t.id)),o.forEach((t=>{t.isSelected=!0})),1===t.length&&(t.rotation=t.objects[0].rotation),t.captureUnchangedSnapshots(),t.refreshObjectDimensions(),t.isSelected=!0,this._core.addSelectionGroup(t),this._previouslySelectedObjects.clear(),this._core.rerender()}}filterDescendantsOfSelectedGroups(t){const e=new Set;for(const i of t)i instanceof co&&co.collectDescendantIds(i,e);return 0===e.size?t:t.filter((t=>!e.has(t.id)))}removeDescendantsOfSelectedGroups(t){const e=this.filterDescendantsOfSelectedGroups(t.objects);e.length!==t.objects.length&&(t.objectIds=e.map((t=>t.id)))}}class wh extends uh{constructor(t){super(t)}handlePointerMove(t){if("mouse"===t.pointerType){const e=this._core.getObjectFromPointerEvent(t,".object");if(!e)return;e.isHovered=e.hitTest(this._core.store.state.pointerX,this._core.store.state.pointerY)}}}class vh extends uh{initialMouseX=0;initialMouseY=0;initialStartX=0;initialStartY=0;initialEndX=0;initialEndY=0;initialControlX;initialControlY;initialTranslateX=0;initialTranslateY=0;hasMoved=!1;currentSnapTarget=null;constructor(t){super(t)}reset(){this.initialMouseX=0,this.initialMouseY=0,this.initialStartX=0,this.initialStartY=0,this.initialEndX=0,this.initialEndY=0,this.initialControlX=void 0,this.initialControlY=void 0,this.initialTranslateX=0,this.initialTranslateY=0,this.hasMoved=!1,this.currentSnapTarget=null,this._core.anchorManager.clearSnapCandidate(),this._core.anchorManager.clearSnapPreviewCandidate()}handlePointerDown(t){"mouse"===t.pointerType&&yo.isLeftClick(t)&&this.startHandleDrag(t),("touch"===t.pointerType||"pen"===t.pointerType)&&1===Array.from(this._core.store.state.pointers.values()).length&&this.startHandleDrag(t)}startHandleDrag(t){const e=this.getSelectedLine();if(!e||!this._core.store.state.isLineHandleSelected)return;const i=t.clientX-this._core.store.offsetX,n=t.clientY-this._core.store.offsetY;this._core.store.state.isLineHandleDragging=!0,this.initialMouseX=i,this.initialMouseY=n,this.initialStartX=e.startX,this.initialStartY=e.startY,this.initialEndX=e.endX,this.initialEndY=e.endY,this.initialControlX=e.controlX,this.initialControlY=e.controlY,this.initialTranslateX=e.translateX,this.initialTranslateY=e.translateY;const r=this._core.store.state.lineHandleType;"start"!==r&&"end"!==r||this._core.anchorManager.removeAnchor(e.id,r);const s=this._core.store.state.longTouchTimeout;s&&globalThis.clearTimeout?.(s)}handlePointerMove(t){const e=this.getSelectedLine();if(!e||!this._core.store.state.isLineHandleDragging)return;const i=t.clientX-this._core.store.offsetX,n=t.clientY-this._core.store.offsetY,r=i-this.initialMouseX,s=n-this.initialMouseY;if((Math.abs(r)>3||Math.abs(s)>3)&&(this.hasMoved=!0),!this.hasMoved)return;const o=this._core.store.state.scale,h=e.scale||1,a=e.rotation,l=r/o,u=s/o,c=Math.cos(-a),f=Math.sin(-a),d=(l*c-u*f)*h,p=(l*f+u*c)*h,g=this._core.store.state.lineHandleType;if("start"===g){const r=(i-this._core.store.state.translateX)/o,s=(n-this._core.store.state.translateY)/o,h=e.endAnchor?.objectId,a=this._core.anchorManager.findSnapPreviewTarget(r,s,e.id,h),l=this._core.anchorManager.findSnapTarget(r,s,e.id,h,t.pointerType);this.currentSnapTarget=l;const u=this.lineLocalToWorld(e,this.initialEndX,this.initialEndY);let c;if(void 0!==e.controlX&&void 0!==e.controlY&&(c=this.lineLocalToWorld(e,e.controlX,e.controlY)),l){const t=this.worldToLineLocal(e,l.centerX,l.centerY);this.updateLineEndpoint(e,t.x,t.y,this.initialEndX,this.initialEndY);const i=this._core.store.allNonSelectionObjects.find((t=>t.id===l.objectId));let n,r,s;if(i){const t=this._core.anchorManager.computeAnchorClipInfo(e,"start",i);t&&(n=t.worldX,r=t.worldY,s=t.t)}this._core.anchorManager.setSnapPreviewCandidate(null),this._core.anchorManager.setSnapCandidate(this.createIndicatorCandidate(e,"start",l,u,c,{edgeX:n,edgeY:r,t:s}))}else a?(this.updateLineEndpoint(e,this.initialStartX+d,this.initialStartY+p,this.initialEndX,this.initialEndY),this._core.anchorManager.clearSnapCandidate(),this._core.anchorManager.setSnapPreviewCandidate(this.createIndicatorCandidate(e,"start",a,u,c))):(this.updateLineEndpoint(e,this.initialStartX+d,this.initialStartY+p,this.initialEndX,this.initialEndY),this._core.anchorManager.clearSnapCandidate(),this._core.anchorManager.clearSnapPreviewCandidate())}else if("end"===g){const r=(i-this._core.store.state.translateX)/o,s=(n-this._core.store.state.translateY)/o,h=e.startAnchor?.objectId,a=this._core.anchorManager.findSnapPreviewTarget(r,s,e.id,h),l=this._core.anchorManager.findSnapTarget(r,s,e.id,h,t.pointerType);this.currentSnapTarget=l;const u=this.lineLocalToWorld(e,this.initialStartX,this.initialStartY);let c;if(void 0!==e.controlX&&void 0!==e.controlY&&(c=this.lineLocalToWorld(e,e.controlX,e.controlY)),l){const t=this.worldToLineLocal(e,l.centerX,l.centerY);this.updateLineEndpoint(e,this.initialStartX,this.initialStartY,t.x,t.y);const i=this._core.store.allNonSelectionObjects.find((t=>t.id===l.objectId));let n,r,s;if(i){const t=this._core.anchorManager.computeAnchorClipInfo(e,"end",i);t&&(n=t.worldX,r=t.worldY,s=t.t)}this._core.anchorManager.setSnapPreviewCandidate(null),this._core.anchorManager.setSnapCandidate(this.createIndicatorCandidate(e,"end",l,u,c,{edgeX:n,edgeY:r,t:s}))}else a?(this.updateLineEndpoint(e,this.initialStartX,this.initialStartY,this.initialEndX+d,this.initialEndY+p),this._core.anchorManager.clearSnapCandidate(),this._core.anchorManager.setSnapPreviewCandidate(this.createIndicatorCandidate(e,"end",a,u,c))):(this.updateLineEndpoint(e,this.initialStartX,this.initialStartY,this.initialEndX+d,this.initialEndY+p),this._core.anchorManager.clearSnapCandidate(),this._core.anchorManager.clearSnapPreviewCandidate())}else if("center"===g){this._core.anchorManager.clearSnapPreviewCandidate(),this._core.anchorManager.clearSnapCandidate();const t=(this.initialControlX??(this.initialStartX+this.initialEndX)/2)+2*d,i=(this.initialControlY??(this.initialStartY+this.initialEndY)/2)+2*p,n=e.startX,r=e.startY,s=e.endX,o=e.endY,h=s-n,a=o-r,l=h*h+a*a;let u,c,f=-1;0!==l&&(f=((t-n)*h+(i-r)*a)/l),f<0?(u=n,c=r):f>1?(u=s,c=o):(u=n+f*h,c=r+f*a);const g=t-u,m=i-c;Math.sqrt(g*g+m*m)<15?e.updateControlPoint(void 0,void 0):e.updateControlPoint(t,i)}this._core.rerender()}worldToLineLocal(t,e,i){const n=(e-t.translateX)*t.scale,r=(i-t.translateY)*t.scale,s=t.totalWidth/2,o=t.totalHeight/2,h=Math.cos(-t.rotation),a=Math.sin(-t.rotation);return{x:(n-s)*h-(r-o)*a+s+t.x,y:(n-s)*a+(r-o)*h+o+t.y}}lineLocalToWorld(t,e,i){const n=e-t.x,r=i-t.y,s=t.totalWidth/2,o=t.totalHeight/2,h=Math.cos(t.rotation),a=Math.sin(t.rotation);return{x:((n-s)*h-(r-o)*a+s)/t.scale+t.translateX,y:((n-s)*a+(r-o)*h+o)/t.scale+t.translateY}}updateLineEndpoint(t,e,i,n,r){const{minX:s,minY:o,maxX:h,maxY:a}=f.calculateBoundingBox(e,i,n,r,t.controlX,t.controlY,t.strokeWidth),l=h-s,u=a-o,{minX:c,minY:d,maxX:p,maxY:g}=f.calculateBoundingBox(this.initialStartX,this.initialStartY,this.initialEndX,this.initialEndY,this.initialControlX,this.initialControlY,t.strokeWidth),m=p-c,w=g-d,v=s-c+(l-m)/2,y=o-d+(u-w)/2,b=t.rotation,k=Math.cos(b),M=Math.sin(b),S=1/t.scale,x=this.initialTranslateX+S*(m-l)/2+S*(v*k-y*M),A=this.initialTranslateY+S*(w-u)/2+S*(v*M+y*k);t.startX=e,t.startY=i,t.endX=n,t.endY=r,t.x=s,t.y=o,t.width=l,t.height=u,t.translateX=x,t.translateY=A;const $=t;$._adjustedPoints=null,$._clipInfo=null,this._core.store.objects.update(t)}handlePointerUp(t){if(this._core.store.state.isLineHandleDragging){const t=this.getSelectedLine(),e=this._core.store.state.lineHandleType;if(t&&this.hasMoved){!this.currentSnapTarget||"start"!==e&&"end"!==e||this._core.anchorManager.setAnchor(t.id,e,this.currentSnapTarget.objectId);const i=this._core.store.selectionGroup;i&&(i.refreshObjectDimensions(),i.update(),this._core.engine.emitObjectsChange(),this._core.store.state.hasObjectsChanged=!0),this._core.store.objects.stopUndoCapturing()}this._core.store.state.isLineHandleDragging=!1,this.reset(),this._core.rerender()}}getSelectedLine(){const t=this._core.store.selectionGroup;if(!t||1!==t.objects.length)return null;const e=t.objects[0];return e instanceof f?e:null}createIndicatorCandidate(t,e,i,n,r,s){return{objectId:i.objectId,endpoint:e,centerX:i.centerX,centerY:i.centerY,lineEndpointX:n.x,lineEndpointY:n.y,controlX:r?.x,controlY:r?.y,t:s?.t,edgeX:s?.edgeX,edgeY:s?.edgeY,lineStroke:g.resolveThemeColor(t.stroke),lineStrokeWidth:t.strokeWidth/t.scale,arrowOffset:"start"===e?t.hasStartArrow?t.getArrowSize("start")/t.scale:void 0:t.hasEndArrow?t.getArrowSize("end")/t.scale:void 0,arrowStyle:"start"===e?t.arrows?.start?.style:t.arrows?.end?.style,arrowFill:t.getArrowFill("start"===e?"start":"end")}}}class yh extends vo{toolType="selection";selectionHandler;moveHandler;hoverHandler;resizeHandler;rotationHandler;lineHandleHandler;palette=[...m];_savedSelectionGroupForPinch=null;hasSelection(){return!!this._core.store.selectionGroup&&this._core.store.selectionGroup.objects.length>0}getSelectedObjects(){return this._core.store.selectionGroup?.objects??[]}flattenObjects(t){let e=[];for(const i of t)uo.isInstanceOf(i,"KritzelGroup")?e=e.concat(this.flattenObjects(i.children)):e.push(i);return e}get color(){const t=this.flattenObjects(this.getSelectedObjects());if(0===t.length)return m[0];for(const e of t){if(e instanceof c)return e.fill;if(e instanceof f)return e.stroke;if(e instanceof no)return e.fontColor;if(e instanceof po)return e.strokeColor}return m[0]}set color(t){this.flattenObjects(this.getSelectedObjects()).forEach((e=>{e instanceof c&&this._core.updateObject(e,{fill:t}),e instanceof f&&this._core.updateObject(e,{stroke:t}),e instanceof no&&this._core.updateObject(e,{fontColor:t}),e instanceof po&&this._core.updateObject(e,{strokeColor:t})})),this._core.rerender()}get opacity(){const t=this.flattenObjects(this.getSelectedObjects());return 0===t.length?1:t[0].opacity}set opacity(t){this.flattenObjects(this.getSelectedObjects()).forEach((e=>this._core.updateObject(e,{opacity:t}))),this._core.rerender()}get size(){const t=this.flattenObjects(this.getSelectedObjects());if(0===t.length)return 1;for(const e of t){if(e instanceof c)return e.strokeWidth;if(e instanceof f)return e.strokeWidth;if(e instanceof no)return e.fontSize;if(e instanceof po)return e.strokeWidth}return 1}set size(t){this.flattenObjects(this.getSelectedObjects()).forEach((e=>{e instanceof c&&this._core.updateObject(e,{strokeWidth:t}),e instanceof f&&this._core.updateObject(e,{strokeWidth:t}),e instanceof no&&this._core.updateObject(e,{fontSize:t}),e instanceof po&&this._core.updateObject(e,{strokeWidth:t})})),this._core.rerender(),this.refreshSelectionGroupDimensions()}get fillColor(){const t=this.flattenObjects(this.getSelectedObjects());for(const e of t)if(e instanceof po)return e.fillColor;return{light:"transparent",dark:"transparent"}}set fillColor(t){this.flattenObjects(this.getSelectedObjects()).forEach((e=>{if(e instanceof po){const i=g.determineTextColor(t);this._core.updateObject(e,{fillColor:t,fontColor:i}),("string"==typeof t?"transparent"===t:"transparent"===t.light&&"transparent"===t.dark)||this._core.updateObject(e,{strokeColor:t})}})),this._core.rerender()}get fontFamily(){const t=this.flattenObjects(this.getSelectedObjects());for(const e of t){if(e instanceof no)return e.fontFamily;if(e instanceof po)return e.fontFamily}return"Arial"}set fontFamily(t){this.flattenObjects(this.getSelectedObjects()).forEach((e=>{e instanceof no&&this._core.updateObject(e,{fontFamily:t}),e instanceof po&&this._core.updateObject(e,{fontFamily:t})})),this._core.rerender(),this.refreshSelectionGroupDimensions()}get arrows(){const t=this.flattenObjects(this.getSelectedObjects());for(const e of t)if(e instanceof f)return e.arrows??{start:{enabled:!1},end:{enabled:!1}};return{start:{enabled:!1},end:{enabled:!1}}}set arrows(t){this.flattenObjects(this.getSelectedObjects()).forEach((e=>{e instanceof f&&this._core.updateObject(e,{arrows:t})})),this._core.rerender(),this.refreshSelectionGroupDimensions()}getToolConfig(){if(!this.hasSelection())return null;const t=this.flattenObjects(this.getSelectedObjects()),e=[],i=t.some((t=>t instanceof po)),n=t.some((t=>t instanceof no)),r=t.some((t=>t instanceof f)),s=t.some((t=>t instanceof lo)),o=t.some((t=>t instanceof c||t instanceof f||t instanceof po));return!s||i||n||r||o?(n&&!o?(e.push({type:"font-size",propertyName:"size"}),e.push({type:"font-family",propertyName:"fontFamily"})):o&&!n?e.push({type:"stroke-size",propertyName:"size"}):(o&&e.push({type:"stroke-size",propertyName:"size"}),n&&e.push({type:"font-family",propertyName:"fontFamily"})),r&&e.push({type:"line-endings",propertyName:"arrows"}),i&&e.push({type:"shape-fill",propertyName:"fillColor"}),{type:"selection",colorProperty:"color",sizeProperty:"size",opacityProperty:"opacity",paletteSource:"palette",sizesSource:"none",controls:e}):{type:"selection",colorProperty:"color",sizeProperty:"size",opacityProperty:"opacity",paletteSource:"none",sizesSource:"none",controls:[]}}refreshSelectionGroupDimensions(){const t=this._core.store.selectionGroup;t&&requestAnimationFrame((()=>{requestAnimationFrame((()=>{t.refreshObjectDimensions(),this._core.rerender()}))}))}constructor(t){super(t),this.selectionHandler=new mh(this._core),this.moveHandler=new ch(this._core),this.hoverHandler=new wh(this._core),this.resizeHandler=new dh(this._core),this.rotationHandler=new ph(this._core),this.lineHandleHandler=new vh(this._core)}handlePointerDown(t){if(t.cancelable&&t.preventDefault(),"mouse"===t.pointerType){if(yo.isLeftClick(t)){this._core.store.state.isResizeHandleSelected=this.isHandleSelected(t),this._core.store.state.isRotationHandleSelected=this.isRotationHandleSelected(t),this._core.store.state.isLineHandleSelected=this.isLineHandleSelected(t),this._core.store.state.resizeHandleType=this.getHandleType(t),this._core.store.state.lineHandleType=this.getLineHandleType(t);const e=this.getSelectedObject(t),i=this._core.store.selectionGroup;if(null!==e&&!(e&&i&&e.id!==i.id)||!i||this._core.store.state.isResizeHandleSelected||this._core.store.state.isRotationHandleSelected||this._core.store.state.isLineHandleSelected||t.shiftKey||t.ctrlKey||(this._core.removeSelectionGroup(),this._core.rerender()),e&&!1===e.isSelected&&1===e?.objects.length){const t=e.objects[0];if(uo.isInstanceOf(t,"KritzelCustomElement")){if(t.isSelected&&1===this._core.store.selectionGroup?.objects.length)return}else if(t.isInteractive)return}}this.lineHandleHandler.handlePointerDown(t),this.moveHandler.handlePointerDown(t),this.selectionHandler.handlePointerDown(t),this.resizeHandler.handlePointerDown(t),this.rotationHandler.handlePointerDown(t),this._core.rerender()}if("touch"===t.pointerType||"pen"===t.pointerType){if(!0===this._core.store.state.isScaling&&(1===this._core.store.state.pointers.size&&(this._core.store.state.isScaling=!1,this._savedSelectionGroupForPinch=null),this._savedSelectionGroupForPinch&&!this._core.store.selectionGroup&&(this._core.addSelectionGroup(this._savedSelectionGroupForPinch),this._savedSelectionGroupForPinch=null,this._core.rerender()),!0===this._core.store.state.isScaling))return;if(1===this._core.store.state.pointers.size){this._core.store.state.isResizeHandleSelected=this.isHandleSelected(t),this._core.store.state.isRotationHandleSelected=this.isRotationHandleSelected(t),this._core.store.state.isLineHandleSelected=this.isLineHandleSelected(t),this._core.store.state.resizeHandleType=this.getHandleType(t),this._core.store.state.lineHandleType=this.getLineHandleType(t);const e=this.getSelectedObject(t),i=this._core.store.selectionGroup,n=e&&i&&e.id!==i.id,r=t.shiftKey||t.ctrlKey;!i&&e&&(this._core.store.state.skipContextMenu=!0),null!==e&&!n||!i||this._core.store.state.isResizeHandleSelected||this._core.store.state.isRotationHandleSelected||this._core.store.state.isLineHandleSelected||r||(this._savedSelectionGroupForPinch=i,this._core.removeSelectionGroup(),this._core.rerender())}this.lineHandleHandler.handlePointerDown(t),this.rotationHandler.handlePointerDown(t),this.resizeHandler.handlePointerDown(t),this.moveHandler.handlePointerDown(t),1===this._core.store.state.pointers.size&&this.selectionHandler.handlePointerDown(t),this._core.rerender()}}handlePointerMove(t){if(t.cancelable&&t.preventDefault(),"mouse"===t.pointerType&&(this.lineHandleHandler.handlePointerMove(t),this.moveHandler.handlePointerMove(t),this.hoverHandler.handlePointerMove(t),this.selectionHandler.handlePointerMove(t),this.resizeHandler.handlePointerMove(t),this.rotationHandler.handlePointerMove(t),this._core.rerender()),"touch"===t.pointerType||"pen"===t.pointerType){if(!0===this._core.store.state.isScaling)return;this.lineHandleHandler.handlePointerMove(t),this.rotationHandler.handlePointerMove(t),this.resizeHandler.handlePointerMove(t),this.moveHandler.handlePointerMove(t),this.selectionHandler.handlePointerMove(t),this._core.rerender()}}handlePointerUp(t){if(t.cancelable&&t.preventDefault(),"mouse"===t.pointerType&&(this.lineHandleHandler.handlePointerUp(t),this.moveHandler.handlePointerUp(t),this.resizeHandler.handlePointerUp(t),this.rotationHandler.handlePointerUp(t),this.selectionHandler.handlePointerUp(t),this._core.rerender()),"touch"===t.pointerType||"pen"===t.pointerType){if(!0===this._core.store.state.isScaling)return;this._savedSelectionGroupForPinch=null,this.lineHandleHandler.handlePointerUp(t),this.rotationHandler.handlePointerUp(t),this.resizeHandler.handlePointerUp(t),this.moveHandler.handlePointerUp(t),this.selectionHandler.handlePointerUp(t),this._core.rerender()}}getSelectedObject(t){const e=t.composedPath().find((t=>t.classList&&t.classList.contains("object"))),i=e?.id?this._core.findObjectById(e.id):null;if(!i)return null;const{x:n,y:r}=this._core.getCanvasPoint(t);if(!i.hitTest(n,r))return null;const s=this._core.store.selectionGroup;if(s?.objects.some((t=>t.id===i.id)))return s;if(i instanceof So)return i;{const t=So.create(this._core);return t.translateX=0,t.translateY=0,t.objectIds=[i.id],t}}getHandleType(t){const e=this._core.store.state.host?.shadowRoot;if(!e)return;const i=e.elementsFromPoint(t.clientX,t.clientY).find((t=>t.classList.contains("resize-handle-overlay")));return i?.classList[1]}isHandleSelected(t){const e=this._core.store.state.host?.shadowRoot;return!!e&&e.elementsFromPoint(t.clientX,t.clientY).some((t=>t.classList.contains("resize-handle-overlay")))}isRotationHandleSelected(t){const e=this._core.store.state.host?.shadowRoot;return!!e&&e.elementsFromPoint(t.clientX,t.clientY).some((t=>t.classList.contains("rotation-handle-overlay")))}isLineHandleSelected(t){const e=this._core.store.state.host?.shadowRoot;return!!e&&e.elementsFromPoint(t.clientX,t.clientY).some((t=>t.classList.contains("selection-line-handle-overlay")))}getLineHandleType(t){const e=this._core.store.state.host?.shadowRoot;if(!e)return;const i=e.elementsFromPoint(t.clientX,t.clientY).find((t=>t.classList.contains("selection-line-handle-overlay")));return i?.classList[1]}}class bh{_core;_anchorIndex=new Map;constructor(t){this._core=t}setAnchor(t,e,i){const n=this.getLineById(t);if(!n)return;if("start"===e&&n.endAnchor?.objectId===i)return;if("end"===e&&n.startAnchor?.objectId===i)return;this.removeAnchor(t,e);const r={objectId:i};"start"===e?n.startAnchor=r:n.endAnchor=r,this.addToIndex(i,t,e),this.snapEndpointToObject(n,e,i),this._core.store.objects.update(n)}removeAnchor(t,e){const i=this.getLineById(t);if(!i)return;const n="start"===e?i.startAnchor:i.endAnchor;n&&(this.removeFromIndex(n.objectId,t,e),"start"===e?i.startAnchor=void 0:i.endAnchor=void 0)}getAnchor(t,e){const i=this.getLineById(t);return i?("start"===e?i.startAnchor:i.endAnchor)??null:null}getLinesAnchoredTo(t){const e=this._anchorIndex.get(t);return e?Array.from(e):[]}updateAnchorsForObject(t){const e=this.getLinesAnchoredTo(t);if(0===e.length)return;if(!this.getObjectById(t))return;for(const i of e){const e=this.getLineById(i.lineId);e&&this.snapEndpointToObject(e,i.endpoint,t)}const i=this._core.store.selectionGroup;i&&this._core.store.state.isDragging&&i.hasExternalAnchoredLineConnections()&&i.refreshObjectDimensions(void 0,!0)}snapEndpointToObject(t,e,i){const n=this.getObjectById(i);if(!n)return;const r=this.worldToLineLocal(t,n.centerX,n.centerY);t.updateEndpoint(e,r.x,r.y)}worldToLineLocal(t,e,i){const n=e-t.centerX,r=i-t.centerY,s=Math.cos(-t.rotation),o=Math.sin(-t.rotation);return{x:(n*s-r*o+t.totalWidth/2/t.scale)*t.scale+t.x,y:(n*o+r*s+t.totalHeight/2/t.scale)*t.scale+t.y}}findSnapTarget(t,e,i,n,r="mouse"){return this.findBestSnapTarget(t,e,i,n,(i=>{const n=this.getSnapRadius(i,r),s=t-i.centerX,o=e-i.centerY;return Math.sqrt(s*s+o*o)<=n}))}findSnapPreviewTarget(t,e,i,n){return this.findBestSnapTarget(t,e,i,n,(()=>!0))}findBestSnapTarget(t,e,i,n,r){let s=null,o=-1/0;const h=this._core.store.allNonSelectionObjects;for(const a of h){if(a.id===i)continue;if(n&&a.id===n)continue;if(!this.isAnchorable(a))continue;const h=a.rotatedPolygon;u.isPointInPolygon({x:t,y:e},[h.topLeft,h.topRight,h.bottomRight,h.bottomLeft])&&r(a)&&a.zIndex>o&&(o=a.zIndex,s={objectId:a.id,centerX:a.centerX,centerY:a.centerY})}return s}getSnapRadius(t,e){const i=Math.min(t.width,t.height)/5,n=this.getSafeScale(this._core.store.state.scale);return"touch"===e||"pen"===e?Math.max(1.75*i,24/n):Math.max(i,12/n)}setSnapCandidate(t){this._core.store.state.snapCandidate=t,this._core.rerender()}setSnapPreviewCandidate(t){this._core.store.state.snapPreviewCandidate=t,this._core.rerender()}getSnapCandidate(){return this._core.store.state.snapCandidate??null}getSnapPreviewCandidate(){return this._core.store.state.snapPreviewCandidate??null}clearSnapCandidate(){this._core.store.state.snapCandidate=null,this._core.rerender()}clearSnapPreviewCandidate(){this._core.store.state.snapPreviewCandidate=null,this._core.rerender()}getAnchorLinesRenderData(){const t=this._core.store.selectionGroup;if(!t||1!==t.objects.length)return null;const e=t.objects[0];if(!uo.isInstanceOf(e,"KritzelLine"))return null;const i=e,n=this.computeAnchorVisualization(i,"start"),r=this.computeAnchorVisualization(i,"end"),s=this.isFiniteAnchorVisualization(n)?n:null,o=this.isFiniteAnchorVisualization(r)?r:null;if(!s&&!o)return null;const h=this.getSafeScale(this._core.store.state.scale),a=this.getSafeScale(i.scale),l=i.strokeWidth/a,u=""+2/h,c=Math.max(2*l,4/h),f=`${c} ${c}`,d=8/h;return this.areFiniteNumbers(l,c,d)?{lineStrokeWidth:l,indicatorStrokeWidth:u,dashArray:f,indicatorRadius:d,startAnchorViz:s,endAnchorViz:o}:null}getSnapIndicatorRenderData(){return this.getIndicatorRenderDataForCandidate(this.getSnapCandidate())}getSnapPreviewRenderData(){return this.getIndicatorRenderDataForCandidate(this.getSnapPreviewCandidate())}getIndicatorRenderDataForCandidate(t){if(!t)return null;if(!this.areFiniteNumbers(t.centerX,t.centerY,t.lineEndpointX,t.lineEndpointY))return null;const e=this.getSafeScale(this._core.store.state.scale),i=8/e,n=""+2/e,r=this.areFiniteNumbers(t.lineStrokeWidth)&&t.lineStrokeWidth>0?t.lineStrokeWidth:4/e,s=`${r}`,o=Math.max(2*r,4/e),h=`${o} ${o}`,a=t.lineStroke||"#000000";let l,u=this.areFiniteNumbers(t.edgeX)?t.edgeX:void 0,c=this.areFiniteNumbers(t.edgeY)?t.edgeY:void 0,f=u,d=c;const p=this.areFiniteNumbers(t.arrowOffset)&&t.arrowOffset>0?t.arrowOffset:void 0;if(void 0!==p&&void 0!==u&&void 0!==c){const e=t.lineEndpointX-u,i=t.lineEndpointY-c,n=Math.sqrt(e*e+i*i);n>p&&(f=u+e/n*p,d=c+i/n*p);const r=u-t.lineEndpointX,s=c-t.lineEndpointY,o=Math.sqrt(r*r+s*s);if(o>0){const t=r/o,e=s/o,i=-e,n=u,h=c,a=n-t*p,f=h-e*p,d=a+i*p/2,g=f+t*p/2,m=a-i*p/2,w=f-t*p/2;this.areFiniteNumbers(n,h,d,g,m,w)&&(l=`${n},${h} ${d},${g} ${m},${w}`)}}if(!this.areFiniteNumbers(i,r,o))return null;const g=(()=>{if(void 0!==t.controlX&&void 0!==t.controlY&&void 0!==t.t&&this.areFiniteNumbers(t.controlX,t.controlY,t.t)){const e="start"===t.endpoint?1-t.t:t.t;if(e>=1)return;const i=this.extractQuadraticSegment({x:t.lineEndpointX,y:t.lineEndpointY},{x:t.controlX,y:t.controlY},{x:t.centerX,y:t.centerY},e,1);if(!this.areFiniteNumbers(i.start.x,i.start.y,i.control.x,i.control.y,i.end.x,i.end.y))return;return`M ${i.start.x} ${i.start.y} Q ${i.control.x} ${i.control.y} ${i.end.x} ${i.end.y}`}})();return{indicatorRadius:i,indicatorStrokeWidth:n,lineStrokeWidth:s,dashArray:h,lineStroke:a,centerX:t.centerX,centerY:t.centerY,lineEndpointX:t.lineEndpointX,lineEndpointY:t.lineEndpointY,edgeX:u,edgeY:c,arrowOffset:p,arrowStyle:t.arrowStyle,arrowFill:t.arrowFill,solidLineEndX:f,solidLineEndY:d,arrowPoints:l,snapLinePath:g}}handleObjectDeleted(t){const e=this.getLinesAnchoredTo(t);for(const t of e){this.removeAnchor(t.lineId,t.endpoint);const e=this.getLineById(t.lineId);e&&this._core.store.objects.update(e)}this._anchorIndex.delete(t)}handleLineDeleted(t){const e=this.getLineById(t);e&&(e.startAnchor&&this.removeFromIndex(e.startAnchor.objectId,t,"start"),e.endAnchor&&this.removeFromIndex(e.endAnchor.objectId,t,"end"))}rebuildIndex(){this._anchorIndex.clear();const t=this._core.store.allObjects;for(const e of t)e instanceof f&&(e.startAnchor&&this.addToIndex(e.startAnchor.objectId,e.id,"start"),e.endAnchor&&this.addToIndex(e.endAnchor.objectId,e.id,"end"))}addToIndex(t,e,i){this._anchorIndex.has(t)||this._anchorIndex.set(t,new Set);const n=this._anchorIndex.get(t);for(const t of n)if(t.lineId===e&&t.endpoint===i)return;n.add({lineId:e,endpoint:i})}removeFromIndex(t,e,i){const n=this._anchorIndex.get(t);if(n){for(const t of n)if(t.lineId===e&&t.endpoint===i){n.delete(t);break}0===n.size&&this._anchorIndex.delete(t)}}getLineById(t){const e=this._core.store.objects.filter((e=>e.id===t));if(0===e.length)return null;const i=e[0];return i instanceof f?i:null}getObjectById(t){const e=this._core.store.objects.filter((e=>e.id===t));return e.length>0?e[0]:null}findAnchorTarget(t,e){const i="start"===e?t.startAnchor:t.endAnchor;return i?this._core.store.allNonSelectionObjects.find((t=>t.id===i.objectId))??null:null}computeAnchorVisualization(t,e){if(!("start"===e?t.startAnchor:t.endAnchor))return null;const i=this.findAnchorTarget(t,e);if(!i)return null;const n=this.computeAnchorClipInfo(t,e,i);if(!n)return null;const r=i.centerX,s=i.centerY;if(!this.areFiniteNumbers(n.worldX,n.worldY,r,s))return null;const o=this.buildAnchorPath(t,e,n,i)??void 0;return o&&!this.isFinitePathData(o)?null:{edgeX:n.worldX,edgeY:n.worldY,centerX:r,centerY:s,pathD:o}}computeClippedLinePath(t,e=!1){const i=this.getSnapCandidate(),n=this._core.store.selectionGroup,r=i&&n&&1===n.objects.length&&n.objects[0].id===t.id;if(!t.startAnchor&&!t.endAnchor&&!r)return e?void 0!==t.controlX&&void 0!==t.controlY?`M ${t.startX-t.x} ${t.startY-t.y} Q ${t.controlX-t.x} ${t.controlY-t.y} ${t.endX-t.x} ${t.endY-t.y}`:`M ${t.startX-t.x} ${t.startY-t.y} L ${t.endX-t.x} ${t.endY-t.y}`:t.d;const s=t.startAnchor?this.findAnchorTarget(t,"start"):null,o=t.endAnchor?this.findAnchorTarget(t,"end"):null;let h=s?this.computeAnchorClipInfo(t,"start",s):null,a=o?this.computeAnchorClipInfo(t,"end",o):null;if(r&&void 0!==i.edgeX&&void 0!==i.edgeY){const e=this.lineWorldToLocal(t,i.edgeX,i.edgeY),n={worldX:i.edgeX,worldY:i.edgeY,localX:e.x,localY:e.y,t:i.t};"start"===i.endpoint?h=n:a=n}const l=e?t.x:0,u=e?t.y:0;if(void 0!==t.controlX&&void 0!==t.controlY){let e=h?.t??0,i=a?.t??1;if(h&&t.hasStartArrow){const i=t.getArrowSize("start"),n=this.evaluateDerivativeSpeedAtT(t,e);n>0&&(e+=i/n)}if(a&&t.hasEndArrow){const e=t.getArrowSize("end"),n=this.evaluateDerivativeSpeedAtT(t,i);n>0&&(i-=e/n)}if(e<0&&(e=0),i>1&&(i=1),i<=e){const t=(e+i)/2;e=t,i=t}const n=this.extractQuadraticSegment({x:t.startX,y:t.startY},{x:t.controlX,y:t.controlY},{x:t.endX,y:t.endY},e,i);return`M ${n.start.x-l} ${n.start.y-u} Q ${n.control.x-l} ${n.control.y-u} ${n.end.x-l} ${n.end.y-u}`}let c=h?.localX??t.startX,f=h?.localY??t.startY,d=a?.localX??t.endX,p=a?.localY??t.endY;if(h&&t.hasStartArrow){const e=t.getArrowSize("start"),i=d-c,n=p-f,r=Math.sqrt(i*i+n*n);r>e&&(c+=i/r*e,f+=n/r*e)}if(a&&t.hasEndArrow){const e=t.getArrowSize("end"),i=c-d,n=f-p,r=Math.sqrt(i*i+n*n);r>e&&(d+=i/r*e,p+=n/r*e)}return`M ${c-l} ${f-u} L ${d-l} ${p-u}`}computeAnchorClipInfo(t,e,i){return void 0!==t.controlX&&void 0!==t.controlY?this.computeCurvedClipInfo(t,e,i):this.computeStraightClipInfo(t,e,i)}computeStraightClipInfo(t,e,i){const n="start"===e?this.lineLocalToWorld(t,t.endX,t.endY):this.lineLocalToWorld(t,t.startX,t.startY),r=this.getPathClipPoint(i,n);if(r){const i=this.lineWorldToLocal(t,r.x,r.y),n=Math.sqrt(Math.pow(t.endX-t.startX,2)+Math.pow(t.endY-t.startY,2)),s=Math.sqrt(Math.pow(i.x-t.startX,2)+Math.pow(i.y-t.startY,2));return{localX:i.x,localY:i.y,worldX:r.x,worldY:r.y,t:n>0?s/n:"start"===e?0:1}}const s=this.getClipPolygonForObject(i);let o;if(o=s?u.getLinePointsArrayIntersection(n,{x:i.centerX,y:i.centerY},s):u.getLinePolygonIntersection(n,{x:i.centerX,y:i.centerY},i.rotatedPolygon),!o)return null;const h=this.lineWorldToLocal(t,o.x,o.y),a=Math.sqrt(Math.pow(t.endX-t.startX,2)+Math.pow(t.endY-t.startY,2)),l=Math.sqrt(Math.pow(h.x-t.startX,2)+Math.pow(h.y-t.startY,2));return{localX:h.x,localY:h.y,worldX:o.x,worldY:o.y,t:a>0?l/a:"start"===e?0:1}}computeCurvedClipInfo(t,e,i){if(uo.isInstanceOf(i,"KritzelPath"))return this.findCurveExitPointForPath(t,e,i);const n=this.getClipPolygonForObject(i),r=n??this.getPolygonPoints(i.rotatedPolygon),s=this.findCurveExitPoint(t,e,r);if(s)return s;const o="start"===e?this.lineLocalToWorld(t,t.endX,t.endY):this.lineLocalToWorld(t,t.startX,t.startY);let h;if(h=n?u.getLinePointsArrayIntersection(o,{x:i.centerX,y:i.centerY},n):u.getLinePolygonIntersection(o,{x:i.centerX,y:i.centerY},i.rotatedPolygon),!h)return null;const a=this.lineWorldToLocal(t,h.x,h.y),l=this.approximateParameterForWorldPoint(t,h);return{localX:a.x,localY:a.y,worldX:h.x,worldY:h.y,t:l}}findCurveExitPoint(t,e,i){const n="start"===e?0:1,r=this.evaluateLineAtT(t,n);let s=u.isPointInPolygon({x:r.worldX,y:r.worldY},i),o=n;for(let n=1;n<=64;n++){const r="start"===e?n/64:1-n/64,h=this.evaluateLineAtT(t,r),a=u.isPointInPolygon({x:h.worldX,y:h.worldY},i);if(s&&!a){const e=this.refineCurveExitParameter(t,i,o,r),n=this.evaluateLineAtT(t,e);return{localX:n.localX,localY:n.localY,worldX:n.worldX,worldY:n.worldY,t:e}}s=a,o=r}return null}findCurveExitPointForPath(t,e,i){const n="start"===e?0:1,r=i.strokeWidth/i.scale/2,s=this.getPathAdjustedPoints(i);if(s.length<1)return null;const o=this.evaluateLineAtT(t,n);let h=this.isPointInPathStroke(o.worldX,o.worldY,s,r),a=n;for(let i=1;i<=64;i++){const n="start"===e?i/64:1-i/64,o=this.evaluateLineAtT(t,n),l=this.isPointInPathStroke(o.worldX,o.worldY,s,r);if(h&&!l){const e=this.refineCurveExitParameterForPath(t,s,r,a,n),i=this.evaluateLineAtT(t,e);return{localX:i.localX,localY:i.localY,worldX:i.worldX,worldY:i.worldY,t:e}}h=l,a=n}return null}refineCurveExitParameterForPath(t,e,i,n,r){let s=n,o=r;for(let n=0;n<8;n++){const n=(s+o)/2,r=this.evaluateLineAtT(t,n);this.isPointInPathStroke(r.worldX,r.worldY,e,i)?s=n:o=n}return(s+o)/2}getPathAdjustedPoints(t){return this.computePathAdjustedPoints(t)}computePathAdjustedPoints(t){if(!t.points?.length)return[];const e=t.rotation,i=Math.cos(e),n=Math.sin(e),r=t.points.map((t=>t[0])),s=t.points.map((t=>t[1])),o={x:(Math.min(...r)+Math.max(...r))/2,y:(Math.min(...s)+Math.max(...s))/2},{x:h,y:a}=o;return t.points.map((([t,e])=>{const r=t-h,s=e-a;return[h+r*i-s*n,a+r*n+s*i]})).map((([e,i])=>[Math.abs(e-t.x)/t.scale+t.translateX,Math.abs(i-t.y)/t.scale+t.translateY]))}isPointInPathStroke(t,e,i,n){if(1===i.length){const r=i[0],s=t-r[0],o=e-r[1];return Math.sqrt(s*s+o*o)<=n}for(let r=0;r<i.length-1;r++){const s=i[r],o=i[r+1];if(this.pointToSegmentDistance(t,e,s[0],s[1],o[0],o[1])<=n)return!0}return!1}pointToSegmentDistance(t,e,i,n,r,s){const o=r-i,h=s-n,a=o*o+h*h;if(0===a)return Math.sqrt((t-i)*(t-i)+(e-n)*(e-n));let l=((t-i)*o+(e-n)*h)/a;l=Math.max(0,Math.min(1,l));const u=i+l*o,c=n+l*h;return Math.sqrt((t-u)*(t-u)+(e-c)*(e-c))}refineCurveExitParameter(t,e,i,n){let r=i,s=n;for(let i=0;i<8;i++){const i=(r+s)/2,n=this.evaluateLineAtT(t,i);u.isPointInPolygon({x:n.worldX,y:n.worldY},e)?r=i:s=i}return(r+s)/2}approximateParameterForWorldPoint(t,e){let i=0,n=1/0;for(let r=0;r<=80;r++){const s=r/80,o=this.evaluateLineAtT(t,s),h=Math.hypot(o.worldX-e.x,o.worldY-e.y);h<n&&(n=h,i=s)}return i}evaluateLineAtT(t,e){const i=Math.max(0,Math.min(1,e));let n,r;if(void 0!==t.controlX&&void 0!==t.controlY){const e=1-i;n=e*e*t.startX+2*e*i*t.controlX+i*i*t.endX,r=e*e*t.startY+2*e*i*t.controlY+i*i*t.endY}else n=t.startX+(t.endX-t.startX)*i,r=t.startY+(t.endY-t.startY)*i;const s=this.lineLocalToWorld(t,n,r);return{t:i,localX:n,localY:r,worldX:s.x,worldY:s.y}}evaluateDerivativeSpeedAtT(t,e){const i=Math.max(0,Math.min(1,e));if(void 0!==t.controlX&&void 0!==t.controlY){const e=t.controlX,n=t.controlY,r=2*(1-i)*(e-t.startX)+2*i*(t.endX-e),s=2*(1-i)*(n-t.startY)+2*i*(t.endY-n);return Math.sqrt(r*r+s*s)}{const e=t.endX-t.startX,i=t.endY-t.startY;return Math.sqrt(e*e+i*i)}}extractQuadraticSegment(t,e,i,n,r){let s=Math.max(0,Math.min(1,n)),o=Math.max(0,Math.min(1,r));if(o<s){const t=s;s=o,o=t}let h={start:t,control:e,end:i};if(s>0){h=this.splitQuadraticSegment(h,s).right;const t=1-s;o=t>0?(o-s)/t:1}return o<1&&(h=this.splitQuadraticSegment(h,o).left),h}splitQuadraticSegment(t,e){const i=Math.max(0,Math.min(1,e)),n=t.start,r=t.control,s=t.end,o=this.lerpPoint(n,r,i),h=this.lerpPoint(r,s,i),a=this.lerpPoint(o,h,i);return{left:{start:n,control:o,end:a},right:{start:a,control:h,end:s}}}lerpPoint(t,e,i){return{x:t.x+(e.x-t.x)*i,y:t.y+(e.y-t.y)*i}}buildAnchorPath(t,e,i,n){if(void 0===t.controlX||void 0===t.controlY||void 0===i.t)return`M ${i.worldX} ${i.worldY} L ${n.centerX} ${n.centerY}`;const r="start"===e?0:i.t,s="start"===e?i.t:1;if(s<=r)return`M ${i.worldX} ${i.worldY} L ${n.centerX} ${n.centerY}`;const o=this.extractQuadraticSegment({x:t.startX,y:t.startY},{x:t.controlX,y:t.controlY},{x:t.endX,y:t.endY},r,s);return this.buildWorldQuadraticPath(t,o,"start"===e)}buildWorldQuadraticPath(t,e,i=!1){const n=i?e.end:e.start,r=i?e.start:e.end,s=e.control,o=this.lineLocalToWorld(t,n.x,n.y),h=this.lineLocalToWorld(t,s.x,s.y),a=this.lineLocalToWorld(t,r.x,r.y);return`M ${o.x} ${o.y} Q ${h.x} ${h.y} ${a.x} ${a.y}`}getPolygonPoints(t){return[t.topLeft,t.topRight,t.bottomRight,t.bottomLeft]}getClipPolygonForObject(t){return uo.isInstanceOf(t,"KritzelShape")?t.getClipPolygon():null}getPathClipPoint(t,e){return uo.isInstanceOf(t,"KritzelPath")?t.getClipPoint(e):null}lineLocalToWorld(t,e,i){const n=e-t.x,r=i-t.y,s=t.totalWidth/2,o=t.totalHeight/2,h=Math.cos(t.rotation),a=Math.sin(t.rotation),l=(n-s)*h-(r-o)*a+s,u=(n-s)*a+(r-o)*h+o,c=this.getSafeScale(t.scale);return{x:l/c+t.translateX,y:u/c+t.translateY}}lineWorldToLocal(t,e,i){const n=this.getSafeScale(t.scale),r=(e-t.translateX)*n,s=(i-t.translateY)*n,o=t.totalWidth/2,h=t.totalHeight/2,a=Math.cos(-t.rotation),l=Math.sin(-t.rotation);return{x:(r-o)*a-(s-h)*l+o+t.x,y:(r-o)*l+(s-h)*a+h+t.y}}getSafeScale(t){return Number.isFinite(t)&&Math.abs(t)>1e-6?t:1}areFiniteNumbers(...t){return t.every((t=>void 0!==t&&Number.isFinite(t)))}isFiniteAnchorVisualization(t){return!(!t||!this.areFiniteNumbers(t.edgeX,t.edgeY,t.centerX,t.centerY)||t.pathD&&!this.isFinitePathData(t.pathD))}isFinitePathData(t){return!t.includes("Infinity")&&!t.includes("NaN")}isAnchorable(t){return!(t instanceof gh||t instanceof So)&&!(t instanceof f)&&t.isVisible}}class kh{static interpolate(t,e){return e?t.replace(/\{(\w+)\}/g,((t,i)=>{const n=e[i];return null==n?t:String(n)})):t}}const Mh={code:"en",label:"English",terms:{"menu.copy":"Copy","menu.cut":"Cut","menu.paste":"Paste","menu.selectAll":"Select All","menu.order":"Order","menu.bringToFront":"Bring to Front","menu.sendToBack":"Send to Back","menu.moveUp":"Move Up","menu.moveDown":"Move Down","menu.align":"Align","menu.alignLeft":"Align Left","menu.alignCenterHorizontal":"Align Center Horizontally","menu.alignRight":"Align Right","menu.alignTop":"Align Top","menu.alignCenterVertical":"Align Center Vertically","menu.alignBottom":"Align Bottom","menu.group":"Group","menu.ungroup":"Ungroup","menu.export":"Export","menu.exportAsSvg":"Export as SVG","menu.exportAsPng":"Export as PNG","menu.delete":"Delete","menu.share":"Share","menu.import":"Import","menu.settings":"Settings","menu.logout":"Logout","settings.dialogTitle":"Settings","settings.categories.general":"General","settings.categories.viewport":"Viewport","settings.categories.shortcuts":"Keyboard Shortcuts","settings.categories.developer":"Developer Options","settings.categories.about":"About","settings.general.title":"General Settings","settings.general.theme.label":"Theme","settings.general.theme.description":"Select a registered color theme for the editor interface.","settings.general.language.label":"Language","settings.general.language.description":"Select the display language for the editor interface.","settings.general.lockDrawingScale.label":"Lock Drawing Scale","settings.general.lockDrawingScale.description":"When enabled, drawn objects maintain a fixed visual size regardless of the current zoom level.","settings.viewport.title":"Viewport Settings","settings.viewport.minZoom.label":"Minimum Zoom Level","settings.viewport.minZoom.description":"Sets the minimum zoom level. Lower values allow zooming out further to see more of the canvas.","settings.viewport.maxZoom.label":"Maximum Zoom Level","settings.viewport.maxZoom.description":"Sets the maximum zoom level. Higher values allow zooming in closer for detailed work.","settings.viewport.boundaryLeft.label":"Viewport Boundary Left","settings.viewport.boundaryLeft.description":"Left boundary in world coordinates. Set to limit how far left the viewport can pan.","settings.viewport.boundaryRight.label":"Viewport Boundary Right","settings.viewport.boundaryRight.description":"Right boundary in world coordinates. Set to limit how far right the viewport can pan.","settings.viewport.boundaryTop.label":"Viewport Boundary Top","settings.viewport.boundaryTop.description":"Top boundary in world coordinates. Set to limit how far up the viewport can pan.","settings.viewport.boundaryBottom.label":"Viewport Boundary Bottom","settings.viewport.boundaryBottom.description":"Bottom boundary in world coordinates. Set to limit how far down the viewport can pan.","settings.viewport.boundaryPlaceholder":"Infinite","settings.shortcuts.title":"Keyboard Shortcuts","settings.developer.title":"Developer Options","settings.developer.showViewportInfo.label":"Show Viewport Info","settings.developer.showViewportInfo.description":"Display viewport debug information such as position, zoom level, and boundaries.","settings.developer.showObjectInfo.label":"Show Object Info","settings.developer.showObjectInfo.description":"Display debug information about objects on the canvas.","settings.developer.showSyncProviderInfo.label":"Show Sync Provider Info","settings.developer.showSyncProviderInfo.description":"Display debug information about the sync provider connection status.","settings.developer.showMigrationInfo.label":"Show Migration Info","settings.developer.showMigrationInfo.description":"Display debug information about data migrations.","settings.about.title":"About","settings.about.description":"Kritzel - A drawing application","export.dialogTitle":"Export","export.tabs.viewport":"Export Viewport","export.tabs.workspace":"Export Workspace","export.format.label":"Format","export.filename.label":"Filename","export.filename.placeholder":"Enter filename","export.exportButton":"Export","workspace.sharedTooltip":"Shared workspace","workspace.rename":"Rename","workspace.delete":"Delete","zoom.zoomIn":"Zoom in","zoom.zoomOut":"Zoom out","utility.undo":"Undo","utility.redo":"Redo","utility.delete":"Delete selected items","share.dialogTitle":"Share Workspace","share.linkSharing.label":"Link sharing","share.linkSharing.enabledDescription":"Anyone with the link can access this workspace.","share.linkSharing.disabledDescription":"Link sharing is disabled. Only you can access this workspace.","share.linkSharing.toggleLabel":"Enable link sharing","share.copyLink.title":"Copy link","share.copyLink.copied":"Copied!","login.dialogTitle":"Sign in","currentUser.dialogTitle":"Account","backToContent.label":"Back to content","toolConfig.collapse":"Collapse","toolConfig.expand":"Expand","moreMenu.ariaLabel":"More options","engine.loading":"Loading...","watermark.poweredBy":"Powered by Kritzel"}},Sh={code:"de",label:"Deutsch",terms:{"menu.copy":"Kopieren","menu.cut":"Ausschneiden","menu.paste":"Einfügen","menu.selectAll":"Alles auswählen","menu.order":"Anordnen","menu.bringToFront":"In den Vordergrund","menu.sendToBack":"In den Hintergrund","menu.moveUp":"Nach vorne","menu.moveDown":"Nach hinten","menu.align":"Ausrichten","menu.alignLeft":"Linksbündig ausrichten","menu.alignCenterHorizontal":"Horizontal zentrieren","menu.alignRight":"Rechtsbündig ausrichten","menu.alignTop":"Oben ausrichten","menu.alignCenterVertical":"Vertikal zentrieren","menu.alignBottom":"Unten ausrichten","menu.group":"Gruppieren","menu.ungroup":"Gruppierung aufheben","menu.export":"Exportieren","menu.exportAsSvg":"Als SVG exportieren","menu.exportAsPng":"Als PNG exportieren","menu.delete":"Löschen","menu.share":"Teilen","menu.import":"Importieren","menu.settings":"Einstellungen","menu.logout":"Abmelden","settings.dialogTitle":"Einstellungen","settings.categories.general":"Allgemein","settings.categories.viewport":"Ansichtsfenster","settings.categories.shortcuts":"Tastenkürzel","settings.categories.developer":"Entwickleroptionen","settings.categories.about":"Über","settings.general.title":"Allgemeine Einstellungen","settings.general.theme.label":"Design","settings.general.theme.description":"Wählen Sie ein registriertes Farbdesign für die Editor-Oberfläche.","settings.general.language.label":"Sprache","settings.general.language.description":"Wählen Sie die Anzeigesprache für die Editor-Oberfläche.","settings.general.lockDrawingScale.label":"Zeichenskalierung sperren","settings.general.lockDrawingScale.description":"Wenn aktiviert, behalten gezeichnete Objekte unabhängig von der aktuellen Zoomstufe eine feste visuelle Größe.","settings.viewport.title":"Ansichtsfenster-Einstellungen","settings.viewport.minZoom.label":"Minimale Zoomstufe","settings.viewport.minZoom.description":"Legt die minimale Zoomstufe fest. Niedrigere Werte ermöglichen weiteres Herauszoomen, um mehr von der Zeichenfläche zu sehen.","settings.viewport.maxZoom.label":"Maximale Zoomstufe","settings.viewport.maxZoom.description":"Legt die maximale Zoomstufe fest. Höhere Werte ermöglichen näheres Heranzoomen für Detailarbeit.","settings.viewport.boundaryLeft.label":"Ansichtsfenster-Grenze links","settings.viewport.boundaryLeft.description":"Linke Grenze in Weltkoordinaten. Legen Sie fest, wie weit das Ansichtsfenster nach links verschoben werden kann.","settings.viewport.boundaryRight.label":"Ansichtsfenster-Grenze rechts","settings.viewport.boundaryRight.description":"Rechte Grenze in Weltkoordinaten. Legen Sie fest, wie weit das Ansichtsfenster nach rechts verschoben werden kann.","settings.viewport.boundaryTop.label":"Ansichtsfenster-Grenze oben","settings.viewport.boundaryTop.description":"Obere Grenze in Weltkoordinaten. Legen Sie fest, wie weit das Ansichtsfenster nach oben verschoben werden kann.","settings.viewport.boundaryBottom.label":"Ansichtsfenster-Grenze unten","settings.viewport.boundaryBottom.description":"Untere Grenze in Weltkoordinaten. Legen Sie fest, wie weit das Ansichtsfenster nach unten verschoben werden kann.","settings.viewport.boundaryPlaceholder":"Unendlich","settings.shortcuts.title":"Tastenkürzel","settings.developer.title":"Entwickleroptionen","settings.developer.showViewportInfo.label":"Ansichtsfenster-Infos anzeigen","settings.developer.showViewportInfo.description":"Zeigt Debug-Informationen zum Ansichtsfenster an, z. B. Position, Zoomstufe und Grenzen.","settings.developer.showObjectInfo.label":"Objekt-Infos anzeigen","settings.developer.showObjectInfo.description":"Zeigt Debug-Informationen zu Objekten auf der Zeichenfläche an.","settings.developer.showSyncProviderInfo.label":"Sync-Provider-Infos anzeigen","settings.developer.showSyncProviderInfo.description":"Zeigt Debug-Informationen zum Verbindungsstatus des Sync-Providers an.","settings.developer.showMigrationInfo.label":"Migrations-Infos anzeigen","settings.developer.showMigrationInfo.description":"Zeigt Debug-Informationen zu Datenmigrationen an.","settings.about.title":"Über","settings.about.description":"Kritzel – Eine Zeichenanwendung","export.dialogTitle":"Exportieren","export.tabs.viewport":"Ansichtsfenster exportieren","export.tabs.workspace":"Arbeitsbereich exportieren","export.format.label":"Format","export.filename.label":"Dateiname","export.filename.placeholder":"Dateiname eingeben","export.exportButton":"Exportieren","workspace.sharedTooltip":"Geteilter Arbeitsbereich","workspace.rename":"Umbenennen","workspace.delete":"Löschen","zoom.zoomIn":"Vergrößern","zoom.zoomOut":"Verkleinern","utility.undo":"Rückgängig","utility.redo":"Wiederholen","utility.delete":"Ausgewählte Elemente löschen","share.dialogTitle":"Arbeitsbereich teilen","share.linkSharing.label":"Link-Freigabe","share.linkSharing.enabledDescription":"Jeder mit dem Link kann auf diesen Arbeitsbereich zugreifen.","share.linkSharing.disabledDescription":"Die Link-Freigabe ist deaktiviert. Nur Sie können auf diesen Arbeitsbereich zugreifen.","share.linkSharing.toggleLabel":"Link-Freigabe aktivieren","share.copyLink.title":"Link kopieren","share.copyLink.copied":"Kopiert!","login.dialogTitle":"Anmelden","currentUser.dialogTitle":"Konto","backToContent.label":"Zurück zum Inhalt","toolConfig.collapse":"Einklappen","toolConfig.expand":"Ausklappen","moreMenu.ariaLabel":"Weitere Optionen","engine.loading":"Wird geladen...","watermark.poweredBy":"Bereitgestellt von Kritzel"}},xh={code:"fr",label:"Français",terms:{"menu.copy":"Copier","menu.cut":"Couper","menu.paste":"Coller","menu.selectAll":"Tout sélectionner","menu.order":"Ordre","menu.bringToFront":"Mettre au premier plan","menu.sendToBack":"Mettre à l'arrière-plan","menu.moveUp":"Avancer","menu.moveDown":"Reculer","menu.align":"Aligner","menu.alignLeft":"Aligner à gauche","menu.alignCenterHorizontal":"Centrer horizontalement","menu.alignRight":"Aligner à droite","menu.alignTop":"Aligner en haut","menu.alignCenterVertical":"Centrer verticalement","menu.alignBottom":"Aligner en bas","menu.group":"Grouper","menu.ungroup":"Dégrouper","menu.export":"Exporter","menu.exportAsSvg":"Exporter en SVG","menu.exportAsPng":"Exporter en PNG","menu.delete":"Supprimer","menu.share":"Partager","menu.import":"Importer","menu.settings":"Paramètres","menu.logout":"Déconnexion","settings.dialogTitle":"Paramètres","settings.categories.general":"Général","settings.categories.viewport":"Fenêtre d'affichage","settings.categories.shortcuts":"Raccourcis clavier","settings.categories.developer":"Options développeur","settings.categories.about":"À propos","settings.general.title":"Paramètres généraux","settings.general.theme.label":"Thème","settings.general.theme.description":"Sélectionnez un thème de couleurs enregistré pour l'interface de l'éditeur.","settings.general.language.label":"Langue","settings.general.language.description":"Sélectionnez la langue d'affichage de l'interface de l'éditeur.","settings.general.lockDrawingScale.label":"Verrouiller l'échelle de dessin","settings.general.lockDrawingScale.description":"Lorsque cette option est activée, les objets dessinés conservent une taille visuelle fixe quel que soit le niveau de zoom actuel.","settings.viewport.title":"Paramètres de la fenêtre d'affichage","settings.viewport.minZoom.label":"Niveau de zoom minimal","settings.viewport.minZoom.description":"Définit le niveau de zoom minimal. Des valeurs plus faibles permettent de dézoomer davantage pour voir une plus grande partie du canevas.","settings.viewport.maxZoom.label":"Niveau de zoom maximal","settings.viewport.maxZoom.description":"Définit le niveau de zoom maximal. Des valeurs plus élevées permettent de zoomer davantage pour un travail détaillé.","settings.viewport.boundaryLeft.label":"Limite gauche de la fenêtre d'affichage","settings.viewport.boundaryLeft.description":"Limite gauche en coordonnées du monde. Définissez jusqu'où la fenêtre d'affichage peut se déplacer vers la gauche.","settings.viewport.boundaryRight.label":"Limite droite de la fenêtre d'affichage","settings.viewport.boundaryRight.description":"Limite droite en coordonnées du monde. Définissez jusqu'où la fenêtre d'affichage peut se déplacer vers la droite.","settings.viewport.boundaryTop.label":"Limite supérieure de la fenêtre d'affichage","settings.viewport.boundaryTop.description":"Limite supérieure en coordonnées du monde. Définissez jusqu'où la fenêtre d'affichage peut se déplacer vers le haut.","settings.viewport.boundaryBottom.label":"Limite inférieure de la fenêtre d'affichage","settings.viewport.boundaryBottom.description":"Limite inférieure en coordonnées du monde. Définissez jusqu'où la fenêtre d'affichage peut se déplacer vers le bas.","settings.viewport.boundaryPlaceholder":"Infini","settings.shortcuts.title":"Raccourcis clavier","settings.developer.title":"Options développeur","settings.developer.showViewportInfo.label":"Afficher les infos de la fenêtre d'affichage","settings.developer.showViewportInfo.description":"Affiche les informations de débogage de la fenêtre d'affichage telles que la position, le niveau de zoom et les limites.","settings.developer.showObjectInfo.label":"Afficher les infos des objets","settings.developer.showObjectInfo.description":"Affiche les informations de débogage des objets sur le canevas.","settings.developer.showSyncProviderInfo.label":"Afficher les infos du fournisseur de synchronisation","settings.developer.showSyncProviderInfo.description":"Affiche les informations de débogage sur l'état de connexion du fournisseur de synchronisation.","settings.developer.showMigrationInfo.label":"Afficher les infos de migration","settings.developer.showMigrationInfo.description":"Affiche les informations de débogage sur les migrations de données.","settings.about.title":"À propos","settings.about.description":"Kritzel - Une application de dessin","export.dialogTitle":"Exporter","export.tabs.viewport":"Exporter la fenêtre d'affichage","export.tabs.workspace":"Exporter l'espace de travail","export.format.label":"Format","export.filename.label":"Nom du fichier","export.filename.placeholder":"Saisir le nom du fichier","export.exportButton":"Exporter","workspace.sharedTooltip":"Espace de travail partagé","workspace.rename":"Renommer","workspace.delete":"Supprimer","zoom.zoomIn":"Zoom avant","zoom.zoomOut":"Zoom arrière","utility.undo":"Annuler","utility.redo":"Rétablir","utility.delete":"Supprimer les éléments sélectionnés","share.dialogTitle":"Partager l'espace de travail","share.linkSharing.label":"Partage par lien","share.linkSharing.enabledDescription":"Toute personne disposant du lien peut accéder à cet espace de travail.","share.linkSharing.disabledDescription":"Le partage par lien est désactivé. Vous seul pouvez accéder à cet espace de travail.","share.linkSharing.toggleLabel":"Activer le partage par lien","share.copyLink.title":"Copier le lien","share.copyLink.copied":"Copié !","login.dialogTitle":"Se connecter","currentUser.dialogTitle":"Compte","backToContent.label":"Retour au contenu","toolConfig.collapse":"Réduire","toolConfig.expand":"Développer","moreMenu.ariaLabel":"Plus d'options","engine.loading":"Chargement...","watermark.poweredBy":"Propulsé par Kritzel"}},Ah="kritzel-settings",$h="en";class zh{_core;_storageKey;_builtinLocales=new Map;_customLocales=new Map;_currentLocale=$h;_fallbackLocale=$h;constructor(t){this._core=t,this._storageKey=t.editorId?`${Ah}-${t.editorId}`:Ah,this._builtinLocales.set(Mh.code,Mh),this._builtinLocales.set(Sh.code,Sh),this._builtinLocales.set(xh.code,xh),this._currentLocale=this.getStoredLocale()}get currentLocale(){return this._currentLocale}get fallbackLocale(){return this._fallbackLocale}setFallbackLocale(t){this._fallbackLocale=t}registerLocales(t){for(const e of t)this._customLocales.set(e.code,e)}setLocale(t){this._currentLocale=t,this._core.rerender()}getAvailableLocales(){return Array.from(new Set([...this._builtinLocales.keys(),...this._customLocales.keys()]))}getAvailableLocaleOptions(){return this.getAvailableLocales().map((t=>({code:t,label:this.getLocaleLabel(t)})))}getLocaleLabel(t){return this._customLocales.get(t)?.label??this._builtinLocales.get(t)?.label??t}translate(t,e){const i=this._customLocales.get(this._currentLocale)?.terms[t]??this._builtinLocales.get(this._currentLocale)?.terms[t]??this._customLocales.get(this._fallbackLocale)?.terms[t]??this._builtinLocales.get(this._fallbackLocale)?.terms[t]??t;return kh.interpolate(i,e)}getAllTerms(){const t=new Set;for(const e of[...this._builtinLocales.values(),...this._customLocales.values()])for(const i of Object.keys(e.terms))t.add(i);const e={};for(const i of t)e[i]=this.translate(i);return e}getStoredLocale(){if("undefined"==typeof localStorage)return $h;const t=localStorage.getItem(this._storageKey);if(!t)return $h;try{const e=JSON.parse(t);if("string"==typeof e?.locale)return e.locale}catch{}return $h}cleanup(){this._customLocales.clear()}}class Ch{_core;_licenseKey;_isLicensed=!1;_verifiedToken;_validationId=0;_publicKeyPromise;_timer=null;constructor(t){this._core=t}get isLicensed(){return this._isLicensed}validate(t){this._licenseKey=t;const e=++this._validationId;let i;try{i=this.preCheck(t)}catch{return this.commit(!0,e),this._isLicensed}return"rejected"===i.status?(this._verifiedToken=void 0,this.commit(!1,e),this._isLicensed):this._verifiedToken===t?(this.commit(!0,e),this._isLicensed):(this.verifySignature(i.payloadSegment,i.signatureSegment).then((i=>{e===this._validationId&&(i?(this._verifiedToken=t,this.commit(!0,e)):(this._verifiedToken=void 0,this.commit(!1,e)))})).catch((()=>{e===this._validationId&&this.commit(!0,e)})),this._isLicensed)}startPeriodicValidation(){this.stopPeriodicValidation(),this.scheduleNextValidation()}stopPeriodicValidation(){null!==this._timer&&(clearTimeout(this._timer),this._timer=null)}destroy(){this.stopPeriodicValidation()}commit(t,e){e===this._validationId&&t!==this._isLicensed&&(this._isLicensed=t,this._core.rerender())}scheduleNextValidation(){const t=this.getRandomRevalidationDelay();this._timer=setTimeout((()=>{this.validate(this._licenseKey),this.scheduleNextValidation()}),t)}getRandomRevalidationDelay(){return 3e4+Math.floor(30001*Math.random())}preCheck(t){if(null==t)return{status:"rejected"};const e=t.trim();if(0===e.length||!e.startsWith("KRTZL1."))return{status:"rejected"};const i=e.slice(7).split(".");if(2!==i.length||0===i[0].length||0===i[1].length)return{status:"rejected"};const[n,r]=i;let s;try{s=JSON.parse(this.base64UrlToString(n))}catch{return{status:"rejected"}}return null===s||"object"!=typeof s||"number"==typeof s.exp&&1e3*s.exp<=Date.now()?{status:"rejected"}:{status:"pass",payloadSegment:n,signatureSegment:r,claims:s}}async verifySignature(t,e){const i=await this.getPublicKey(),n=this.utf8Bytes(t),r=this.base64UrlToBytes(e);return crypto.subtle.verify("Ed25519",i,r,n)}getPublicKey(){if(!this._publicKeyPromise){const t=this.base64UrlToBytes("I-pYJlxDEjT94rwSaqhXW5Sv__fMKS-JKKnV3pg0PaM");this._publicKeyPromise=Promise.resolve().then((()=>crypto.subtle.importKey("raw",t,{name:"Ed25519"},!1,["verify"]))),this._publicKeyPromise.catch((()=>{this._publicKeyPromise=void 0}))}return this._publicKeyPromise}base64UrlToString(t){return(new TextDecoder).decode(this.base64UrlToBytes(t))}base64UrlToBytes(t){const e=t.replace(/-/g,"+").replace(/_/g,"/"),i=e.padEnd(e.length+(4-e.length%4)%4,"="),n=atob(i),r=new Uint8Array(new ArrayBuffer(n.length));for(let t=0;t<n.length;t++)r[t]=n.charCodeAt(t);return r}utf8Bytes(t){const e=(new TextEncoder).encode(t),i=new Uint8Array(new ArrayBuffer(e.length));return i.set(e),i}}var Th;function Eh(t,e,i,n,r,s){const o=s?.quiet??!0,h=e.get("schemaVersion")??0;if(h>=r)return{migrated:!1,fromVersion:h,toVersion:h};const a=n.filter((t=>t.fromVersion>=h&&t.toVersion<=r)).sort(((t,e)=>t.fromVersion-e.fromVersion));return o||console.log(`[Kritzel] Running ${a.length} migration(s) from v${h} to v${r}`),t.transact((()=>{for(const e of a)o||console.log(`[Kritzel] Migrating v${e.fromVersion} → v${e.toVersion}`),e.migrate(t,i);e.set("schemaVersion",r)}),"migration"),o||console.log(`[Kritzel] Migrations complete. Schema now at v${r}`),{migrated:!0,fromVersion:h,toVersion:r}}!function(t){t.StartHorizontal="start-horizontal",t.CenterHorizontal="center-horizontal",t.EndHorizontal="end-horizontal",t.StartVertical="start-vertical",t.CenterVertical="center-vertical",t.EndVertical="end-vertical"}(Th||(Th={}));const Oh=[{fromVersion:1,toVersion:2,migrate(t,e){const i=e.workspaces;i&&i.forEach(((t,e)=>{const n=t?.viewport;if(!n)return;if("centerWorldX"in n)return;const r=n.scale??1,s=n.translateX??0,o=n.translateY??0,h={...t,viewport:{centerWorldX:-s/r||0,centerWorldY:-o/r||0,scale:r}};i.set(e,h)}))}}],Ih=[{fromVersion:1,toVersion:2,migrate(t,e){}}],jh={providers:[]};var Ph,Rh,Dh,_h={exports:{}},Lh=(Ph||(Ph=1,Rh=_h,Dh=_h.exports,function(){var t,e="Expected a function",i="__lodash_hash_undefined__",n="__lodash_placeholder__",r=32,s=128,o=1/0,h=9007199254740991,a=NaN,l=4294967295,u=[["ary",s],["bind",1],["bindKey",2],["curry",8],["curryRight",16],["flip",512],["partial",r],["partialRight",64],["rearg",256]],c="[object Arguments]",f="[object Array]",d="[object Boolean]",g="[object Date]",m="[object Error]",w="[object Function]",v="[object GeneratorFunction]",y="[object Map]",b="[object Number]",k="[object Object]",M="[object Promise]",S="[object RegExp]",x="[object Set]",A="[object String]",$="[object Symbol]",z="[object WeakMap]",C="[object ArrayBuffer]",T="[object DataView]",E="[object Float32Array]",O="[object Float64Array]",I="[object Int8Array]",j="[object Int16Array]",P="[object Int32Array]",R="[object Uint8Array]",D="[object Uint8ClampedArray]",_="[object Uint16Array]",L="[object Uint32Array]",B=/\b__p \+= '';/g,F=/\b(__p \+=) '' \+/g,N=/(__e\(.*?\)|\b__t\)) \+\n'';/g,W=/&(?:amp|lt|gt|quot|#39);/g,U=/[&<>"']/g,K=RegExp(W.source),H=RegExp(U.source),V=/<%-([\s\S]+?)%>/g,G=/<%([\s\S]+?)%>/g,X=/<%=([\s\S]+?)%>/g,Y=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,q=/^\w*$/,J=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,Q=/[\\^$.*+?()[\]{}|]/g,Z=RegExp(Q.source),tt=/^\s+/,et=/\s/,it=/\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/,nt=/\{\n\/\* \[wrapped with (.+)\] \*/,rt=/,? & /,st=/[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g,ot=/[()=,{}\[\]\/\s]/,ht=/\\(\\)?/g,at=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g,lt=/\w*$/,ut=/^[-+]0x[0-9a-f]+$/i,ct=/^0b[01]+$/i,ft=/^\[object .+?Constructor\]$/,dt=/^0o[0-7]+$/i,pt=/^(?:0|[1-9]\d*)$/,gt=/[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g,mt=/($^)/,wt=/['\n\r\u2028\u2029\\]/g,vt="\\ud800-\\udfff",yt="\\u0300-\\u036f\\ufe20-\\ufe2f\\u20d0-\\u20ff",bt="\\u2700-\\u27bf",kt="a-z\\xdf-\\xf6\\xf8-\\xff",Mt="A-Z\\xc0-\\xd6\\xd8-\\xde",St="\\ufe0e\\ufe0f",xt="\\xac\\xb1\\xd7\\xf7\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf\\u2000-\\u206f \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000",At="["+vt+"]",$t="["+xt+"]",zt="["+yt+"]",Ct="\\d+",Tt="["+bt+"]",Et="["+kt+"]",Ot="[^"+vt+xt+Ct+bt+kt+Mt+"]",It="\\ud83c[\\udffb-\\udfff]",jt="[^"+vt+"]",Pt="(?:\\ud83c[\\udde6-\\uddff]){2}",Rt="[\\ud800-\\udbff][\\udc00-\\udfff]",Dt="["+Mt+"]",_t="\\u200d",Lt="(?:"+Et+"|"+Ot+")",Bt="(?:"+Dt+"|"+Ot+")",Ft="(?:['’](?:d|ll|m|re|s|t|ve))?",Nt="(?:['’](?:D|LL|M|RE|S|T|VE))?",Wt="(?:"+zt+"|"+It+")?",Ut="["+St+"]?",Kt=Ut+Wt+"(?:"+_t+"(?:"+[jt,Pt,Rt].join("|")+")"+Ut+Wt+")*",Ht="(?:"+[Tt,Pt,Rt].join("|")+")"+Kt,Vt="(?:"+[jt+zt+"?",zt,Pt,Rt,At].join("|")+")",Gt=RegExp("['’]","g"),Xt=RegExp(zt,"g"),Yt=RegExp(It+"(?="+It+")|"+Vt+Kt,"g"),qt=RegExp([Dt+"?"+Et+"+"+Ft+"(?="+[$t,Dt,"$"].join("|")+")",Bt+"+"+Nt+"(?="+[$t,Dt+Lt,"$"].join("|")+")",Dt+"?"+Lt+"+"+Ft,Dt+"+"+Nt,"\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])","\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])",Ct,Ht].join("|"),"g"),Jt=RegExp("["+_t+vt+yt+St+"]"),Qt=/[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/,Zt=["Array","Buffer","DataView","Date","Error","Float32Array","Float64Array","Function","Int8Array","Int16Array","Int32Array","Map","Math","Object","Promise","RegExp","Set","String","Symbol","TypeError","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","WeakMap","_","clearTimeout","isFinite","parseInt","setTimeout"],te=-1,ee={};ee[E]=ee[O]=ee[I]=ee[j]=ee[P]=ee[R]=ee[D]=ee[_]=ee[L]=!0,ee[c]=ee[f]=ee[C]=ee[d]=ee[T]=ee[g]=ee[m]=ee[w]=ee[y]=ee[b]=ee[k]=ee[S]=ee[x]=ee[A]=ee[z]=!1;var ie={};ie[c]=ie[f]=ie[C]=ie[T]=ie[d]=ie[g]=ie[E]=ie[O]=ie[I]=ie[j]=ie[P]=ie[y]=ie[b]=ie[k]=ie[S]=ie[x]=ie[A]=ie[$]=ie[R]=ie[D]=ie[_]=ie[L]=!0,ie[m]=ie[w]=ie[z]=!1;var ne={"\\":"\\","'":"'","\n":"n","\r":"r","\u2028":"u2028","\u2029":"u2029"},re=parseFloat,se=parseInt,oe="object"==typeof p&&p&&p.Object===Object&&p,he="object"==typeof self&&self&&self.Object===Object&&self,ae=oe||he||Function("return this")(),le=Dh&&!Dh.nodeType&&Dh,ue=le&&Rh&&!Rh.nodeType&&Rh,ce=ue&&ue.exports===le,fe=ce&&oe.process,de=function(){try{return ue&&ue.require&&ue.require("util").types||fe&&fe.binding&&fe.binding("util")}catch(t){}}(),pe=de&&de.isArrayBuffer,ge=de&&de.isDate,me=de&&de.isMap,we=de&&de.isRegExp,ve=de&&de.isSet,ye=de&&de.isTypedArray;function be(t,e,i){switch(i.length){case 0:return t.call(e);case 1:return t.call(e,i[0]);case 2:return t.call(e,i[0],i[1]);case 3:return t.call(e,i[0],i[1],i[2])}return t.apply(e,i)}function ke(t,e,i,n){for(var r=-1,s=null==t?0:t.length;++r<s;){var o=t[r];e(n,o,i(o),t)}return n}function Me(t,e){for(var i=-1,n=null==t?0:t.length;++i<n&&!1!==e(t[i],i,t););return t}function Se(t,e){for(var i=null==t?0:t.length;i--&&!1!==e(t[i],i,t););return t}function xe(t,e){for(var i=-1,n=null==t?0:t.length;++i<n;)if(!e(t[i],i,t))return!1;return!0}function Ae(t,e){for(var i=-1,n=null==t?0:t.length,r=0,s=[];++i<n;){var o=t[i];e(o,i,t)&&(s[r++]=o)}return s}function $e(t,e){return!(null==t||!t.length)&&De(t,e,0)>-1}function ze(t,e,i){for(var n=-1,r=null==t?0:t.length;++n<r;)if(i(e,t[n]))return!0;return!1}function Ce(t,e){for(var i=-1,n=null==t?0:t.length,r=Array(n);++i<n;)r[i]=e(t[i],i,t);return r}function Te(t,e){for(var i=-1,n=e.length,r=t.length;++i<n;)t[r+i]=e[i];return t}function Ee(t,e,i,n){var r=-1,s=null==t?0:t.length;for(n&&s&&(i=t[++r]);++r<s;)i=e(i,t[r],r,t);return i}function Oe(t,e,i,n){var r=null==t?0:t.length;for(n&&r&&(i=t[--r]);r--;)i=e(i,t[r],r,t);return i}function Ie(t,e){for(var i=-1,n=null==t?0:t.length;++i<n;)if(e(t[i],i,t))return!0;return!1}var je=Fe("length");function Pe(t,e,i){var n;return i(t,(function(t,i,r){if(e(t,i,r))return n=i,!1})),n}function Re(t,e,i,n){for(var r=t.length,s=i+(n?1:-1);n?s--:++s<r;)if(e(t[s],s,t))return s;return-1}function De(t,e,i){return e==e?function(t,e,i){for(var n=i-1,r=t.length;++n<r;)if(t[n]===e)return n;return-1}(t,e,i):Re(t,Le,i)}function _e(t,e,i,n){for(var r=i-1,s=t.length;++r<s;)if(n(t[r],e))return r;return-1}function Le(t){return t!=t}function Be(t,e){var i=null==t?0:t.length;return i?Ue(t,e)/i:a}function Fe(e){return function(i){return null==i?t:i[e]}}function Ne(e){return function(i){return null==e?t:e[i]}}function We(t,e,i,n,r){return r(t,(function(t,r,s){i=n?(n=!1,t):e(i,t,r,s)})),i}function Ue(e,i){for(var n,r=-1,s=e.length;++r<s;){var o=i(e[r]);o!==t&&(n=n===t?o:n+o)}return n}function Ke(t,e){for(var i=-1,n=Array(t);++i<t;)n[i]=e(i);return n}function He(t){return t?t.slice(0,ai(t)+1).replace(tt,""):t}function Ve(t){return function(e){return t(e)}}function Ge(t,e){return Ce(e,(function(e){return t[e]}))}function Xe(t,e){return t.has(e)}function Ye(t,e){for(var i=-1,n=t.length;++i<n&&De(e,t[i],0)>-1;);return i}function qe(t,e){for(var i=t.length;i--&&De(e,t[i],0)>-1;);return i}var Je=Ne({À:"A",Á:"A",Â:"A",Ã:"A",Ä:"A",Å:"A",à:"a",á:"a",â:"a",ã:"a",ä:"a",å:"a",Ç:"C",ç:"c",Ð:"D",ð:"d",È:"E",É:"E",Ê:"E",Ë:"E",è:"e",é:"e",ê:"e",ë:"e",Ì:"I",Í:"I",Î:"I",Ï:"I",ì:"i",í:"i",î:"i",ï:"i",Ñ:"N",ñ:"n",Ò:"O",Ó:"O",Ô:"O",Õ:"O",Ö:"O",Ø:"O",ò:"o",ó:"o",ô:"o",õ:"o",ö:"o",ø:"o",Ù:"U",Ú:"U",Û:"U",Ü:"U",ù:"u",ú:"u",û:"u",ü:"u",Ý:"Y",ý:"y",ÿ:"y",Æ:"Ae",æ:"ae",Þ:"Th",þ:"th",ß:"ss",Ā:"A",Ă:"A",Ą:"A",ā:"a",ă:"a",ą:"a",Ć:"C",Ĉ:"C",Ċ:"C",Č:"C",ć:"c",ĉ:"c",ċ:"c",č:"c",Ď:"D",Đ:"D",ď:"d",đ:"d",Ē:"E",Ĕ:"E",Ė:"E",Ę:"E",Ě:"E",ē:"e",ĕ:"e",ė:"e",ę:"e",ě:"e",Ĝ:"G",Ğ:"G",Ġ:"G",Ģ:"G",ĝ:"g",ğ:"g",ġ:"g",ģ:"g",Ĥ:"H",Ħ:"H",ĥ:"h",ħ:"h",Ĩ:"I",Ī:"I",Ĭ:"I",Į:"I",İ:"I",ĩ:"i",ī:"i",ĭ:"i",į:"i",ı:"i",Ĵ:"J",ĵ:"j",Ķ:"K",ķ:"k",ĸ:"k",Ĺ:"L",Ļ:"L",Ľ:"L",Ŀ:"L",Ł:"L",ĺ:"l",ļ:"l",ľ:"l",ŀ:"l",ł:"l",Ń:"N",Ņ:"N",Ň:"N",Ŋ:"N",ń:"n",ņ:"n",ň:"n",ŋ:"n",Ō:"O",Ŏ:"O",Ő:"O",ō:"o",ŏ:"o",ő:"o",Ŕ:"R",Ŗ:"R",Ř:"R",ŕ:"r",ŗ:"r",ř:"r",Ś:"S",Ŝ:"S",Ş:"S",Š:"S",ś:"s",ŝ:"s",ş:"s",š:"s",Ţ:"T",Ť:"T",Ŧ:"T",ţ:"t",ť:"t",ŧ:"t",Ũ:"U",Ū:"U",Ŭ:"U",Ů:"U",Ű:"U",Ų:"U",ũ:"u",ū:"u",ŭ:"u",ů:"u",ű:"u",ų:"u",Ŵ:"W",ŵ:"w",Ŷ:"Y",ŷ:"y",Ÿ:"Y",Ź:"Z",Ż:"Z",Ž:"Z",ź:"z",ż:"z",ž:"z",IJ:"IJ",ij:"ij",Œ:"Oe",œ:"oe",ʼn:"'n",ſ:"s"}),Qe=Ne({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"});function Ze(t){return"\\"+ne[t]}function ti(t){return Jt.test(t)}function ei(t){var e=-1,i=Array(t.size);return t.forEach((function(t,n){i[++e]=[n,t]})),i}function ii(t,e){return function(i){return t(e(i))}}function ni(t,e){for(var i=-1,r=t.length,s=0,o=[];++i<r;){var h=t[i];h!==e&&h!==n||(t[i]=n,o[s++]=i)}return o}function ri(t){var e=-1,i=Array(t.size);return t.forEach((function(t){i[++e]=t})),i}function si(t){var e=-1,i=Array(t.size);return t.forEach((function(t){i[++e]=[t,t]})),i}function oi(t){return ti(t)?function(t){for(var e=Yt.lastIndex=0;Yt.test(t);)++e;return e}(t):je(t)}function hi(t){return ti(t)?function(t){return t.match(Yt)||[]}(t):function(t){return t.split("")}(t)}function ai(t){for(var e=t.length;e--&&et.test(t.charAt(e)););return e}var li=Ne({"&amp;":"&","&lt;":"<","&gt;":">","&quot;":'"',"&#39;":"'"}),ui=function p(et){var vt,yt=(et=null==et?ae:ui.defaults(ae.Object(),et,ui.pick(ae,Zt))).Array,bt=et.Date,kt=et.Error,Mt=et.Function,St=et.Math,xt=et.Object,At=et.RegExp,$t=et.String,zt=et.TypeError,Ct=yt.prototype,Tt=xt.prototype,Et=et["__core-js_shared__"],Ot=Mt.prototype.toString,It=Tt.hasOwnProperty,jt=0,Pt=(vt=/[^.]+$/.exec(Et&&Et.keys&&Et.keys.IE_PROTO||""))?"Symbol(src)_1."+vt:"",Rt=Tt.toString,Dt=Ot.call(xt),_t=ae._,Lt=At("^"+Ot.call(It).replace(Q,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),Bt=ce?et.Buffer:t,Ft=et.Symbol,Nt=et.Uint8Array,Wt=Bt?Bt.allocUnsafe:t,Ut=ii(xt.getPrototypeOf,xt),Kt=xt.create,Ht=Tt.propertyIsEnumerable,Vt=Ct.splice,Yt=Ft?Ft.isConcatSpreadable:t,Jt=Ft?Ft.iterator:t,ne=Ft?Ft.toStringTag:t,oe=function(){try{var t=hs(xt,"defineProperty");return t({},"",{}),t}catch(t){}}(),he=et.clearTimeout!==ae.clearTimeout&&et.clearTimeout,le=bt&&bt.now!==ae.Date.now&&bt.now,ue=et.setTimeout!==ae.setTimeout&&et.setTimeout,fe=St.ceil,de=St.floor,je=xt.getOwnPropertySymbols,Ne=Bt?Bt.isBuffer:t,ci=et.isFinite,fi=Ct.join,di=ii(xt.keys,xt),pi=St.max,gi=St.min,mi=bt.now,wi=et.parseInt,vi=St.random,yi=Ct.reverse,bi=hs(et,"DataView"),ki=hs(et,"Map"),Mi=hs(et,"Promise"),Si=hs(et,"Set"),xi=hs(et,"WeakMap"),Ai=hs(xt,"create"),$i=xi&&new xi,zi={},Ci=js(bi),Ti=js(ki),Ei=js(Mi),Oi=js(Si),Ii=js(xi),ji=Ft?Ft.prototype:t,Pi=ji?ji.valueOf:t,Ri=ji?ji.toString:t;function Di(t){if(Jo(t)&&!Fo(t)&&!(t instanceof Fi)){if(t instanceof Bi)return t;if(It.call(t,"__wrapped__"))return Ps(t)}return new Bi(t)}var _i=function(){function e(){}return function(i){if(!qo(i))return{};if(Kt)return Kt(i);e.prototype=i;var n=new e;return e.prototype=t,n}}();function Li(){}function Bi(e,i){this.__wrapped__=e,this.__actions__=[],this.__chain__=!!i,this.__index__=0,this.__values__=t}function Fi(t){this.__wrapped__=t,this.__actions__=[],this.__dir__=1,this.__filtered__=!1,this.__iteratees__=[],this.__takeCount__=l,this.__views__=[]}function Ni(t){var e=-1,i=null==t?0:t.length;for(this.clear();++e<i;){var n=t[e];this.set(n[0],n[1])}}function Wi(t){var e=-1,i=null==t?0:t.length;for(this.clear();++e<i;){var n=t[e];this.set(n[0],n[1])}}function Ui(t){var e=-1,i=null==t?0:t.length;for(this.clear();++e<i;){var n=t[e];this.set(n[0],n[1])}}function Ki(t){var e=-1,i=null==t?0:t.length;for(this.__data__=new Ui;++e<i;)this.add(t[e])}function Hi(t){var e=this.__data__=new Wi(t);this.size=e.size}function Vi(t,e){var i=Fo(t),n=!i&&Bo(t),r=!i&&!n&&Ko(t),s=!i&&!n&&!r&&sh(t),o=i||n||r||s,h=o?Ke(t.length,$t):[],a=h.length;for(var l in t)!e&&!It.call(t,l)||o&&("length"==l||r&&("offset"==l||"parent"==l)||s&&("buffer"==l||"byteLength"==l||"byteOffset"==l)||ps(l,a))||h.push(l);return h}function Gi(e){var i=e.length;return i?e[Kn(0,i-1)]:t}function Xi(t,e){return Es(Ar(t),rn(e,0,t.length))}function Yi(t){return Es(Ar(t))}function qi(e,i,n){(n!==t&&!Do(e[i],n)||n===t&&!(i in e))&&en(e,i,n)}function Ji(e,i,n){var r=e[i];It.call(e,i)&&Do(r,n)&&(n!==t||i in e)||en(e,i,n)}function Qi(t,e){for(var i=t.length;i--;)if(Do(t[i][0],e))return i;return-1}function Zi(t,e,i,n){return ln(t,(function(t,r,s){e(n,t,i(t),s)})),n}function tn(t,e){return t&&$r(e,zh(e),t)}function en(t,e,i){"__proto__"==e&&oe?oe(t,e,{configurable:!0,enumerable:!0,value:i,writable:!0}):t[e]=i}function nn(e,i){for(var n=-1,r=i.length,s=yt(r),o=null==e;++n<r;)s[n]=o?t:Mh(e,i[n]);return s}function rn(e,i,n){return e==e&&(n!==t&&(e=e<=n?e:n),i!==t&&(e=e>=i?e:i)),e}function sn(e,i,n,r,s,o){var h,a=1&i,l=2&i,u=4&i;if(n&&(h=s?n(e,r,s,o):n(e)),h!==t)return h;if(!qo(e))return e;var f=Fo(e);if(f){if(h=function(t){var e=t.length,i=new t.constructor(e);return e&&"string"==typeof t[0]&&It.call(t,"index")&&(i.index=t.index,i.input=t.input),i}(e),!a)return Ar(e,h)}else{var p=us(e),m=p==w||p==v;if(Ko(e))return yr(e,a);if(p==k||p==c||m&&!s){if(h=l||m?{}:fs(e),!a)return l?function(t,e){return $r(t,ls(t),e)}(e,function(t,e){return t&&$r(e,Ch(e),t)}(h,e)):function(t,e){return $r(t,as(t),e)}(e,tn(h,e))}else{if(!ie[p])return s?e:{};h=function(t,e,i){var n=t.constructor;switch(e){case C:return br(t);case d:case g:return new n(+t);case T:return function(t,e){var i=e?br(t.buffer):t.buffer;return new t.constructor(i,t.byteOffset,t.byteLength)}(t,i);case E:case O:case I:case j:case P:case R:case D:case _:case L:return kr(t,i);case y:return new n;case b:case A:return new n(t);case S:return function(t){var e=new t.constructor(t.source,lt.exec(t));return e.lastIndex=t.lastIndex,e}(t);case x:return new n;case $:return Pi?xt(Pi.call(t)):{}}}(e,p,a)}}o||(o=new Hi);var M=o.get(e);if(M)return M;o.set(e,h),ih(e)?e.forEach((function(t){h.add(sn(t,i,n,t,e,o))})):Qo(e)&&e.forEach((function(t,r){h.set(r,sn(t,i,n,r,e,o))}));var z=f?t:(u?l?ts:Zr:l?Ch:zh)(e);return Me(z||e,(function(t,r){z&&(t=e[r=t]),Ji(h,r,sn(t,i,n,r,e,o))})),h}function on(e,i,n){var r=n.length;if(null==e)return!r;for(e=xt(e);r--;){var s=n[r],o=e[s];if(o===t&&!(s in e)||!(0,i[s])(o))return!1}return!0}function hn(i,n,r){if("function"!=typeof i)throw new zt(e);return $s((function(){i.apply(t,r)}),n)}function an(t,e,i,n){var r=-1,s=$e,o=!0,h=t.length,a=[],l=e.length;if(!h)return a;i&&(e=Ce(e,Ve(i))),n?(s=ze,o=!1):e.length>=200&&(s=Xe,o=!1,e=new Ki(e));t:for(;++r<h;){var u=t[r],c=null==i?u:i(u);if(u=n||0!==u?u:0,o&&c==c){for(var f=l;f--;)if(e[f]===c)continue t;a.push(u)}else s(e,c,n)||a.push(u)}return a}Di.templateSettings={escape:V,evaluate:G,interpolate:X,variable:"",imports:{_:Di}},(Di.prototype=Li.prototype).constructor=Di,(Bi.prototype=_i(Li.prototype)).constructor=Bi,(Fi.prototype=_i(Li.prototype)).constructor=Fi,Ni.prototype.clear=function(){this.__data__=Ai?Ai(null):{},this.size=0},Ni.prototype.delete=function(t){var e=this.has(t)&&delete this.__data__[t];return this.size-=e?1:0,e},Ni.prototype.get=function(e){var n=this.__data__;if(Ai){var r=n[e];return r===i?t:r}return It.call(n,e)?n[e]:t},Ni.prototype.has=function(e){var i=this.__data__;return Ai?i[e]!==t:It.call(i,e)},Ni.prototype.set=function(e,n){var r=this.__data__;return this.size+=this.has(e)?0:1,r[e]=Ai&&n===t?i:n,this},Wi.prototype.clear=function(){this.__data__=[],this.size=0},Wi.prototype.delete=function(t){var e=this.__data__,i=Qi(e,t);return!(i<0||(i==e.length-1?e.pop():Vt.call(e,i,1),--this.size,0))},Wi.prototype.get=function(e){var i=this.__data__,n=Qi(i,e);return n<0?t:i[n][1]},Wi.prototype.has=function(t){return Qi(this.__data__,t)>-1},Wi.prototype.set=function(t,e){var i=this.__data__,n=Qi(i,t);return n<0?(++this.size,i.push([t,e])):i[n][1]=e,this},Ui.prototype.clear=function(){this.size=0,this.__data__={hash:new Ni,map:new(ki||Wi),string:new Ni}},Ui.prototype.delete=function(t){var e=ss(this,t).delete(t);return this.size-=e?1:0,e},Ui.prototype.get=function(t){return ss(this,t).get(t)},Ui.prototype.has=function(t){return ss(this,t).has(t)},Ui.prototype.set=function(t,e){var i=ss(this,t),n=i.size;return i.set(t,e),this.size+=i.size==n?0:1,this},Ki.prototype.add=Ki.prototype.push=function(t){return this.__data__.set(t,i),this},Ki.prototype.has=function(t){return this.__data__.has(t)},Hi.prototype.clear=function(){this.__data__=new Wi,this.size=0},Hi.prototype.delete=function(t){var e=this.__data__,i=e.delete(t);return this.size=e.size,i},Hi.prototype.get=function(t){return this.__data__.get(t)},Hi.prototype.has=function(t){return this.__data__.has(t)},Hi.prototype.set=function(t,e){var i=this.__data__;if(i instanceof Wi){var n=i.__data__;if(!ki||n.length<199)return n.push([t,e]),this.size=++i.size,this;i=this.__data__=new Ui(n)}return i.set(t,e),this.size=i.size,this};var ln=Tr(wn),un=Tr(vn,!0);function cn(t,e){var i=!0;return ln(t,(function(t,n,r){return i=!!e(t,n,r)})),i}function fn(e,i,n){for(var r=-1,s=e.length;++r<s;){var o=e[r],h=i(o);if(null!=h&&(a===t?h==h&&!rh(h):n(h,a)))var a=h,l=o}return l}function dn(t,e){var i=[];return ln(t,(function(t,n,r){e(t,n,r)&&i.push(t)})),i}function pn(t,e,i,n,r){var s=-1,o=t.length;for(i||(i=ds),r||(r=[]);++s<o;){var h=t[s];e>0&&i(h)?e>1?pn(h,e-1,i,n,r):Te(r,h):n||(r[r.length]=h)}return r}var gn=Er(),mn=Er(!0);function wn(t,e){return t&&gn(t,e,zh)}function vn(t,e){return t&&mn(t,e,zh)}function yn(t,e){return Ae(e,(function(e){return Go(t[e])}))}function bn(e,i){for(var n=0,r=(i=gr(i,e)).length;null!=e&&n<r;)e=e[Is(i[n++])];return n&&n==r?e:t}function kn(t,e,i){var n=e(t);return Fo(t)?n:Te(n,i(t))}function Mn(e){return null==e?e===t?"[object Undefined]":"[object Null]":ne&&ne in xt(e)?function(e){var i=It.call(e,ne),n=e[ne];try{e[ne]=t;var r=!0}catch(t){}var s=Rt.call(e);return r&&(i?e[ne]=n:delete e[ne]),s}(e):function(t){return Rt.call(t)}(e)}function Sn(t,e){return t>e}function xn(t,e){return null!=t&&It.call(t,e)}function An(t,e){return null!=t&&e in xt(t)}function $n(e,i,n){for(var r=n?ze:$e,s=e[0].length,o=e.length,h=o,a=yt(o),l=1/0,u=[];h--;){var c=e[h];h&&i&&(c=Ce(c,Ve(i))),l=gi(c.length,l),a[h]=!n&&(i||s>=120&&c.length>=120)?new Ki(h&&c):t}c=e[0];var f=-1,d=a[0];t:for(;++f<s&&u.length<l;){var p=c[f],g=i?i(p):p;if(p=n||0!==p?p:0,!(d?Xe(d,g):r(u,g,n))){for(h=o;--h;){var m=a[h];if(!(m?Xe(m,g):r(e[h],g,n)))continue t}d&&d.push(g),u.push(p)}}return u}function zn(e,i,n){var r=null==(e=Ss(e,i=gr(i,e)))?e:e[Is(Hs(i))];return null==r?t:be(r,e,n)}function Cn(t){return Jo(t)&&Mn(t)==c}function Tn(e,i,n,r,s){return e===i||(null==e||null==i||!Jo(e)&&!Jo(i)?e!=e&&i!=i:function(e,i,n,r,s,o){var h=Fo(e),a=Fo(i),l=h?f:us(e),u=a?f:us(i),p=(l=l==c?k:l)==k,w=(u=u==c?k:u)==k,v=l==u;if(v&&Ko(e)){if(!Ko(i))return!1;h=!0,p=!1}if(v&&!p)return o||(o=new Hi),h||sh(e)?Jr(e,i,n,r,s,o):function(t,e,i,n,r,s,o){switch(i){case T:if(t.byteLength!=e.byteLength||t.byteOffset!=e.byteOffset)return!1;t=t.buffer,e=e.buffer;case C:return!(t.byteLength!=e.byteLength||!s(new Nt(t),new Nt(e)));case d:case g:case b:return Do(+t,+e);case m:return t.name==e.name&&t.message==e.message;case S:case A:return t==e+"";case y:var h=ei;case x:if(h||(h=ri),t.size!=e.size&&!(1&n))return!1;var a=o.get(t);if(a)return a==e;n|=2,o.set(t,e);var l=Jr(h(t),h(e),n,r,s,o);return o.delete(t),l;case $:if(Pi)return Pi.call(t)==Pi.call(e)}return!1}(e,i,l,n,r,s,o);if(!(1&n)){var M=p&&It.call(e,"__wrapped__"),z=w&&It.call(i,"__wrapped__");if(M||z){var E=M?e.value():e,O=z?i.value():i;return o||(o=new Hi),s(E,O,n,r,o)}}return!!v&&(o||(o=new Hi),function(e,i,n,r,s,o){var h=1&n,a=Zr(e),l=a.length;if(l!=Zr(i).length&&!h)return!1;for(var u=l;u--;){var c=a[u];if(!(h?c in i:It.call(i,c)))return!1}var f=o.get(e),d=o.get(i);if(f&&d)return f==i&&d==e;var p=!0;o.set(e,i),o.set(i,e);for(var g=h;++u<l;){var m=e[c=a[u]],w=i[c];if(r)var v=h?r(w,m,c,i,e,o):r(m,w,c,e,i,o);if(!(v===t?m===w||s(m,w,n,r,o):v)){p=!1;break}g||(g="constructor"==c)}if(p&&!g){var y=e.constructor,b=i.constructor;y==b||!("constructor"in e)||!("constructor"in i)||"function"==typeof y&&y instanceof y&&"function"==typeof b&&b instanceof b||(p=!1)}return o.delete(e),o.delete(i),p}(e,i,n,r,s,o))}(e,i,n,r,Tn,s))}function En(e,i,n,r){var s=n.length,o=s,h=!r;if(null==e)return!o;for(e=xt(e);s--;){var a=n[s];if(h&&a[2]?a[1]!==e[a[0]]:!(a[0]in e))return!1}for(;++s<o;){var l=(a=n[s])[0],u=e[l],c=a[1];if(h&&a[2]){if(u===t&&!(l in e))return!1}else{var f=new Hi;if(r)var d=r(u,c,l,e,i,f);if(!(d===t?Tn(c,u,3,r,f):d))return!1}}return!0}function On(t){return!(!qo(t)||(e=t,Pt&&Pt in e))&&(Go(t)?Lt:ft).test(js(t));var e}function In(t){return"function"==typeof t?t:null==t?Zh:"object"==typeof t?Fo(t)?_n(t[0],t[1]):Dn(t):aa(t)}function jn(t){if(!ys(t))return di(t);var e=[];for(var i in xt(t))It.call(t,i)&&"constructor"!=i&&e.push(i);return e}function Pn(t,e){return t<e}function Rn(t,e){var i=-1,n=Wo(t)?yt(t.length):[];return ln(t,(function(t,r,s){n[++i]=e(t,r,s)})),n}function Dn(t){var e=os(t);return 1==e.length&&e[0][2]?ks(e[0][0],e[0][1]):function(i){return i===t||En(i,t,e)}}function _n(e,i){return ms(e)&&bs(i)?ks(Is(e),i):function(n){var r=Mh(n,e);return r===t&&r===i?Sh(n,e):Tn(i,r,3)}}function Ln(e,i,n,r,s){e!==i&&gn(i,(function(o,h){if(s||(s=new Hi),qo(o))!function(e,i,n,r,s,o,h){var a=xs(e,n),l=xs(i,n),u=h.get(l);if(u)qi(e,n,u);else{var c=o?o(a,l,n+"",e,i,h):t,f=c===t;if(f){var d=Fo(l),p=!d&&Ko(l),g=!d&&!p&&sh(l);c=l,d||p||g?Fo(a)?c=a:Uo(a)?c=Ar(a):p?(f=!1,c=yr(l,!0)):g?(f=!1,c=kr(l,!0)):c=[]:th(l)||Bo(l)?(c=a,Bo(a)?c=dh(a):qo(a)&&!Go(a)||(c=fs(l))):f=!1}f&&(h.set(l,c),s(c,l,r,o,h),h.delete(l)),qi(e,n,c)}}(e,i,h,n,Ln,r,s);else{var a=r?r(xs(e,h),o,h+"",e,i,s):t;a===t&&(a=o),qi(e,h,a)}}),Ch)}function Bn(e,i){var n=e.length;if(n)return ps(i+=i<0?n:0,n)?e[i]:t}function Fn(t,e,i){e=e.length?Ce(e,(function(t){return Fo(t)?function(e){return bn(e,1===t.length?t[0]:t)}:t})):[Zh];var n=-1;e=Ce(e,Ve(rs()));var r=Rn(t,(function(t){var i=Ce(e,(function(e){return e(t)}));return{criteria:i,index:++n,value:t}}));return function(t){var e=t.length;for(t.sort((function(t,e){return function(t,e,i){for(var n=-1,r=t.criteria,s=e.criteria,o=r.length,h=i.length;++n<o;){var a=Mr(r[n],s[n]);if(a)return n>=h?a:a*("desc"==i[n]?-1:1)}return t.index-e.index}(t,e,i)}));e--;)t[e]=t[e].value;return t}(r)}function Nn(t,e,i){for(var n=-1,r=e.length,s={};++n<r;){var o=e[n],h=bn(t,o);i(h,o)&&Yn(s,gr(o,t),h)}return s}function Wn(t,e,i,n){var r=n?_e:De,s=-1,o=e.length,h=t;for(t===e&&(e=Ar(e)),i&&(h=Ce(t,Ve(i)));++s<o;)for(var a=0,l=e[s],u=i?i(l):l;(a=r(h,u,a,n))>-1;)h!==t&&Vt.call(h,a,1),Vt.call(t,a,1);return t}function Un(t,e){for(var i=t?e.length:0,n=i-1;i--;){var r=e[i];if(i==n||r!==s){var s=r;ps(r)?Vt.call(t,r,1):hr(t,r)}}return t}function Kn(t,e){return t+de(vi()*(e-t+1))}function Hn(t,e){var i="";if(!t||e<1||e>h)return i;do{e%2&&(i+=t),(e=de(e/2))&&(t+=t)}while(e);return i}function Vn(t,e){return zs(Ms(t,e,Zh),t+"")}function Gn(t){return Gi(Dh(t))}function Xn(t,e){var i=Dh(t);return Es(i,rn(e,0,i.length))}function Yn(e,i,n,r){if(!qo(e))return e;for(var s=-1,o=(i=gr(i,e)).length,h=o-1,a=e;null!=a&&++s<o;){var l=Is(i[s]),u=n;if("__proto__"===l||"constructor"===l||"prototype"===l)return e;if(s!=h){var c=a[l];(u=r?r(c,l,a):t)===t&&(u=qo(c)?c:ps(i[s+1])?[]:{})}Ji(a,l,u),a=a[l]}return e}var qn=$i?function(t,e){return $i.set(t,e),t}:Zh,Jn=oe?function(t,e){return oe(t,"toString",{configurable:!0,enumerable:!1,value:qh(e),writable:!0})}:Zh;function Qn(t){return Es(Dh(t))}function Zn(t,e,i){var n=-1,r=t.length;e<0&&(e=-e>r?0:r+e),(i=i>r?r:i)<0&&(i+=r),r=e>i?0:i-e>>>0,e>>>=0;for(var s=yt(r);++n<r;)s[n]=t[n+e];return s}function tr(t,e){var i;return ln(t,(function(t,n,r){return!(i=e(t,n,r))})),!!i}function er(t,e,i){var n=0,r=null==t?n:t.length;if("number"==typeof e&&e==e&&r<=2147483647){for(;n<r;){var s=n+r>>>1,o=t[s];null!==o&&!rh(o)&&(i?o<=e:o<e)?n=s+1:r=s}return r}return ir(t,e,Zh,i)}function ir(e,i,n,r){var s=0,o=null==e?0:e.length;if(0===o)return 0;for(var h=(i=n(i))!=i,a=null===i,l=rh(i),u=i===t;s<o;){var c=de((s+o)/2),f=n(e[c]),d=f!==t,p=null===f,g=f==f,m=rh(f);if(h)var w=r||g;else w=u?g&&(r||d):a?g&&d&&(r||!p):l?g&&d&&!p&&(r||!m):!p&&!m&&(r?f<=i:f<i);w?s=c+1:o=c}return gi(o,4294967294)}function nr(t,e){for(var i=-1,n=t.length,r=0,s=[];++i<n;){var o=t[i],h=e?e(o):o;if(!i||!Do(h,a)){var a=h;s[r++]=0===o?0:o}}return s}function rr(t){return"number"==typeof t?t:rh(t)?a:+t}function sr(t){if("string"==typeof t)return t;if(Fo(t))return Ce(t,sr)+"";if(rh(t))return Ri?Ri.call(t):"";var e=t+"";return"0"==e&&1/t==-1/0?"-0":e}function or(t,e,i){var n=-1,r=$e,s=t.length,o=!0,h=[],a=h;if(i)o=!1,r=ze;else if(s>=200){var l=e?null:Hr(t);if(l)return ri(l);o=!1,r=Xe,a=new Ki}else a=e?[]:h;t:for(;++n<s;){var u=t[n],c=e?e(u):u;if(u=i||0!==u?u:0,o&&c==c){for(var f=a.length;f--;)if(a[f]===c)continue t;e&&a.push(c),h.push(u)}else r(a,c,i)||(a!==h&&a.push(c),h.push(u))}return h}function hr(t,e){var i=-1,n=(e=gr(e,t)).length;if(!n)return!0;for(;++i<n;){var r=Is(e[i]);if("__proto__"===r&&!It.call(t,"__proto__"))return!1;if(("constructor"===r||"prototype"===r)&&i<n-1)return!1}var s=Ss(t,e);return null==s||delete s[Is(Hs(e))]}function ar(t,e,i,n){return Yn(t,e,i(bn(t,e)),n)}function lr(t,e,i,n){for(var r=t.length,s=n?r:-1;(n?s--:++s<r)&&e(t[s],s,t););return i?Zn(t,n?0:s,n?s+1:r):Zn(t,n?s+1:0,n?r:s)}function ur(t,e){var i=t;return i instanceof Fi&&(i=i.value()),Ee(e,(function(t,e){return e.func.apply(e.thisArg,Te([t],e.args))}),i)}function cr(t,e,i){var n=t.length;if(n<2)return n?or(t[0]):[];for(var r=-1,s=yt(n);++r<n;)for(var o=t[r],h=-1;++h<n;)h!=r&&(s[r]=an(s[r]||o,t[h],e,i));return or(pn(s,1),e,i)}function fr(e,i,n){for(var r=-1,s=e.length,o=i.length,h={};++r<s;)n(h,e[r],r<o?i[r]:t);return h}function dr(t){return Uo(t)?t:[]}function pr(t){return"function"==typeof t?t:Zh}function gr(t,e){return Fo(t)?t:ms(t,e)?[t]:Os(ph(t))}var mr=Vn;function wr(e,i,n){var r=e.length;return n=n===t?r:n,!i&&n>=r?e:Zn(e,i,n)}var vr=he||function(t){return ae.clearTimeout(t)};function yr(t,e){if(e)return t.slice();var i=t.length,n=Wt?Wt(i):new t.constructor(i);return t.copy(n),n}function br(t){var e=new t.constructor(t.byteLength);return new Nt(e).set(new Nt(t)),e}function kr(t,e){var i=e?br(t.buffer):t.buffer;return new t.constructor(i,t.byteOffset,t.length)}function Mr(e,i){if(e!==i){var n=e!==t,r=null===e,s=e==e,o=rh(e),h=i!==t,a=null===i,l=i==i,u=rh(i);if(!a&&!u&&!o&&e>i||o&&h&&l&&!a&&!u||r&&h&&l||!n&&l||!s)return 1;if(!r&&!o&&!u&&e<i||u&&n&&s&&!r&&!o||a&&n&&s||!h&&s||!l)return-1}return 0}function Sr(t,e,i,n){for(var r=-1,s=t.length,o=i.length,h=-1,a=e.length,l=pi(s-o,0),u=yt(a+l),c=!n;++h<a;)u[h]=e[h];for(;++r<o;)(c||r<s)&&(u[i[r]]=t[r]);for(;l--;)u[h++]=t[r++];return u}function xr(t,e,i,n){for(var r=-1,s=t.length,o=-1,h=i.length,a=-1,l=e.length,u=pi(s-h,0),c=yt(u+l),f=!n;++r<u;)c[r]=t[r];for(var d=r;++a<l;)c[d+a]=e[a];for(;++o<h;)(f||r<s)&&(c[d+i[o]]=t[r++]);return c}function Ar(t,e){var i=-1,n=t.length;for(e||(e=yt(n));++i<n;)e[i]=t[i];return e}function $r(e,i,n,r){var s=!n;n||(n={});for(var o=-1,h=i.length;++o<h;){var a=i[o],l=r?r(n[a],e[a],a,n,e):t;l===t&&(l=e[a]),s?en(n,a,l):Ji(n,a,l)}return n}function zr(t,e){return function(i,n){var r=Fo(i)?ke:Zi,s=e?e():{};return r(i,t,rs(n,2),s)}}function Cr(e){return Vn((function(i,n){var r=-1,s=n.length,o=s>1?n[s-1]:t,h=s>2?n[2]:t;for(o=e.length>3&&"function"==typeof o?(s--,o):t,h&&gs(n[0],n[1],h)&&(o=s<3?t:o,s=1),i=xt(i);++r<s;){var a=n[r];a&&e(i,a,r,o)}return i}))}function Tr(t,e){return function(i,n){if(null==i)return i;if(!Wo(i))return t(i,n);for(var r=i.length,s=e?r:-1,o=xt(i);(e?s--:++s<r)&&!1!==n(o[s],s,o););return i}}function Er(t){return function(e,i,n){for(var r=-1,s=xt(e),o=n(e),h=o.length;h--;){var a=o[t?h:++r];if(!1===i(s[a],a,s))break}return e}}function Or(e){return function(i){var n=ti(i=ph(i))?hi(i):t,r=n?n[0]:i.charAt(0),s=n?wr(n,1).join(""):i.slice(1);return r[e]()+s}}function Ir(t){return function(e){return Ee(Gh(Bh(e).replace(Gt,"")),t,"")}}function jr(t){return function(){var e=arguments;switch(e.length){case 0:return new t;case 1:return new t(e[0]);case 2:return new t(e[0],e[1]);case 3:return new t(e[0],e[1],e[2]);case 4:return new t(e[0],e[1],e[2],e[3]);case 5:return new t(e[0],e[1],e[2],e[3],e[4]);case 6:return new t(e[0],e[1],e[2],e[3],e[4],e[5]);case 7:return new t(e[0],e[1],e[2],e[3],e[4],e[5],e[6])}var i=_i(t.prototype),n=t.apply(i,e);return qo(n)?n:i}}function Pr(e){return function(i,n,r){var s=xt(i);if(!Wo(i)){var o=rs(n,3);i=zh(i),n=function(t){return o(s[t],t,s)}}var h=e(i,n,r);return h>-1?s[o?i[h]:h]:t}}function Rr(i){return Qr((function(n){var r=n.length,s=r,o=Bi.prototype.thru;for(i&&n.reverse();s--;){var h=n[s];if("function"!=typeof h)throw new zt(e);if(o&&!a&&"wrapper"==is(h))var a=new Bi([],!0)}for(s=a?s:r;++s<r;){var l=is(h=n[s]),u="wrapper"==l?es(h):t;a=u&&ws(u[0])&&424==u[1]&&!u[4].length&&1==u[9]?a[is(u[0])].apply(a,u[3]):1==h.length&&ws(h)?a[l]():a.thru(h)}return function(){var t=arguments,e=t[0];if(a&&1==t.length&&Fo(e))return a.plant(e).value();for(var i=0,s=r?n[i].apply(this,t):e;++i<r;)s=n[i].call(this,s);return s}}))}function Dr(e,i,n,r,o,h,a,l,u,c){var f=i&s,d=1&i,p=2&i,g=24&i,m=512&i,w=p?t:jr(e);return function s(){for(var v=arguments.length,y=yt(v),b=v;b--;)y[b]=arguments[b];if(g)var k=ns(s),M=function(t,e){for(var i=t.length,n=0;i--;)t[i]===e&&++n;return n}(y,k);if(r&&(y=Sr(y,r,o,g)),h&&(y=xr(y,h,a,g)),v-=M,g&&v<c){var S=ni(y,k);return Ur(e,i,Dr,s.placeholder,n,y,S,l,u,c-v)}var x=d?n:this,A=p?x[e]:e;return v=y.length,l?y=function(e,i){for(var n=e.length,r=gi(i.length,n),s=Ar(e);r--;){var o=i[r];e[r]=ps(o,n)?s[o]:t}return e}(y,l):m&&v>1&&y.reverse(),f&&u<v&&(y.length=u),this&&this!==ae&&this instanceof s&&(A=w||jr(A)),A.apply(x,y)}}function _r(t,e){return function(i,n){return function(t,e,i,n){return wn(t,(function(t,r,s){e(n,i(t),r,s)})),n}(i,t,e(n),{})}}function Lr(e,i){return function(n,r){var s;if(n===t&&r===t)return i;if(n!==t&&(s=n),r!==t){if(s===t)return r;"string"==typeof n||"string"==typeof r?(n=sr(n),r=sr(r)):(n=rr(n),r=rr(r)),s=e(n,r)}return s}}function Br(t){return Qr((function(e){return e=Ce(e,Ve(rs())),Vn((function(i){var n=this;return t(e,(function(t){return be(t,n,i)}))}))}))}function Fr(e,i){var n=(i=i===t?" ":sr(i)).length;if(n<2)return n?Hn(i,e):i;var r=Hn(i,fe(e/oi(i)));return ti(i)?wr(hi(r),0,e).join(""):r.slice(0,e)}function Nr(e){return function(i,n,r){return r&&"number"!=typeof r&&gs(i,n,r)&&(n=r=t),i=lh(i),n===t?(n=i,i=0):n=lh(n),function(t,e,i,n){for(var r=-1,s=pi(fe((e-t)/(i||1)),0),o=yt(s);s--;)o[n?s:++r]=t,t+=i;return o}(i,n,r=r===t?i<n?1:-1:lh(r),e)}}function Wr(t){return function(e,i){return"string"==typeof e&&"string"==typeof i||(e=fh(e),i=fh(i)),t(e,i)}}function Ur(e,i,n,s,o,h,a,l,u,c){var f=8&i;i|=f?r:64,4&(i&=~(f?64:r))||(i&=-4);var d=[e,i,o,f?h:t,f?a:t,f?t:h,f?t:a,l,u,c],p=n.apply(t,d);return ws(e)&&As(p,d),p.placeholder=s,Cs(p,e,i)}function Kr(t){var e=St[t];return function(t,i){if(t=fh(t),(i=null==i?0:gi(uh(i),292))&&ci(t)){var n=(ph(t)+"e").split("e");return+((n=(ph(e(n[0]+"e"+(+n[1]+i)))+"e").split("e"))[0]+"e"+(+n[1]-i))}return e(t)}}var Hr=Si&&1/ri(new Si([,-0]))[1]==o?function(t){return new Si(t)}:ra;function Vr(t){return function(e){var i=us(e);return i==y?ei(e):i==x?si(e):function(t,e){return Ce(e,(function(e){return[e,t[e]]}))}(e,t(e))}}function Gr(i,o,h,a,l,u,c,f){var d=2&o;if(!d&&"function"!=typeof i)throw new zt(e);var p=a?a.length:0;if(p||(o&=-97,a=l=t),c=c===t?c:pi(uh(c),0),f=f===t?f:uh(f),p-=l?l.length:0,64&o){var g=a,m=l;a=l=t}var w=d?t:es(i),v=[i,o,h,a,l,g,m,u,c,f];if(w&&function(t,e){var i=t[1],r=e[1],o=i|r;if(!(o<131||(r==s&&8==i||r==s&&256==i&&t[7].length<=e[8]||384==r&&e[7].length<=e[8]&&8==i)))return t;1&r&&(t[2]=e[2],o|=1&i?0:4);var h=e[3];if(h){var a=t[3];t[3]=a?Sr(a,h,e[4]):h,t[4]=a?ni(t[3],n):e[4]}(h=e[5])&&(t[5]=(a=t[5])?xr(a,h,e[6]):h,t[6]=a?ni(t[5],n):e[6]),(h=e[7])&&(t[7]=h),r&s&&(t[8]=null==t[8]?e[8]:gi(t[8],e[8])),null==t[9]&&(t[9]=e[9]),t[0]=e[0],t[1]=o}(v,w),i=v[0],o=v[1],h=v[2],a=v[3],l=v[4],!(f=v[9]=v[9]===t?d?0:i.length:pi(v[9]-p,0))&&24&o&&(o&=-25),o&&1!=o)y=8==o||16==o?function(e,i,n){var r=jr(e);return function s(){for(var o=arguments.length,h=yt(o),a=o,l=ns(s);a--;)h[a]=arguments[a];var u=o<3&&h[0]!==l&&h[o-1]!==l?[]:ni(h,l);return(o-=u.length)<n?Ur(e,i,Dr,s.placeholder,t,h,u,t,t,n-o):be(this&&this!==ae&&this instanceof s?r:e,this,h)}}(i,o,f):o!=r&&33!=o||l.length?Dr.apply(t,v):function(t,e,i,n){var r=1&e,s=jr(t);return function e(){for(var o=-1,h=arguments.length,a=-1,l=n.length,u=yt(l+h),c=this&&this!==ae&&this instanceof e?s:t;++a<l;)u[a]=n[a];for(;h--;)u[a++]=arguments[++o];return be(c,r?i:this,u)}}(i,o,h,a);else var y=function(t,e,i){var n=1&e,r=jr(t);return function e(){return(this&&this!==ae&&this instanceof e?r:t).apply(n?i:this,arguments)}}(i,o,h);return Cs((w?qn:As)(y,v),i,o)}function Xr(e,i,n,r){return e===t||Do(e,Tt[n])&&!It.call(r,n)?i:e}function Yr(e,i,n,r,s,o){return qo(e)&&qo(i)&&(o.set(i,e),Ln(e,i,t,Yr,o),o.delete(i)),e}function qr(e){return th(e)?t:e}function Jr(e,i,n,r,s,o){var h=1&n,a=e.length,l=i.length;if(a!=l&&!(h&&l>a))return!1;var u=o.get(e),c=o.get(i);if(u&&c)return u==i&&c==e;var f=-1,d=!0,p=2&n?new Ki:t;for(o.set(e,i),o.set(i,e);++f<a;){var g=e[f],m=i[f];if(r)var w=h?r(m,g,f,i,e,o):r(g,m,f,e,i,o);if(w!==t){if(w)continue;d=!1;break}if(p){if(!Ie(i,(function(t,e){if(!Xe(p,e)&&(g===t||s(g,t,n,r,o)))return p.push(e)}))){d=!1;break}}else if(g!==m&&!s(g,m,n,r,o)){d=!1;break}}return o.delete(e),o.delete(i),d}function Qr(e){return zs(Ms(e,t,Fs),e+"")}function Zr(t){return kn(t,zh,as)}function ts(t){return kn(t,Ch,ls)}var es=$i?function(t){return $i.get(t)}:ra;function is(t){for(var e=t.name+"",i=zi[e],n=It.call(zi,e)?i.length:0;n--;){var r=i[n],s=r.func;if(null==s||s==t)return r.name}return e}function ns(t){return(It.call(Di,"placeholder")?Di:t).placeholder}function rs(){var t=Di.iteratee||ta;return t=t===ta?In:t,arguments.length?t(arguments[0],arguments[1]):t}function ss(t,e){var i,n,r=t.__data__;return("string"==(n=typeof(i=e))||"number"==n||"symbol"==n||"boolean"==n?"__proto__"!==i:null===i)?r["string"==typeof e?"string":"hash"]:r.map}function os(t){for(var e=zh(t),i=e.length;i--;){var n=e[i],r=t[n];e[i]=[n,r,bs(r)]}return e}function hs(e,i){var n=function(e,i){return null==e?t:e[i]}(e,i);return On(n)?n:t}var as=je?function(t){return null==t?[]:(t=xt(t),Ae(je(t),(function(e){return Ht.call(t,e)})))}:ca,ls=je?function(t){for(var e=[];t;)Te(e,as(t)),t=Ut(t);return e}:ca,us=Mn;function cs(t,e,i){for(var n=-1,r=(e=gr(e,t)).length,s=!1;++n<r;){var o=Is(e[n]);if(!(s=null!=t&&i(t,o)))break;t=t[o]}return s||++n!=r?s:!!(r=null==t?0:t.length)&&Yo(r)&&ps(o,r)&&(Fo(t)||Bo(t))}function fs(t){return"function"!=typeof t.constructor||ys(t)?{}:_i(Ut(t))}function ds(t){return Fo(t)||Bo(t)||!!(Yt&&t&&t[Yt])}function ps(t,e){var i=typeof t;return!!(e=null==e?h:e)&&("number"==i||"symbol"!=i&&pt.test(t))&&t>-1&&t%1==0&&t<e}function gs(t,e,i){if(!qo(i))return!1;var n=typeof e;return!!("number"==n?Wo(i)&&ps(e,i.length):"string"==n&&e in i)&&Do(i[e],t)}function ms(t,e){if(Fo(t))return!1;var i=typeof t;return!("number"!=i&&"symbol"!=i&&"boolean"!=i&&null!=t&&!rh(t))||q.test(t)||!Y.test(t)||null!=e&&t in xt(e)}function ws(t){var e=is(t),i=Di[e];if("function"!=typeof i||!(e in Fi.prototype))return!1;if(t===i)return!0;var n=es(i);return!!n&&t===n[0]}(bi&&us(new bi(new ArrayBuffer(1)))!=T||ki&&us(new ki)!=y||Mi&&us(Mi.resolve())!=M||Si&&us(new Si)!=x||xi&&us(new xi)!=z)&&(us=function(e){var i=Mn(e),n=i==k?e.constructor:t,r=n?js(n):"";if(r)switch(r){case Ci:return T;case Ti:return y;case Ei:return M;case Oi:return x;case Ii:return z}return i});var vs=Et?Go:fa;function ys(t){var e=t&&t.constructor;return t===("function"==typeof e&&e.prototype||Tt)}function bs(t){return t==t&&!qo(t)}function ks(e,i){return function(n){return null!=n&&n[e]===i&&(i!==t||e in xt(n))}}function Ms(e,i,n){return i=pi(i===t?e.length-1:i,0),function(){for(var t=arguments,r=-1,s=pi(t.length-i,0),o=yt(s);++r<s;)o[r]=t[i+r];r=-1;for(var h=yt(i+1);++r<i;)h[r]=t[r];return h[i]=n(o),be(e,this,h)}}function Ss(t,e){return e.length<2?t:bn(t,Zn(e,0,-1))}function xs(t,e){if(("constructor"!==e||"function"!=typeof t[e])&&"__proto__"!=e)return t[e]}var As=Ts(qn),$s=ue||function(t,e){return ae.setTimeout(t,e)},zs=Ts(Jn);function Cs(t,e,i){var n=e+"";return zs(t,function(t,e){var i=e.length;if(!i)return t;var n=i-1;return e[n]=(i>1?"& ":"")+e[n],e=e.join(i>2?", ":" "),t.replace(it,"{\n/* [wrapped with "+e+"] */\n")}(n,function(t,e){return Me(u,(function(i){var n="_."+i[0];e&i[1]&&!$e(t,n)&&t.push(n)})),t.sort()}(function(t){var e=t.match(nt);return e?e[1].split(rt):[]}(n),i)))}function Ts(e){var i=0,n=0;return function(){var r=mi(),s=16-(r-n);if(n=r,s>0){if(++i>=800)return arguments[0]}else i=0;return e.apply(t,arguments)}}function Es(e,i){var n=-1,r=e.length,s=r-1;for(i=i===t?r:i;++n<i;){var o=Kn(n,s),h=e[o];e[o]=e[n],e[n]=h}return e.length=i,e}var Os=function(){var t=Eo((function(t){var e=[];return 46===t.charCodeAt(0)&&e.push(""),t.replace(J,(function(t,i,n,r){e.push(n?r.replace(ht,"$1"):i||t)})),e}),(function(t){return 500===e.size&&e.clear(),t})),e=t.cache;return t}();function Is(t){if("string"==typeof t||rh(t))return t;var e=t+"";return"0"==e&&1/t==-1/0?"-0":e}function js(t){if(null!=t){try{return Ot.call(t)}catch(t){}try{return t+""}catch(t){}}return""}function Ps(t){if(t instanceof Fi)return t.clone();var e=new Bi(t.__wrapped__,t.__chain__);return e.__actions__=Ar(t.__actions__),e.__index__=t.__index__,e.__values__=t.__values__,e}var Rs=Vn((function(t,e){return Uo(t)?an(t,pn(e,1,Uo,!0)):[]})),Ds=Vn((function(e,i){var n=Hs(i);return Uo(n)&&(n=t),Uo(e)?an(e,pn(i,1,Uo,!0),rs(n,2)):[]})),_s=Vn((function(e,i){var n=Hs(i);return Uo(n)&&(n=t),Uo(e)?an(e,pn(i,1,Uo,!0),t,n):[]}));function Ls(t,e,i){var n=null==t?0:t.length;if(!n)return-1;var r=null==i?0:uh(i);return r<0&&(r=pi(n+r,0)),Re(t,rs(e,3),r)}function Bs(e,i,n){var r=null==e?0:e.length;if(!r)return-1;var s=r-1;return n!==t&&(s=uh(n),s=n<0?pi(r+s,0):gi(s,r-1)),Re(e,rs(i,3),s,!0)}function Fs(t){return null!=t&&t.length?pn(t,1):[]}function Ns(e){return e&&e.length?e[0]:t}var Ws=Vn((function(t){var e=Ce(t,dr);return e.length&&e[0]===t[0]?$n(e):[]})),Us=Vn((function(e){var i=Hs(e),n=Ce(e,dr);return i===Hs(n)?i=t:n.pop(),n.length&&n[0]===e[0]?$n(n,rs(i,2)):[]})),Ks=Vn((function(e){var i=Hs(e),n=Ce(e,dr);return(i="function"==typeof i?i:t)&&n.pop(),n.length&&n[0]===e[0]?$n(n,t,i):[]}));function Hs(e){var i=null==e?0:e.length;return i?e[i-1]:t}var Vs=Vn(Gs);function Gs(t,e){return t&&t.length&&e&&e.length?Wn(t,e):t}var Xs=Qr((function(t,e){var i=null==t?0:t.length,n=nn(t,e);return Un(t,Ce(e,(function(t){return ps(t,i)?+t:t})).sort(Mr)),n}));function Ys(t){return null==t?t:yi.call(t)}var qs=Vn((function(t){return or(pn(t,1,Uo,!0))})),Js=Vn((function(e){var i=Hs(e);return Uo(i)&&(i=t),or(pn(e,1,Uo,!0),rs(i,2))})),Qs=Vn((function(e){var i=Hs(e);return i="function"==typeof i?i:t,or(pn(e,1,Uo,!0),t,i)}));function Zs(t){if(!t||!t.length)return[];var e=0;return t=Ae(t,(function(t){if(Uo(t))return e=pi(t.length,e),!0})),Ke(e,(function(e){return Ce(t,Fe(e))}))}function to(e,i){if(!e||!e.length)return[];var n=Zs(e);return null==i?n:Ce(n,(function(e){return be(i,t,e)}))}var eo=Vn((function(t,e){return Uo(t)?an(t,e):[]})),io=Vn((function(t){return cr(Ae(t,Uo))})),no=Vn((function(e){var i=Hs(e);return Uo(i)&&(i=t),cr(Ae(e,Uo),rs(i,2))})),ro=Vn((function(e){var i=Hs(e);return i="function"==typeof i?i:t,cr(Ae(e,Uo),t,i)})),so=Vn(Zs),oo=Vn((function(e){var i=e.length,n=i>1?e[i-1]:t;return n="function"==typeof n?(e.pop(),n):t,to(e,n)}));function ho(t){var e=Di(t);return e.__chain__=!0,e}function ao(t,e){return e(t)}var lo=Qr((function(e){var i=e.length,n=i?e[0]:0,r=this.__wrapped__,s=function(t){return nn(t,e)};return!(i>1||this.__actions__.length)&&r instanceof Fi&&ps(n)?((r=r.slice(n,+n+(i?1:0))).__actions__.push({func:ao,args:[s],thisArg:t}),new Bi(r,this.__chain__).thru((function(e){return i&&!e.length&&e.push(t),e}))):this.thru(s)})),uo=zr((function(t,e,i){It.call(t,i)?++t[i]:en(t,i,1)})),co=Pr(Ls),fo=Pr(Bs);function po(t,e){return(Fo(t)?Me:ln)(t,rs(e,3))}function go(t,e){return(Fo(t)?Se:un)(t,rs(e,3))}var mo=zr((function(t,e,i){It.call(t,i)?t[i].push(e):en(t,i,[e])})),wo=Vn((function(t,e,i){var n=-1,r="function"==typeof e,s=Wo(t)?yt(t.length):[];return ln(t,(function(t){s[++n]=r?be(e,t,i):zn(t,e,i)})),s})),vo=zr((function(t,e,i){en(t,i,e)}));function yo(t,e){return(Fo(t)?Ce:Rn)(t,rs(e,3))}var bo=zr((function(t,e,i){t[i?0:1].push(e)}),(function(){return[[],[]]})),ko=Vn((function(t,e){if(null==t)return[];var i=e.length;return i>1&&gs(t,e[0],e[1])?e=[]:i>2&&gs(e[0],e[1],e[2])&&(e=[e[0]]),Fn(t,pn(e,1),[])})),Mo=le||function(){return ae.Date.now()};function So(e,i,n){return i=n?t:i,Gr(e,s,t,t,t,t,i=e&&null==i?e.length:i)}function xo(i,n){var r;if("function"!=typeof n)throw new zt(e);return i=uh(i),function(){return--i>0&&(r=n.apply(this,arguments)),i<=1&&(n=t),r}}var Ao=Vn((function(t,e,i){var n=1;if(i.length){var s=ni(i,ns(Ao));n|=r}return Gr(t,n,e,i,s)})),$o=Vn((function(t,e,i){var n=3;if(i.length){var s=ni(i,ns($o));n|=r}return Gr(e,n,t,i,s)}));function zo(i,n,r){var s,o,h,a,l,u,c=0,f=!1,d=!1,p=!0;if("function"!=typeof i)throw new zt(e);function g(e){var n=s,r=o;return s=o=t,c=e,a=i.apply(r,n)}function m(e){var i=e-u;return u===t||i>=n||i<0||d&&e-c>=h}function w(){var t=Mo();if(m(t))return v(t);l=$s(w,function(t){var e=n-(t-u);return d?gi(e,h-(t-c)):e}(t))}function v(e){return l=t,p&&s?g(e):(s=o=t,a)}function y(){var e=Mo(),i=m(e);if(s=arguments,o=this,u=e,i){if(l===t)return function(t){return c=t,l=$s(w,n),f?g(t):a}(u);if(d)return vr(l),l=$s(w,n),g(u)}return l===t&&(l=$s(w,n)),a}return n=fh(n)||0,qo(r)&&(f=!!r.leading,h=(d="maxWait"in r)?pi(fh(r.maxWait)||0,n):h,p="trailing"in r?!!r.trailing:p),y.cancel=function(){l!==t&&vr(l),c=0,s=u=o=l=t},y.flush=function(){return l===t?a:v(Mo())},y}var Co=Vn((function(t,e){return hn(t,1,e)})),To=Vn((function(t,e,i){return hn(t,fh(e)||0,i)}));function Eo(t,i){if("function"!=typeof t||null!=i&&"function"!=typeof i)throw new zt(e);var n=function(){var e=arguments,r=i?i.apply(this,e):e[0],s=n.cache;if(s.has(r))return s.get(r);var o=t.apply(this,e);return n.cache=s.set(r,o)||s,o};return n.cache=new(Eo.Cache||Ui),n}function Oo(t){if("function"!=typeof t)throw new zt(e);return function(){var e=arguments;switch(e.length){case 0:return!t.call(this);case 1:return!t.call(this,e[0]);case 2:return!t.call(this,e[0],e[1]);case 3:return!t.call(this,e[0],e[1],e[2])}return!t.apply(this,e)}}Eo.Cache=Ui;var Io=mr((function(t,e){var i=(e=1==e.length&&Fo(e[0])?Ce(e[0],Ve(rs())):Ce(pn(e,1),Ve(rs()))).length;return Vn((function(n){for(var r=-1,s=gi(n.length,i);++r<s;)n[r]=e[r].call(this,n[r]);return be(t,this,n)}))})),jo=Vn((function(e,i){var n=ni(i,ns(jo));return Gr(e,r,t,i,n)})),Po=Vn((function(e,i){var n=ni(i,ns(Po));return Gr(e,64,t,i,n)})),Ro=Qr((function(e,i){return Gr(e,256,t,t,t,i)}));function Do(t,e){return t===e||t!=t&&e!=e}var _o=Wr(Sn),Lo=Wr((function(t,e){return t>=e})),Bo=Cn(function(){return arguments}())?Cn:function(t){return Jo(t)&&It.call(t,"callee")&&!Ht.call(t,"callee")},Fo=yt.isArray,No=pe?Ve(pe):function(t){return Jo(t)&&Mn(t)==C};function Wo(t){return null!=t&&Yo(t.length)&&!Go(t)}function Uo(t){return Jo(t)&&Wo(t)}var Ko=Ne||fa,Ho=ge?Ve(ge):function(t){return Jo(t)&&Mn(t)==g};function Vo(t){if(!Jo(t))return!1;var e=Mn(t);return e==m||"[object DOMException]"==e||"string"==typeof t.message&&"string"==typeof t.name&&!th(t)}function Go(t){if(!qo(t))return!1;var e=Mn(t);return e==w||e==v||"[object AsyncFunction]"==e||"[object Proxy]"==e}function Xo(t){return"number"==typeof t&&t==uh(t)}function Yo(t){return"number"==typeof t&&t>-1&&t%1==0&&t<=h}function qo(t){var e=typeof t;return null!=t&&("object"==e||"function"==e)}function Jo(t){return null!=t&&"object"==typeof t}var Qo=me?Ve(me):function(t){return Jo(t)&&us(t)==y};function Zo(t){return"number"==typeof t||Jo(t)&&Mn(t)==b}function th(t){if(!Jo(t)||Mn(t)!=k)return!1;var e=Ut(t);if(null===e)return!0;var i=It.call(e,"constructor")&&e.constructor;return"function"==typeof i&&i instanceof i&&Ot.call(i)==Dt}var eh=we?Ve(we):function(t){return Jo(t)&&Mn(t)==S},ih=ve?Ve(ve):function(t){return Jo(t)&&us(t)==x};function nh(t){return"string"==typeof t||!Fo(t)&&Jo(t)&&Mn(t)==A}function rh(t){return"symbol"==typeof t||Jo(t)&&Mn(t)==$}var sh=ye?Ve(ye):function(t){return Jo(t)&&Yo(t.length)&&!!ee[Mn(t)]},oh=Wr(Pn),hh=Wr((function(t,e){return t<=e}));function ah(t){if(!t)return[];if(Wo(t))return nh(t)?hi(t):Ar(t);if(Jt&&t[Jt])return function(t){for(var e,i=[];!(e=t.next()).done;)i.push(e.value);return i}(t[Jt]());var e=us(t);return(e==y?ei:e==x?ri:Dh)(t)}function lh(t){return t?(t=fh(t))===o||t===-1/0?17976931348623157e292*(t<0?-1:1):t==t?t:0:0===t?t:0}function uh(t){var e=lh(t),i=e%1;return e==e?i?e-i:e:0}function ch(t){return t?rn(uh(t),0,l):0}function fh(t){if("number"==typeof t)return t;if(rh(t))return a;if(qo(t)){var e="function"==typeof t.valueOf?t.valueOf():t;t=qo(e)?e+"":e}if("string"!=typeof t)return 0===t?t:+t;t=He(t);var i=ct.test(t);return i||dt.test(t)?se(t.slice(2),i?2:8):ut.test(t)?a:+t}function dh(t){return $r(t,Ch(t))}function ph(t){return null==t?"":sr(t)}var gh=Cr((function(t,e){if(ys(e)||Wo(e))$r(e,zh(e),t);else for(var i in e)It.call(e,i)&&Ji(t,i,e[i])})),mh=Cr((function(t,e){$r(e,Ch(e),t)})),wh=Cr((function(t,e,i,n){$r(e,Ch(e),t,n)})),vh=Cr((function(t,e,i,n){$r(e,zh(e),t,n)})),yh=Qr(nn),bh=Vn((function(e,i){e=xt(e);var n=-1,r=i.length,s=r>2?i[2]:t;for(s&&gs(i[0],i[1],s)&&(r=1);++n<r;)for(var o=i[n],h=Ch(o),a=-1,l=h.length;++a<l;){var u=h[a],c=e[u];(c===t||Do(c,Tt[u])&&!It.call(e,u))&&(e[u]=o[u])}return e})),kh=Vn((function(e){return e.push(t,Yr),be(Eh,t,e)}));function Mh(e,i,n){var r=null==e?t:bn(e,i);return r===t?n:r}function Sh(t,e){return null!=t&&cs(t,e,An)}var xh=_r((function(t,e,i){null!=e&&"function"!=typeof e.toString&&(e=Rt.call(e)),t[e]=i}),qh(Zh)),Ah=_r((function(t,e,i){null!=e&&"function"!=typeof e.toString&&(e=Rt.call(e)),It.call(t,e)?t[e].push(i):t[e]=[i]}),rs),$h=Vn(zn);function zh(t){return Wo(t)?Vi(t):jn(t)}function Ch(t){return Wo(t)?Vi(t,!0):function(t){if(!qo(t))return function(t){var e=[];if(null!=t)for(var i in xt(t))e.push(i);return e}(t);var e=ys(t),i=[];for(var n in t)("constructor"!=n||!e&&It.call(t,n))&&i.push(n);return i}(t)}var Th=Cr((function(t,e,i){Ln(t,e,i)})),Eh=Cr((function(t,e,i,n){Ln(t,e,i,n)})),Oh=Qr((function(t,e){var i={};if(null==t)return i;var n=!1;e=Ce(e,(function(e){return e=gr(e,t),n||(n=e.length>1),e})),$r(t,ts(t),i),n&&(i=sn(i,7,qr));for(var r=e.length;r--;)hr(i,e[r]);return i})),Ih=Qr((function(t,e){return null==t?{}:function(t,e){return Nn(t,e,(function(e,i){return Sh(t,i)}))}(t,e)}));function jh(t,e){if(null==t)return{};var i=Ce(ts(t),(function(t){return[t]}));return e=rs(e),Nn(t,i,(function(t,i){return e(t,i[0])}))}var Ph=Vr(zh),Rh=Vr(Ch);function Dh(t){return null==t?[]:Ge(t,zh(t))}var _h=Ir((function(t,e,i){return e=e.toLowerCase(),t+(i?Lh(e):e)}));function Lh(t){return Vh(ph(t).toLowerCase())}function Bh(t){return(t=ph(t))&&t.replace(gt,Je).replace(Xt,"")}var Fh=Ir((function(t,e,i){return t+(i?"-":"")+e.toLowerCase()})),Nh=Ir((function(t,e,i){return t+(i?" ":"")+e.toLowerCase()})),Wh=Or("toLowerCase"),Uh=Ir((function(t,e,i){return t+(i?"_":"")+e.toLowerCase()})),Kh=Ir((function(t,e,i){return t+(i?" ":"")+Vh(e)})),Hh=Ir((function(t,e,i){return t+(i?" ":"")+e.toUpperCase()})),Vh=Or("toUpperCase");function Gh(e,i,n){return e=ph(e),(i=n?t:i)===t?function(t){return Qt.test(t)}(e)?function(t){return t.match(qt)||[]}(e):function(t){return t.match(st)||[]}(e):e.match(i)||[]}var Xh=Vn((function(e,i){try{return be(e,t,i)}catch(t){return Vo(t)?t:new kt(t)}})),Yh=Qr((function(t,e){return Me(e,(function(e){e=Is(e),en(t,e,Ao(t[e],t))})),t}));function qh(t){return function(){return t}}var Jh=Rr(),Qh=Rr(!0);function Zh(t){return t}function ta(t){return In("function"==typeof t?t:sn(t,1))}var ea=Vn((function(t,e){return function(i){return zn(i,t,e)}})),ia=Vn((function(t,e){return function(i){return zn(t,i,e)}}));function na(t,e,i){var n=zh(e),r=yn(e,n);null!=i||qo(e)&&(r.length||!n.length)||(i=e,e=t,t=this,r=yn(e,zh(e)));var s=!(qo(i)&&"chain"in i&&!i.chain),o=Go(t);return Me(r,(function(i){var n=e[i];t[i]=n,o&&(t.prototype[i]=function(){var e=this.__chain__;if(s||e){var i=t(this.__wrapped__);return(i.__actions__=Ar(this.__actions__)).push({func:n,args:arguments,thisArg:t}),i.__chain__=e,i}return n.apply(t,Te([this.value()],arguments))})})),t}function ra(){}var sa=Br(Ce),oa=Br(xe),ha=Br(Ie);function aa(t){return ms(t)?Fe(Is(t)):function(t){return function(e){return bn(e,t)}}(t)}var la=Nr(),ua=Nr(!0);function ca(){return[]}function fa(){return!1}var da,pa=Lr((function(t,e){return t+e}),0),ga=Kr("ceil"),ma=Lr((function(t,e){return t/e}),1),wa=Kr("floor"),va=Lr((function(t,e){return t*e}),1),ya=Kr("round"),ba=Lr((function(t,e){return t-e}),0);return Di.after=function(t,i){if("function"!=typeof i)throw new zt(e);return t=uh(t),function(){if(--t<1)return i.apply(this,arguments)}},Di.ary=So,Di.assign=gh,Di.assignIn=mh,Di.assignInWith=wh,Di.assignWith=vh,Di.at=yh,Di.before=xo,Di.bind=Ao,Di.bindAll=Yh,Di.bindKey=$o,Di.castArray=function(){if(!arguments.length)return[];var t=arguments[0];return Fo(t)?t:[t]},Di.chain=ho,Di.chunk=function(e,i,n){i=(n?gs(e,i,n):i===t)?1:pi(uh(i),0);var r=null==e?0:e.length;if(!r||i<1)return[];for(var s=0,o=0,h=yt(fe(r/i));s<r;)h[o++]=Zn(e,s,s+=i);return h},Di.compact=function(t){for(var e=-1,i=null==t?0:t.length,n=0,r=[];++e<i;){var s=t[e];s&&(r[n++]=s)}return r},Di.concat=function(){var t=arguments.length;if(!t)return[];for(var e=yt(t-1),i=arguments[0],n=t;n--;)e[n-1]=arguments[n];return Te(Fo(i)?Ar(i):[i],pn(e,1))},Di.cond=function(t){var i=null==t?0:t.length,n=rs();return t=i?Ce(t,(function(t){if("function"!=typeof t[1])throw new zt(e);return[n(t[0]),t[1]]})):[],Vn((function(e){for(var n=-1;++n<i;){var r=t[n];if(be(r[0],this,e))return be(r[1],this,e)}}))},Di.conforms=function(t){return function(t){var e=zh(t);return function(i){return on(i,t,e)}}(sn(t,1))},Di.constant=qh,Di.countBy=uo,Di.create=function(t,e){var i=_i(t);return null==e?i:tn(i,e)},Di.curry=function e(i,n,r){var s=Gr(i,8,t,t,t,t,t,n=r?t:n);return s.placeholder=e.placeholder,s},Di.curryRight=function e(i,n,r){var s=Gr(i,16,t,t,t,t,t,n=r?t:n);return s.placeholder=e.placeholder,s},Di.debounce=zo,Di.defaults=bh,Di.defaultsDeep=kh,Di.defer=Co,Di.delay=To,Di.difference=Rs,Di.differenceBy=Ds,Di.differenceWith=_s,Di.drop=function(e,i,n){var r=null==e?0:e.length;return r?Zn(e,(i=n||i===t?1:uh(i))<0?0:i,r):[]},Di.dropRight=function(e,i,n){var r=null==e?0:e.length;return r?Zn(e,0,(i=r-(i=n||i===t?1:uh(i)))<0?0:i):[]},Di.dropRightWhile=function(t,e){return t&&t.length?lr(t,rs(e,3),!0,!0):[]},Di.dropWhile=function(t,e){return t&&t.length?lr(t,rs(e,3),!0):[]},Di.fill=function(e,i,n,r){var s=null==e?0:e.length;return s?(n&&"number"!=typeof n&&gs(e,i,n)&&(n=0,r=s),function(e,i,n,r){var s=e.length;for((n=uh(n))<0&&(n=-n>s?0:s+n),(r=r===t||r>s?s:uh(r))<0&&(r+=s),r=n>r?0:ch(r);n<r;)e[n++]=i;return e}(e,i,n,r)):[]},Di.filter=function(t,e){return(Fo(t)?Ae:dn)(t,rs(e,3))},Di.flatMap=function(t,e){return pn(yo(t,e),1)},Di.flatMapDeep=function(t,e){return pn(yo(t,e),o)},Di.flatMapDepth=function(e,i,n){return n=n===t?1:uh(n),pn(yo(e,i),n)},Di.flatten=Fs,Di.flattenDeep=function(t){return null!=t&&t.length?pn(t,o):[]},Di.flattenDepth=function(e,i){return null!=e&&e.length?pn(e,i=i===t?1:uh(i)):[]},Di.flip=function(t){return Gr(t,512)},Di.flow=Jh,Di.flowRight=Qh,Di.fromPairs=function(t){for(var e=-1,i=null==t?0:t.length,n={};++e<i;){var r=t[e];en(n,r[0],r[1])}return n},Di.functions=function(t){return null==t?[]:yn(t,zh(t))},Di.functionsIn=function(t){return null==t?[]:yn(t,Ch(t))},Di.groupBy=mo,Di.initial=function(t){return null!=t&&t.length?Zn(t,0,-1):[]},Di.intersection=Ws,Di.intersectionBy=Us,Di.intersectionWith=Ks,Di.invert=xh,Di.invertBy=Ah,Di.invokeMap=wo,Di.iteratee=ta,Di.keyBy=vo,Di.keys=zh,Di.keysIn=Ch,Di.map=yo,Di.mapKeys=function(t,e){var i={};return e=rs(e,3),wn(t,(function(t,n,r){en(i,e(t,n,r),t)})),i},Di.mapValues=function(t,e){var i={};return e=rs(e,3),wn(t,(function(t,n,r){en(i,n,e(t,n,r))})),i},Di.matches=function(t){return Dn(sn(t,1))},Di.matchesProperty=function(t,e){return _n(t,sn(e,1))},Di.memoize=Eo,Di.merge=Th,Di.mergeWith=Eh,Di.method=ea,Di.methodOf=ia,Di.mixin=na,Di.negate=Oo,Di.nthArg=function(t){return t=uh(t),Vn((function(e){return Bn(e,t)}))},Di.omit=Oh,Di.omitBy=function(t,e){return jh(t,Oo(rs(e)))},Di.once=function(t){return xo(2,t)},Di.orderBy=function(e,i,n,r){return null==e?[]:(Fo(i)||(i=null==i?[]:[i]),Fo(n=r?t:n)||(n=null==n?[]:[n]),Fn(e,i,n))},Di.over=sa,Di.overArgs=Io,Di.overEvery=oa,Di.overSome=ha,Di.partial=jo,Di.partialRight=Po,Di.partition=bo,Di.pick=Ih,Di.pickBy=jh,Di.property=aa,Di.propertyOf=function(e){return function(i){return null==e?t:bn(e,i)}},Di.pull=Vs,Di.pullAll=Gs,Di.pullAllBy=function(t,e,i){return t&&t.length&&e&&e.length?Wn(t,e,rs(i,2)):t},Di.pullAllWith=function(e,i,n){return e&&e.length&&i&&i.length?Wn(e,i,t,n):e},Di.pullAt=Xs,Di.range=la,Di.rangeRight=ua,Di.rearg=Ro,Di.reject=function(t,e){return(Fo(t)?Ae:dn)(t,Oo(rs(e,3)))},Di.remove=function(t,e){var i=[];if(!t||!t.length)return i;var n=-1,r=[],s=t.length;for(e=rs(e,3);++n<s;){var o=t[n];e(o,n,t)&&(i.push(o),r.push(n))}return Un(t,r),i},Di.rest=function(i,n){if("function"!=typeof i)throw new zt(e);return Vn(i,n=n===t?n:uh(n))},Di.reverse=Ys,Di.sampleSize=function(e,i,n){return i=(n?gs(e,i,n):i===t)?1:uh(i),(Fo(e)?Xi:Xn)(e,i)},Di.set=function(t,e,i){return null==t?t:Yn(t,e,i)},Di.setWith=function(e,i,n,r){return r="function"==typeof r?r:t,null==e?e:Yn(e,i,n,r)},Di.shuffle=function(t){return(Fo(t)?Yi:Qn)(t)},Di.slice=function(e,i,n){var r=null==e?0:e.length;return r?(n&&"number"!=typeof n&&gs(e,i,n)?(i=0,n=r):(i=null==i?0:uh(i),n=n===t?r:uh(n)),Zn(e,i,n)):[]},Di.sortBy=ko,Di.sortedUniq=function(t){return t&&t.length?nr(t):[]},Di.sortedUniqBy=function(t,e){return t&&t.length?nr(t,rs(e,2)):[]},Di.split=function(e,i,n){return n&&"number"!=typeof n&&gs(e,i,n)&&(i=n=t),(n=n===t?l:n>>>0)?(e=ph(e))&&("string"==typeof i||null!=i&&!eh(i))&&!(i=sr(i))&&ti(e)?wr(hi(e),0,n):e.split(i,n):[]},Di.spread=function(t,i){if("function"!=typeof t)throw new zt(e);return i=null==i?0:pi(uh(i),0),Vn((function(e){var n=e[i],r=wr(e,0,i);return n&&Te(r,n),be(t,this,r)}))},Di.tail=function(t){var e=null==t?0:t.length;return e?Zn(t,1,e):[]},Di.take=function(e,i,n){return e&&e.length?Zn(e,0,(i=n||i===t?1:uh(i))<0?0:i):[]},Di.takeRight=function(e,i,n){var r=null==e?0:e.length;return r?Zn(e,(i=r-(i=n||i===t?1:uh(i)))<0?0:i,r):[]},Di.takeRightWhile=function(t,e){return t&&t.length?lr(t,rs(e,3),!1,!0):[]},Di.takeWhile=function(t,e){return t&&t.length?lr(t,rs(e,3)):[]},Di.tap=function(t,e){return e(t),t},Di.throttle=function(t,i,n){var r=!0,s=!0;if("function"!=typeof t)throw new zt(e);return qo(n)&&(r="leading"in n?!!n.leading:r,s="trailing"in n?!!n.trailing:s),zo(t,i,{leading:r,maxWait:i,trailing:s})},Di.thru=ao,Di.toArray=ah,Di.toPairs=Ph,Di.toPairsIn=Rh,Di.toPath=function(t){return Fo(t)?Ce(t,Is):rh(t)?[t]:Ar(Os(ph(t)))},Di.toPlainObject=dh,Di.transform=function(t,e,i){var n=Fo(t),r=n||Ko(t)||sh(t);if(e=rs(e,4),null==i){var s=t&&t.constructor;i=r?n?new s:[]:qo(t)&&Go(s)?_i(Ut(t)):{}}return(r?Me:wn)(t,(function(t,n,r){return e(i,t,n,r)})),i},Di.unary=function(t){return So(t,1)},Di.union=qs,Di.unionBy=Js,Di.unionWith=Qs,Di.uniq=function(t){return t&&t.length?or(t):[]},Di.uniqBy=function(t,e){return t&&t.length?or(t,rs(e,2)):[]},Di.uniqWith=function(e,i){return i="function"==typeof i?i:t,e&&e.length?or(e,t,i):[]},Di.unset=function(t,e){return null==t||hr(t,e)},Di.unzip=Zs,Di.unzipWith=to,Di.update=function(t,e,i){return null==t?t:ar(t,e,pr(i))},Di.updateWith=function(e,i,n,r){return r="function"==typeof r?r:t,null==e?e:ar(e,i,pr(n),r)},Di.values=Dh,Di.valuesIn=function(t){return null==t?[]:Ge(t,Ch(t))},Di.without=eo,Di.words=Gh,Di.wrap=function(t,e){return jo(pr(e),t)},Di.xor=io,Di.xorBy=no,Di.xorWith=ro,Di.zip=so,Di.zipObject=function(t,e){return fr(t||[],e||[],Ji)},Di.zipObjectDeep=function(t,e){return fr(t||[],e||[],Yn)},Di.zipWith=oo,Di.entries=Ph,Di.entriesIn=Rh,Di.extend=mh,Di.extendWith=wh,na(Di,Di),Di.add=pa,Di.attempt=Xh,Di.camelCase=_h,Di.capitalize=Lh,Di.ceil=ga,Di.clamp=function(e,i,n){return n===t&&(n=i,i=t),n!==t&&(n=(n=fh(n))==n?n:0),i!==t&&(i=(i=fh(i))==i?i:0),rn(fh(e),i,n)},Di.clone=function(t){return sn(t,4)},Di.cloneDeep=function(t){return sn(t,5)},Di.cloneDeepWith=function(e,i){return sn(e,5,i="function"==typeof i?i:t)},Di.cloneWith=function(e,i){return sn(e,4,i="function"==typeof i?i:t)},Di.conformsTo=function(t,e){return null==e||on(t,e,zh(e))},Di.deburr=Bh,Di.defaultTo=function(t,e){return null==t||t!=t?e:t},Di.divide=ma,Di.endsWith=function(e,i,n){e=ph(e),i=sr(i);var r=e.length,s=n=n===t?r:rn(uh(n),0,r);return(n-=i.length)>=0&&e.slice(n,s)==i},Di.eq=Do,Di.escape=function(t){return(t=ph(t))&&H.test(t)?t.replace(U,Qe):t},Di.escapeRegExp=function(t){return(t=ph(t))&&Z.test(t)?t.replace(Q,"\\$&"):t},Di.every=function(e,i,n){var r=Fo(e)?xe:cn;return n&&gs(e,i,n)&&(i=t),r(e,rs(i,3))},Di.find=co,Di.findIndex=Ls,Di.findKey=function(t,e){return Pe(t,rs(e,3),wn)},Di.findLast=fo,Di.findLastIndex=Bs,Di.findLastKey=function(t,e){return Pe(t,rs(e,3),vn)},Di.floor=wa,Di.forEach=po,Di.forEachRight=go,Di.forIn=function(t,e){return null==t?t:gn(t,rs(e,3),Ch)},Di.forInRight=function(t,e){return null==t?t:mn(t,rs(e,3),Ch)},Di.forOwn=function(t,e){return t&&wn(t,rs(e,3))},Di.forOwnRight=function(t,e){return t&&vn(t,rs(e,3))},Di.get=Mh,Di.gt=_o,Di.gte=Lo,Di.has=function(t,e){return null!=t&&cs(t,e,xn)},Di.hasIn=Sh,Di.head=Ns,Di.identity=Zh,Di.includes=function(t,e,i,n){t=Wo(t)?t:Dh(t),i=i&&!n?uh(i):0;var r=t.length;return i<0&&(i=pi(r+i,0)),nh(t)?i<=r&&t.indexOf(e,i)>-1:!!r&&De(t,e,i)>-1},Di.indexOf=function(t,e,i){var n=null==t?0:t.length;if(!n)return-1;var r=null==i?0:uh(i);return r<0&&(r=pi(n+r,0)),De(t,e,r)},Di.inRange=function(e,i,n){return i=lh(i),n===t?(n=i,i=0):n=lh(n),function(t,e,i){return t>=gi(e,i)&&t<pi(e,i)}(e=fh(e),i,n)},Di.invoke=$h,Di.isArguments=Bo,Di.isArray=Fo,Di.isArrayBuffer=No,Di.isArrayLike=Wo,Di.isArrayLikeObject=Uo,Di.isBoolean=function(t){return!0===t||!1===t||Jo(t)&&Mn(t)==d},Di.isBuffer=Ko,Di.isDate=Ho,Di.isElement=function(t){return Jo(t)&&1===t.nodeType&&!th(t)},Di.isEmpty=function(t){if(null==t)return!0;if(Wo(t)&&(Fo(t)||"string"==typeof t||"function"==typeof t.splice||Ko(t)||sh(t)||Bo(t)))return!t.length;var e=us(t);if(e==y||e==x)return!t.size;if(ys(t))return!jn(t).length;for(var i in t)if(It.call(t,i))return!1;return!0},Di.isEqual=function(t,e){return Tn(t,e)},Di.isEqualWith=function(e,i,n){var r=(n="function"==typeof n?n:t)?n(e,i):t;return r===t?Tn(e,i,t,n):!!r},Di.isError=Vo,Di.isFinite=function(t){return"number"==typeof t&&ci(t)},Di.isFunction=Go,Di.isInteger=Xo,Di.isLength=Yo,Di.isMap=Qo,Di.isMatch=function(t,e){return t===e||En(t,e,os(e))},Di.isMatchWith=function(e,i,n){return n="function"==typeof n?n:t,En(e,i,os(i),n)},Di.isNaN=function(t){return Zo(t)&&t!=+t},Di.isNative=function(t){if(vs(t))throw new kt("Unsupported core-js use. Try https://npms.io/search?q=ponyfill.");return On(t)},Di.isNil=function(t){return null==t},Di.isNull=function(t){return null===t},Di.isNumber=Zo,Di.isObject=qo,Di.isObjectLike=Jo,Di.isPlainObject=th,Di.isRegExp=eh,Di.isSafeInteger=function(t){return Xo(t)&&t>=-9007199254740991&&t<=h},Di.isSet=ih,Di.isString=nh,Di.isSymbol=rh,Di.isTypedArray=sh,Di.isUndefined=function(e){return e===t},Di.isWeakMap=function(t){return Jo(t)&&us(t)==z},Di.isWeakSet=function(t){return Jo(t)&&"[object WeakSet]"==Mn(t)},Di.join=function(t,e){return null==t?"":fi.call(t,e)},Di.kebabCase=Fh,Di.last=Hs,Di.lastIndexOf=function(e,i,n){var r=null==e?0:e.length;if(!r)return-1;var s=r;return n!==t&&(s=(s=uh(n))<0?pi(r+s,0):gi(s,r-1)),i==i?function(t,e,i){for(var n=i+1;n--;)if(t[n]===e)return n;return n}(e,i,s):Re(e,Le,s,!0)},Di.lowerCase=Nh,Di.lowerFirst=Wh,Di.lt=oh,Di.lte=hh,Di.max=function(e){return e&&e.length?fn(e,Zh,Sn):t},Di.maxBy=function(e,i){return e&&e.length?fn(e,rs(i,2),Sn):t},Di.mean=function(t){return Be(t,Zh)},Di.meanBy=function(t,e){return Be(t,rs(e,2))},Di.min=function(e){return e&&e.length?fn(e,Zh,Pn):t},Di.minBy=function(e,i){return e&&e.length?fn(e,rs(i,2),Pn):t},Di.stubArray=ca,Di.stubFalse=fa,Di.stubObject=function(){return{}},Di.stubString=function(){return""},Di.stubTrue=function(){return!0},Di.multiply=va,Di.nth=function(e,i){return e&&e.length?Bn(e,uh(i)):t},Di.noConflict=function(){return ae._===this&&(ae._=_t),this},Di.noop=ra,Di.now=Mo,Di.pad=function(t,e,i){t=ph(t);var n=(e=uh(e))?oi(t):0;if(!e||n>=e)return t;var r=(e-n)/2;return Fr(de(r),i)+t+Fr(fe(r),i)},Di.padEnd=function(t,e,i){t=ph(t);var n=(e=uh(e))?oi(t):0;return e&&n<e?t+Fr(e-n,i):t},Di.padStart=function(t,e,i){t=ph(t);var n=(e=uh(e))?oi(t):0;return e&&n<e?Fr(e-n,i)+t:t},Di.parseInt=function(t,e,i){return i||null==e?e=0:e&&(e=+e),wi(ph(t).replace(tt,""),e||0)},Di.random=function(e,i,n){if(n&&"boolean"!=typeof n&&gs(e,i,n)&&(i=n=t),n===t&&("boolean"==typeof i?(n=i,i=t):"boolean"==typeof e&&(n=e,e=t)),e===t&&i===t?(e=0,i=1):(e=lh(e),i===t?(i=e,e=0):i=lh(i)),e>i){var r=e;e=i,i=r}if(n||e%1||i%1){var s=vi();return gi(e+s*(i-e+re("1e-"+((s+"").length-1))),i)}return Kn(e,i)},Di.reduce=function(t,e,i){var n=Fo(t)?Ee:We,r=arguments.length<3;return n(t,rs(e,4),i,r,ln)},Di.reduceRight=function(t,e,i){var n=Fo(t)?Oe:We,r=arguments.length<3;return n(t,rs(e,4),i,r,un)},Di.repeat=function(e,i,n){return i=(n?gs(e,i,n):i===t)?1:uh(i),Hn(ph(e),i)},Di.replace=function(){var t=arguments,e=ph(t[0]);return t.length<3?e:e.replace(t[1],t[2])},Di.result=function(e,i,n){var r=-1,s=(i=gr(i,e)).length;for(s||(s=1,e=t);++r<s;){var o=null==e?t:e[Is(i[r])];o===t&&(r=s,o=n),e=Go(o)?o.call(e):o}return e},Di.round=ya,Di.runInContext=p,Di.sample=function(t){return(Fo(t)?Gi:Gn)(t)},Di.size=function(t){if(null==t)return 0;if(Wo(t))return nh(t)?oi(t):t.length;var e=us(t);return e==y||e==x?t.size:jn(t).length},Di.snakeCase=Uh,Di.some=function(e,i,n){var r=Fo(e)?Ie:tr;return n&&gs(e,i,n)&&(i=t),r(e,rs(i,3))},Di.sortedIndex=function(t,e){return er(t,e)},Di.sortedIndexBy=function(t,e,i){return ir(t,e,rs(i,2))},Di.sortedIndexOf=function(t,e){var i=null==t?0:t.length;if(i){var n=er(t,e);if(n<i&&Do(t[n],e))return n}return-1},Di.sortedLastIndex=function(t,e){return er(t,e,!0)},Di.sortedLastIndexBy=function(t,e,i){return ir(t,e,rs(i,2),!0)},Di.sortedLastIndexOf=function(t,e){if(null!=t&&t.length){var i=er(t,e,!0)-1;if(Do(t[i],e))return i}return-1},Di.startCase=Kh,Di.startsWith=function(t,e,i){return t=ph(t),i=null==i?0:rn(uh(i),0,t.length),e=sr(e),t.slice(i,i+e.length)==e},Di.subtract=ba,Di.sum=function(t){return t&&t.length?Ue(t,Zh):0},Di.sumBy=function(t,e){return t&&t.length?Ue(t,rs(e,2)):0},Di.template=function(e,i,n){var r=Di.templateSettings;n&&gs(e,i,n)&&(i=t),e=ph(e),i=vh({},i,r,Xr);var s=vh({},i.imports,r.imports,Xr),o=zh(s),h=Ge(s,o);Me(o,(function(t){if(ot.test(t))throw new kt("Invalid `imports` option passed into `_.template`")}));var a,l,u=0,c=i.interpolate||mt,f="__p += '",d=At((i.escape||mt).source+"|"+c.source+"|"+(c===X?at:mt).source+"|"+(i.evaluate||mt).source+"|$","g"),p="//# sourceURL="+(It.call(i,"sourceURL")?(i.sourceURL+"").replace(/\s/g," "):"lodash.templateSources["+ ++te+"]")+"\n";e.replace(d,(function(t,i,n,r,s,o){return n||(n=r),f+=e.slice(u,o).replace(wt,Ze),i&&(a=!0,f+="' +\n__e("+i+") +\n'"),s&&(l=!0,f+="';\n"+s+";\n__p += '"),n&&(f+="' +\n((__t = ("+n+")) == null ? '' : __t) +\n'"),u=o+t.length,t})),f+="';\n";var g=It.call(i,"variable")&&i.variable;if(g){if(ot.test(g))throw new kt("Invalid `variable` option passed into `_.template`")}else f="with (obj) {\n"+f+"\n}\n";f=(l?f.replace(B,""):f).replace(F,"$1").replace(N,"$1;"),f="function("+(g||"obj")+") {\n"+(g?"":"obj || (obj = {});\n")+"var __t, __p = ''"+(a?", __e = _.escape":"")+(l?", __j = Array.prototype.join;\nfunction print() { __p += __j.call(arguments, '') }\n":";\n")+f+"return __p\n}";var m=Xh((function(){return Mt(o,p+"return "+f).apply(t,h)}));if(m.source=f,Vo(m))throw m;return m},Di.times=function(t,e){if((t=uh(t))<1||t>h)return[];var i=l,n=gi(t,l);e=rs(e),t-=l;for(var r=Ke(n,e);++i<t;)e(i);return r},Di.toFinite=lh,Di.toInteger=uh,Di.toLength=ch,Di.toLower=function(t){return ph(t).toLowerCase()},Di.toNumber=fh,Di.toSafeInteger=function(t){return t?rn(uh(t),-9007199254740991,h):0===t?t:0},Di.toString=ph,Di.toUpper=function(t){return ph(t).toUpperCase()},Di.trim=function(e,i,n){if((e=ph(e))&&(n||i===t))return He(e);if(!e||!(i=sr(i)))return e;var r=hi(e),s=hi(i);return wr(r,Ye(r,s),qe(r,s)+1).join("")},Di.trimEnd=function(e,i,n){if((e=ph(e))&&(n||i===t))return e.slice(0,ai(e)+1);if(!e||!(i=sr(i)))return e;var r=hi(e);return wr(r,0,qe(r,hi(i))+1).join("")},Di.trimStart=function(e,i,n){if((e=ph(e))&&(n||i===t))return e.replace(tt,"");if(!e||!(i=sr(i)))return e;var r=hi(e);return wr(r,Ye(r,hi(i))).join("")},Di.truncate=function(e,i){var n=30,r="...";if(qo(i)){var s="separator"in i?i.separator:s;n="length"in i?uh(i.length):n,r="omission"in i?sr(i.omission):r}var o=(e=ph(e)).length;if(ti(e)){var h=hi(e);o=h.length}if(n>=o)return e;var a=n-oi(r);if(a<1)return r;var l=h?wr(h,0,a).join(""):e.slice(0,a);if(s===t)return l+r;if(h&&(a+=l.length-a),eh(s)){if(e.slice(a).search(s)){var u,c=l;for(s.global||(s=At(s.source,ph(lt.exec(s))+"g")),s.lastIndex=0;u=s.exec(c);)var f=u.index;l=l.slice(0,f===t?a:f)}}else if(e.indexOf(sr(s),a)!=a){var d=l.lastIndexOf(s);d>-1&&(l=l.slice(0,d))}return l+r},Di.unescape=function(t){return(t=ph(t))&&K.test(t)?t.replace(W,li):t},Di.uniqueId=function(t){var e=++jt;return ph(t)+e},Di.upperCase=Hh,Di.upperFirst=Vh,Di.each=po,Di.eachRight=go,Di.first=Ns,na(Di,(da={},wn(Di,(function(t,e){It.call(Di.prototype,e)||(da[e]=t)})),da),{chain:!1}),Di.VERSION="4.18.1",Me(["bind","bindKey","curry","curryRight","partial","partialRight"],(function(t){Di[t].placeholder=Di})),Me(["drop","take"],(function(e,i){Fi.prototype[e]=function(n){n=n===t?1:pi(uh(n),0);var r=this.__filtered__&&!i?new Fi(this):this.clone();return r.__filtered__?r.__takeCount__=gi(n,r.__takeCount__):r.__views__.push({size:gi(n,l),type:e+(r.__dir__<0?"Right":"")}),r},Fi.prototype[e+"Right"]=function(t){return this.reverse()[e](t).reverse()}})),Me(["filter","map","takeWhile"],(function(t,e){var i=e+1,n=1==i||3==i;Fi.prototype[t]=function(t){var e=this.clone();return e.__iteratees__.push({iteratee:rs(t,3),type:i}),e.__filtered__=e.__filtered__||n,e}})),Me(["head","last"],(function(t,e){var i="take"+(e?"Right":"");Fi.prototype[t]=function(){return this[i](1).value()[0]}})),Me(["initial","tail"],(function(t,e){var i="drop"+(e?"":"Right");Fi.prototype[t]=function(){return this.__filtered__?new Fi(this):this[i](1)}})),Fi.prototype.compact=function(){return this.filter(Zh)},Fi.prototype.find=function(t){return this.filter(t).head()},Fi.prototype.findLast=function(t){return this.reverse().find(t)},Fi.prototype.invokeMap=Vn((function(t,e){return"function"==typeof t?new Fi(this):this.map((function(i){return zn(i,t,e)}))})),Fi.prototype.reject=function(t){return this.filter(Oo(rs(t)))},Fi.prototype.slice=function(e,i){e=uh(e);var n=this;return n.__filtered__&&(e>0||i<0)?new Fi(n):(e<0?n=n.takeRight(-e):e&&(n=n.drop(e)),i!==t&&(n=(i=uh(i))<0?n.dropRight(-i):n.take(i-e)),n)},Fi.prototype.takeRightWhile=function(t){return this.reverse().takeWhile(t).reverse()},Fi.prototype.toArray=function(){return this.take(l)},wn(Fi.prototype,(function(e,i){var n=/^(?:filter|find|map|reject)|While$/.test(i),r=/^(?:head|last)$/.test(i),s=Di[r?"take"+("last"==i?"Right":""):i],o=r||/^find/.test(i);s&&(Di.prototype[i]=function(){var i=this.__wrapped__,h=r?[1]:arguments,a=i instanceof Fi,l=h[0],u=a||Fo(i),c=function(t){var e=s.apply(Di,Te([t],h));return r&&f?e[0]:e};u&&n&&"function"==typeof l&&1!=l.length&&(a=u=!1);var f=this.__chain__,d=o&&!f,p=a&&!this.__actions__.length;if(!o&&u){i=p?i:new Fi(this);var g=e.apply(i,h);return g.__actions__.push({func:ao,args:[c],thisArg:t}),new Bi(g,f)}return d&&p?e.apply(this,h):(g=this.thru(c),d?r?g.value()[0]:g.value():g)})})),Me(["pop","push","shift","sort","splice","unshift"],(function(t){var e=Ct[t],i=/^(?:push|sort|unshift)$/.test(t)?"tap":"thru",n=/^(?:pop|shift)$/.test(t);Di.prototype[t]=function(){var t=arguments;if(n&&!this.__chain__){var r=this.value();return e.apply(Fo(r)?r:[],t)}return this[i]((function(i){return e.apply(Fo(i)?i:[],t)}))}})),wn(Fi.prototype,(function(t,e){var i=Di[e];if(i){var n=i.name+"";It.call(zi,n)||(zi[n]=[]),zi[n].push({name:e,func:i})}})),zi[Dr(t,2).name]=[{name:"wrapper",func:t}],Fi.prototype.clone=function(){var t=new Fi(this.__wrapped__);return t.__actions__=Ar(this.__actions__),t.__dir__=this.__dir__,t.__filtered__=this.__filtered__,t.__iteratees__=Ar(this.__iteratees__),t.__takeCount__=this.__takeCount__,t.__views__=Ar(this.__views__),t},Fi.prototype.reverse=function(){if(this.__filtered__){var t=new Fi(this);t.__dir__=-1,t.__filtered__=!0}else(t=this.clone()).__dir__*=-1;return t},Fi.prototype.value=function(){var t=this.__wrapped__.value(),e=this.__dir__,i=Fo(t),n=e<0,r=i?t.length:0,s=function(t,e,i){for(var n=-1,r=i.length;++n<r;){var s=i[n],o=s.size;switch(s.type){case"drop":t+=o;break;case"dropRight":e-=o;break;case"take":e=gi(e,t+o);break;case"takeRight":t=pi(t,e-o)}}return{start:t,end:e}}(0,r,this.__views__),o=s.start,h=s.end,a=h-o,l=n?h:o-1,u=this.__iteratees__,c=u.length,f=0,d=gi(a,this.__takeCount__);if(!i||!n&&r==a&&d==a)return ur(t,this.__actions__);var p=[];t:for(;a--&&f<d;){for(var g=-1,m=t[l+=e];++g<c;){var w=u[g],v=w.type,y=(0,w.iteratee)(m);if(2==v)m=y;else if(!y){if(1==v)continue t;break t}}p[f++]=m}return p},Di.prototype.at=lo,Di.prototype.chain=function(){return ho(this)},Di.prototype.commit=function(){return new Bi(this.value(),this.__chain__)},Di.prototype.next=function(){this.__values__===t&&(this.__values__=ah(this.value()));var e=this.__index__>=this.__values__.length;return{done:e,value:e?t:this.__values__[this.__index__++]}},Di.prototype.plant=function(e){for(var i,n=this;n instanceof Li;){var r=Ps(n);r.__index__=0,r.__values__=t,i?s.__wrapped__=r:i=r;var s=r;n=n.__wrapped__}return s.__wrapped__=e,i},Di.prototype.reverse=function(){var e=this.__wrapped__;if(e instanceof Fi){var i=e;return this.__actions__.length&&(i=new Fi(this)),(i=i.reverse()).__actions__.push({func:ao,args:[Ys],thisArg:t}),new Bi(i,this.__chain__)}return this.thru(Ys)},Di.prototype.toJSON=Di.prototype.valueOf=Di.prototype.value=function(){return ur(this.__wrapped__,this.__actions__)},Di.prototype.first=Di.prototype.head,Jt&&(Di.prototype[Jt]=function(){return this}),Di}();ue?((ue.exports=ui)._=ui,le._=ui):ae._=ui}.call(_h.exports)),_h.exports);
2
+ /**
3
+ * @license
4
+ * Lodash <https://lodash.com/>
5
+ * Copyright OpenJS Foundation and other contributors <https://openjsf.org/>
6
+ * Released under MIT license <https://lodash.com/license>
7
+ * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
8
+ * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
9
+ */class Bh{_core;_debounceUpdate;_debounceEndScaling;_animationFrameId=null;initialTouchDistance=0;startX=0;startY=0;static TOUCH_CURSOR_BROADCAST_THRESHOLD=5;_touchStartScreenX=0;_touchStartScreenY=0;_touchCursorBroadcastActive=!1;constructor(t,e){this._core=t,this._core.store.state.host=e,this._core.store.state.viewportWidth=e.clientWidth,this._core.store.state.viewportHeight=e.clientHeight,this._core.store.state.startX=0,this._core.store.state.startY=0,this._core.store.state.translateX=0,this._core.store.state.translateY=0,this._debounceUpdate=Lh.debounce((()=>{this._core.updateWorkspaceViewport(this._core.store.state.translateX,this._core.store.state.translateY,this._core.store.state.scale)}),300),this._debounceEndScaling=Lh.debounce((()=>{this._core.store.state.isScaling=!1,this._core.rerender()}),100)}cancelPendingUpdates(){this._debounceUpdate.cancel()}clampTranslate(t,e){const i=this._core.store.state,{scale:n,viewportWidth:r,viewportHeight:s}=i,{viewportBoundaryLeft:o,viewportBoundaryRight:h,viewportBoundaryTop:a,viewportBoundaryBottom:l}=i,u=-o*n,c=r-h*n,f=-a*n,d=s-l*n;let p=t,g=e;return Number.isFinite(c)&&Number.isFinite(u)?p=Math.max(c,Math.min(u,t)):Number.isFinite(c)?p=Math.max(c,t):Number.isFinite(u)&&(p=Math.min(u,t)),Number.isFinite(d)&&Number.isFinite(f)?g=Math.max(d,Math.min(f,e)):Number.isFinite(d)?g=Math.max(d,e):Number.isFinite(f)&&(g=Math.min(f,e)),{translateX:p,translateY:g}}getEffectiveMinScale(){const t=this._core.store.state,{viewportWidth:e,viewportHeight:i,scaleMin:n}=t,{viewportBoundaryLeft:r,viewportBoundaryRight:s,viewportBoundaryTop:o,viewportBoundaryBottom:h}=t,a=s-r,l=h-o;if(!Number.isFinite(a)||!Number.isFinite(l))return n;const u=Math.max(a>0?e/a:n,l>0?i/l:n);return Math.max(n,u)}handleResize(){this._core.store.state.viewportWidth=this._core.store.host.clientWidth,this._core.store.state.viewportHeight=this._core.store.host.clientHeight,this._core.store.state.hasViewportChanged=!0,this._core.rerender()}handlePointerDown(t){if(this.cancelViewportAnimation(),"mouse"===t.pointerType){const e=t.clientX-this._core.store.offsetX,i=t.clientY-this._core.store.offsetY;t.button===o.Right&&(this._core.store.state.isPanning=!0,this._core.store.state.startX=e,this._core.store.state.startY=i)}if("touch"===t.pointerType||"pen"===t.pointerType){const e=Array.from(this._core.store.state.pointers.values());if(1===e.length&&(this._touchStartScreenX=t.clientX,this._touchStartScreenY=t.clientY,this._touchCursorBroadcastActive=!1),2===e.length){this._core.store.objects?.clearCursorPosition();const t=this._core.store.currentPath;t&&this._core.store.objects.remove((e=>e.id===t.id)),this._core.store.state.isSelecting&&(this._core.store.state.isSelecting=!1,this._core.store.objects.remove((t=>t instanceof gh)),this._core.store.setSelectionBox(null),this._core.store.selectedObjects.forEach((t=>{t.isSelected=!1}))),this._core.store.state.isScaling=!0;const i=e[0].clientX-this._core.store.offsetX,n=e[0].clientY-this._core.store.offsetY,r=e[1].clientX-this._core.store.offsetX,s=e[1].clientY-this._core.store.offsetY;this.initialTouchDistance=Math.sqrt(Math.pow(i-r,2)+Math.pow(n-s,2)),this.startX=(i+r)/2,this.startY=(n+s)/2,this._core.rerender()}}}handlePointerMove(t){if("mouse"===t.pointerType){const e=this._core.store.host.getBoundingClientRect(),i=t.clientX-e.left,n=t.clientY-e.top;if(this._core.store.state.pointerX=(i-this._core.store.state.translateX)/this._core.store.state.scale,this._core.store.state.pointerY=(n-this._core.store.state.translateY)/this._core.store.state.scale,this._core.store.objects?.updateCursorPosition(this._core.store.state.pointerX,this._core.store.state.pointerY),this._core.store.state.isPanning){const t=this.clampTranslate(this._core.store.state.translateX+(i-this._core.store.state.startX),this._core.store.state.translateY+(n-this._core.store.state.startY));this._core.store.state.translateX=t.translateX,this._core.store.state.translateY=t.translateY,this._core.store.state.startX=i,this._core.store.state.startY=n,this._core.store.state.hasViewportChanged=!0,this._core.store.state.skipContextMenu=!0,this._core.rerender(),this._debounceUpdate()}}if("touch"===t.pointerType||"pen"===t.pointerType){const e=this._core.store.host.getBoundingClientRect(),i=t.clientX-e.left,n=t.clientY-e.top,r=Array.from(this._core.store.state.pointers.values());if(this._core.store.state.isScaling||r.length>1)this._core.store.objects?.clearCursorPosition();else{if(this._core.store.state.pointerX=(i-this._core.store.state.translateX)/this._core.store.state.scale,this._core.store.state.pointerY=(n-this._core.store.state.translateY)/this._core.store.state.scale,!this._touchCursorBroadcastActive){const e=t.clientX-this._touchStartScreenX,i=t.clientY-this._touchStartScreenY;Math.sqrt(e*e+i*i)>=Bh.TOUCH_CURSOR_BROADCAST_THRESHOLD&&(this._touchCursorBroadcastActive=!0)}this._touchCursorBroadcastActive&&this._core.store.objects?.updateCursorPosition(this._core.store.state.pointerX,this._core.store.state.pointerY)}if(2===r.length){const t=r[0].clientX-this._core.store.offsetX,e=r[0].clientY-this._core.store.offsetY,i=r[1].clientX-this._core.store.offsetX,n=r[1].clientY-this._core.store.offsetY,s=Math.sqrt(Math.pow(t-i,2)+Math.pow(e-n,2)),o=(t+i)/2,h=(e+n)/2,a=s/this.initialTouchDistance,l=this._core.store.state.scale*a,u=this.getEffectiveMinScale();if(l>this._core.store.state.scaleMax||l<u){const t=this.clampTranslate(this._core.store.state.translateX+o-this.startX,this._core.store.state.translateY+h-this.startY);this._core.store.state.translateX=t.translateX,this._core.store.state.translateY=t.translateY}else{const t=this._core.store.state.translateX+o-this.startX-(o-this._core.store.state.translateX)*(a-1),e=this._core.store.state.translateY+h-this.startY-(h-this._core.store.state.translateY)*(a-1);this._core.store.state.scale=l;const i=this.clampTranslate(t,e);this._core.store.state.translateX=i.translateX,this._core.store.state.translateY=i.translateY,this.initialTouchDistance=s}this.startX=o,this.startY=h,this._core.store.state.hasViewportChanged=!0,this._core.rerender(),this._debounceUpdate()}}}handlePointerUp(t){"mouse"===t.pointerType&&this._core.store.state.isPanning&&(this._core.store.state.isPanning=!1,this._core.rerender()),"touch"!==t.pointerType&&"pen"!==t.pointerType||(this._touchCursorBroadcastActive=!1,0===this._core.store.state.pointers.size&&this._debounceEndScaling())}handleWheel(t){this.cancelViewportAnimation(),t.ctrlKey?this.handleZoom(t):this.handlePan(t)}getViewport(){const t=this._core.store.state;return{translateX:t.translateX,translateY:t.translateY,scale:t.scale,width:t.viewportWidth,height:t.viewportHeight}}screenToWorld(t,e){const i=this._core.store.state;return{x:(t-i.translateX)/i.scale,y:(e-i.translateY)/i.scale}}worldToScreen(t,e){const i=this._core.store.state;return{x:t*i.scale+i.translateX,y:e*i.scale+i.translateY}}setViewport(t,e,i){const n=this._core.store.state,r=Math.min(n.scaleMax,Math.max(this.getEffectiveMinScale(),i));this.animateViewportTo(n.viewportWidth/2-t*r,n.viewportHeight/2-e*r,r)}panTo(t,e){this.setViewport(t,e,this._core.store.state.scale)}zoomTo(t,e,i){const n=this._core.store.state;void 0!==e&&void 0!==i?this.setViewport(e,i,t):this.setViewport((n.viewportWidth/2-n.translateX)/n.scale,(n.viewportHeight/2-n.translateY)/n.scale,t)}zoomIn(t,e){this.animateZoomAroundViewportCenter(t,e)}zoomOut(t,e){this.animateZoomAroundViewportCenter(1/t,e)}animateZoomAroundViewportCenter(t,e){this.cancelViewportAnimation();const i=this._core.store.state,n=i.scale,r=this.getEffectiveMinScale(),s=Math.min(i.scaleMax,Math.max(r,n*t)),o=i.viewportWidth/2,h=i.viewportHeight/2,a=(o-i.translateX)/n,l=(h-i.translateY)/n;if(s===n||e<=0)return this.applyZoomAroundCenter(s,o,h,a,l),i.isScaling=!0,this._core.rerender(),this._debounceUpdate(),void this._debounceEndScaling();const u=performance.now();i.isScaling=!0;const c=t=>{const r=Math.min((t-u)/e,1),f=r<.5?4*r*r*r:1-Math.pow(-2*r+2,3)/2;this.applyZoomAroundCenter(n+(s-n)*f,o,h,a,l),this._core.rerender(),r<1?this._animationFrameId=requestAnimationFrame(c):(this._animationFrameId=null,i.isScaling=!1,this._core.rerender(),this._debounceUpdate())};this._animationFrameId=requestAnimationFrame(c)}applyZoomAroundCenter(t,e,i,n,r){const s=this._core.store.state;s.scale=t;const o=this.clampTranslate(e-n*t,i-r*t);s.translateX=o.translateX,s.translateY=o.translateY,s.hasViewportChanged=!0}centerInViewport(t){const{scale:e,viewportWidth:i,viewportHeight:n}=this._core.store.state,{x:r,y:s,width:o,height:h}=t.rotatedBoundingBox,a=this.clampTranslate(i/2-(r+o/2)*e,n/2-(s+h/2)*e);this._core.store.state.translateX=a.translateX,this._core.store.state.translateY=a.translateY,this._core.store.state.hasViewportChanged=!0,this._core.rerender(),this._debounceUpdate()}centerFitInViewport(t){const e=Math.min(this._core.store.state.viewportWidth/(1.1*t.rotatedBoundingBox.width),this._core.store.state.viewportHeight/(1.1*t.rotatedBoundingBox.height),this._core.store.state.scaleMax),i=Math.max(e,this.getEffectiveMinScale());this._core.store.state.scale=i,this.centerInViewport(t)}centerFitInViewportIfNeeded(t){const e=Math.min(this._core.store.state.viewportWidth/(1.1*t.rotatedBoundingBox.width),this._core.store.state.viewportHeight/(1.1*t.rotatedBoundingBox.height),this._core.store.state.scaleMax),i=Math.max(e,this.getEffectiveMinScale());i<this._core.store.state.scale&&(this._core.store.state.scale=i),this.centerInViewport(t)}fitInViewportIfNeeded(t){const e=Math.min(this._core.store.state.viewportWidth/(1.1*t.rotatedBoundingBox.width),this._core.store.state.viewportHeight/(1.1*t.rotatedBoundingBox.height),this._core.store.state.scaleMax),i=Math.max(e,this.getEffectiveMinScale());i<this._core.store.state.scale&&(this._core.store.state.scale=i,this.centerInViewport(t))}bringIntoViewIfNeeded(t){const{scale:e,translateX:i,translateY:n,viewportWidth:r,viewportHeight:s}=this._core.store.state,o=t.rotatedBoundingBox;if(o.x*e+i>=0&&o.y*e+n>=0&&(o.x+o.width)*e+i<=r&&(o.y+o.height)*e+n<=s)return;const h=Math.min(r/(1.1*o.width),s/(1.1*o.height),this._core.store.state.scaleMax),a=Math.max(h,this.getEffectiveMinScale()),l=Math.min(a,e),u=this.clampTranslate(r/2-(o.x+o.width/2)*l,s/2-(o.y+o.height/2)*l);this.animateViewportTo(u.translateX,u.translateY,l)}handleZoom(t){this._core.store.state.isScaling=!0;const e=this._core.store.host.getBoundingClientRect(),i=t.clientX-e.left,n=t.clientY-e.top;this._core.store.state.pointerX=(i-this._core.store.state.translateX)/this._core.store.state.scale,this._core.store.state.pointerY=(n-this._core.store.state.translateY)/this._core.store.state.scale,this._core.store.objects?.updateCursorPosition(this._core.store.state.pointerX,this._core.store.state.pointerY);const r=Math.max(.8,Math.min(1.2,1+-.012*t.deltaY)),s=this.getEffectiveMinScale(),o=Math.min(this._core.store.state.scaleMax,Math.max(s,this._core.store.state.scale*r)),h=o/this._core.store.state.scale,a=(i-this._core.store.state.translateX)*(h-1),l=(n-this._core.store.state.translateY)*(h-1);this._core.store.state.scale=o;let u=this._core.store.state.translateX-a;0!==t.deltaX&&(u-=.8*t.deltaX);const c=this.clampTranslate(u,this._core.store.state.translateY-l);this._core.store.state.translateX=c.translateX,this._core.store.state.translateY=c.translateY,this._core.store.state.hasViewportChanged=!0,this._core.rerender(),this._debounceUpdate(),this._debounceEndScaling()}handlePan(t){const e=this.clampTranslate(this._core.store.state.translateX-.8*t.deltaX,this._core.store.state.translateY-.8*t.deltaY);this._core.store.state.translateX=e.translateX,this._core.store.state.translateY=e.translateY,this._core.store.state.hasViewportChanged=!0,this._core.rerender(),this._debounceUpdate()}cancelViewportAnimation(){null!==this._animationFrameId&&(cancelAnimationFrame(this._animationFrameId),this._animationFrameId=null)}animateViewportTo(t,e,i,n=150){this.cancelViewportAnimation();const r=this._core.store.state.translateX,s=this._core.store.state.translateY,o=this._core.store.state.scale,h=performance.now();this._core.store.state.isScaling=!0;const a=l=>{const u=Math.min((l-h)/n,1),c=1-Math.pow(1-u,3);this._core.store.state.scale=o+(i-o)*c;const f=this.clampTranslate(r+(t-r)*c,s+(e-s)*c);this._core.store.state.translateX=f.translateX,this._core.store.state.translateY=f.translateY,this._core.store.state.hasViewportChanged=!0,this._core.rerender(),u<1?this._animationFrameId=requestAnimationFrame(a):(this._animationFrameId=null,this._core.store.state.isScaling=!1,this._core.rerender(),this._debounceUpdate())};this._animationFrameId=requestAnimationFrame(a)}centerFitNearestContent(t=20){const e=this._core.store.allNonSelectionObjects;if(0===e.length)return!1;const i=-this._core.store.state.translateX/this._core.store.state.scale+this._core.store.state.viewportWidth/2/this._core.store.state.scale,n=-this._core.store.state.translateY/this._core.store.state.scale+this._core.store.state.viewportHeight/2/this._core.store.state.scale,r=e.map((t=>{const e=t.rotatedBoundingBox,r=e.y+e.height/2;return{obj:t,distance:Math.sqrt(Math.pow(e.x+e.width/2-i,2)+Math.pow(r-n,2))}}));r.sort(((t,e)=>t.distance-e.distance));const s=r.slice(0,t).map((t=>t.obj));let o=1/0,h=1/0,a=-1/0,l=-1/0;for(const t of s){const e=t.rotatedBoundingBox;o=Math.min(o,e.x),h=Math.min(h,e.y),a=Math.max(a,e.x+e.width),l=Math.max(l,e.y+e.height)}const u=a-o,c=l-h,f=o+u/2,d=h+c/2,p=Math.min(this._core.store.state.viewportWidth/(1.1*u),this._core.store.state.viewportHeight/(1.1*c),this._core.store.state.scaleMax),g=Math.max(p,this.getEffectiveMinScale());return this.animateViewportTo(this._core.store.state.viewportWidth/2-f*g,this._core.store.state.viewportHeight/2-d*g,g),!0}centerFitObjects(t,e=!0){if(0===t.length)return!1;let i=1/0,n=1/0,r=-1/0,s=-1/0;for(const e of t){const t=e.rotatedBoundingBox;i=Math.min(i,t.x),n=Math.min(n,t.y),r=Math.max(r,t.x+t.width),s=Math.max(s,t.y+t.height)}const o=r-i,h=s-n,a=i+o/2,l=n+h/2,u=Math.min(this._core.store.state.viewportWidth/(1.1*o),this._core.store.state.viewportHeight/(1.1*h),this._core.store.state.scaleMax),c=Math.max(u,this.getEffectiveMinScale());return this.animateViewportTo(this._core.store.state.viewportWidth/2-a*c,this._core.store.state.viewportHeight/2-l*c,c,e?150:0),!0}centerFitAllObjects(t=!0){return this.centerFitObjects(this._core.store.allNonSelectionObjects,t)}}class Fh extends uh{shortcuts=[{key:"Escape",label:"Clear Selection",category:"General",condition:t=>!!t.store.activeText||!!t.store.activeShape||!!t.store.selectionGroup,action:t=>{t.store.activeText?t.store.activeText.handleEscape():t.store.activeShape?t.store.activeShape.handleEscape():t.clearSelection()}},{key:"Delete",label:"Delete Selected",category:"General",condition:t=>!!t.store.selectionGroup,action:t=>t.delete()},{key:"a",ctrl:!0,label:"Select All in Viewport",category:"General",action:t=>t.selectAllObjectsInViewport()},{key:"A",ctrl:!0,shift:!0,label:"Select All Objects",category:"General",action:t=>t.selectAllObjects()},{key:"z",ctrl:!0,label:"Undo",category:"Undo/Redo",action:t=>t.undo()},{key:"y",ctrl:!0,label:"Redo",category:"Undo/Redo",action:t=>t.redo()},{key:"1",ctrl:!0,label:"Tool 1",category:"Tool Selection",action:()=>this.switchToolByIndex(0)},{key:"2",ctrl:!0,label:"Tool 2",category:"Tool Selection",action:()=>this.switchToolByIndex(1)},{key:"3",ctrl:!0,label:"Tool 3",category:"Tool Selection",action:()=>this.switchToolByIndex(2)},{key:"4",ctrl:!0,label:"Tool 4",category:"Tool Selection",action:()=>this.switchToolByIndex(3)},{key:"5",ctrl:!0,label:"Tool 5",category:"Tool Selection",action:()=>this.switchToolByIndex(4)},{key:"6",ctrl:!0,label:"Tool 6",category:"Tool Selection",action:()=>this.switchToolByIndex(5)},{key:"7",ctrl:!0,label:"Tool 7",category:"Tool Selection",action:()=>this.switchToolByIndex(6)},{key:"8",ctrl:!0,label:"Tool 8",category:"Tool Selection",action:()=>this.switchToolByIndex(7)},{key:"9",ctrl:!0,label:"Tool 9",category:"Tool Selection",action:()=>this.switchToolByIndex(8)},{key:"+",ctrl:!0,label:"Bring Forward",category:"Object Layering",condition:t=>!!t.store.selectionGroup,action:t=>t.bringForward()},{key:"-",ctrl:!0,label:"Send Backward",category:"Object Layering",condition:t=>!!t.store.selectionGroup,action:t=>t.sendBackward()},{key:"*",shift:!0,label:"Bring to Front",category:"Object Layering",condition:t=>!!t.store.selectionGroup,action:t=>t.bringToFront()},{key:"_",shift:!0,label:"Send to Back",category:"Object Layering",condition:t=>!!t.store.selectionGroup,action:t=>t.sendToBack()},{key:"g",ctrl:!0,label:"Group",category:"Grouping",condition:t=>!!t.store.selectionGroup&&t.store.selectionGroup.objects.length>=2,action:t=>t.group()},{key:"G",ctrl:!0,shift:!0,label:"Ungroup",category:"Grouping",condition:t=>!!t.store.selectionGroup,action:t=>t.ungroup()},{key:"ArrowUp",label:"Move Object Up",category:"Movement",condition:t=>!!t.store.selectionGroup,action:t=>{t.store.selectionGroup.move(0,0,0,10),t.rerender()}},{key:"ArrowDown",label:"Move Object Down",category:"Movement",condition:t=>!!t.store.selectionGroup,action:t=>{t.store.selectionGroup.move(0,10,0,0),t.rerender()}},{key:"ArrowLeft",label:"Move Object Left",category:"Movement",condition:t=>!!t.store.selectionGroup,action:t=>{t.store.selectionGroup.move(0,0,10,0),t.rerender()}},{key:"ArrowRight",label:"Move Object Right",category:"Movement",condition:t=>!!t.store.selectionGroup,action:t=>{t.store.selectionGroup.move(10,0,0,0),t.rerender()}}];constructor(t){super(t)}switchToolByIndex(t){const e=this._core.toolRegistry.getToolByIndex(t);e&&(this._core.store.setState("activeTool",e),this._core.deselectAllObjects(),e.onActivate())}handleKeyDown(t){if(this._core.store.state.isCtrlKeyPressed=t.ctrlKey,(this._core.store.activeText||this._core.store.activeShape||this._core.store.activeInteractiveCustomElement)&&"Escape"!==t.key)return;const e=this.shortcuts.find((e=>e.key===t.key&&!!e.ctrl===t.ctrlKey&&!!e.shift===t.shiftKey&&(!e.condition||e.condition(this._core))));e&&(t.preventDefault(),e.action(this._core))}handleKeyUp(t){this._core.store.state.isCtrlKeyPressed=t.ctrlKey}getDisplayableShortcuts(){return this.shortcuts.map((({key:t,ctrl:e,shift:i,label:n,category:r})=>({key:t,ctrl:e,shift:i,label:n,category:r})))}}class Nh extends uh{globalContextMenuItems=[];objectContextMenuItems=[];constructor(t,e,i){super(t),this.globalContextMenuItems=e,this.objectContextMenuItems=i}resolveLabels(t){return t.map((t=>({...t,label:this._core.localizationManager.translate(t.label),children:t.children?this.resolveLabels(t.children):void 0})))}getResolvedContextMenuItems(){return this.resolveLabels(this._core.store.selectionGroup?this.objectContextMenuItems:this.globalContextMenuItems)}handleContextMenu(t){if("selection"!==this._core.store.state.activeTool?.toolType)return;if(this._core.store.state.skipContextMenu)return void(this._core.store.state.skipContextMenu=!1);const e=this._core.store.state.activeTool;e?.moveHandler?.cancelPendingDrag(),this._core.store.selectionBox&&(this._core.store.objects.remove((t=>t instanceof gh)),this._core.store.setSelectionBox(null),this._core.store.state.isSelecting=!1);const i=this._core.getObjectFromPointerEvent(t,".object");if(i&&!(i instanceof So)&&!(i instanceof gh)){const t=So.create(this._core);t.addOrRemove(i),t.isSelected=!0,t.rotation=i.rotation,this._core.store.state.isSelecting=!1,this._core.store.selectionGroup&&this._core.removeSelectionGroup(),this._core.addSelectionGroup(t),this._core.rerender()}this._core.store.state.contextMenuItems=this.getResolvedContextMenuItems();const n=t.clientX-this._core.store.offsetX,r=t.clientY-this._core.store.offsetY,{translateX:s,translateY:o,scale:h}=this._core.store.state;this._core.store.state.contextMenuWorldX=(n-s)/h,this._core.store.state.contextMenuWorldY=(r-o)/h;let a=n,l=r;a+150>this._core.store.state.viewportWidth-10&&(a=this._core.store.state.viewportWidth-150-10),a=Math.max(10,a),l=Math.max(10,l),this._core.store.state.contextMenuX=a,this._core.store.state.contextMenuY=l,this._core.store.state.isContextMenuVisible=!0,this._core.store.state.isEnabled=!1,this._core.rerender()}open(t){const{x:e,y:i,objectId:n}=t;if("selection"===this._core.store.state.activeTool?.toolType){const t=this._core.store.state.activeTool;t?.moveHandler?.cancelPendingDrag()}if(this._core.store.selectionBox&&(this._core.store.objects.remove((t=>t instanceof gh)),this._core.store.setSelectionBox(null),this._core.store.state.isSelecting=!1),n){const t=this._core.store.allObjects.find((t=>t.id===n));if(t&&!(t instanceof So)&&!(t instanceof gh)){const e=So.create(this._core);e.addOrRemove(t),e.isSelected=!0,e.rotation=t.rotation,this._core.store.state.isSelecting=!1,this._core.store.selectionGroup&&this._core.removeSelectionGroup(),this._core.addSelectionGroup(e)}}this._core.store.state.contextMenuItems=this.getResolvedContextMenuItems(),this._core.store.state.contextMenuWorldX=e,this._core.store.state.contextMenuWorldY=i;const{translateX:r,translateY:s,scale:o}=this._core.store.state;let h=e*o+r,a=i*o+s;h+150>this._core.store.state.viewportWidth-10&&(h=this._core.store.state.viewportWidth-150-10),h=Math.max(10,h),a=Math.max(10,a),this._core.store.state.contextMenuX=h,this._core.store.state.contextMenuY=a,this._core.store.state.isContextMenuVisible=!0,this._core.store.state.isEnabled=!1,this._core.rerender()}}class Wh{_core;constructor(t){this._core=t}revive(t){if(t&&"object"==typeof t){if(t.__class__){let e;switch(t.__class__){case"KritzelPath":e=c.create(this._core).deserialize(t);break;case"KritzelLine":e=f.create(this._core).deserialize(t);break;case"KritzelText":e=no.create(this._core,t.fontSize,t.fontFamily).deserialize(t);break;case"KritzelShape":e=po.create(this._core,{shapeType:t.shapeType,fillColor:t.fillColor,strokeColor:t.strokeColor,strokeWidth:t.strokeWidth,fontSize:t.fontSize,fontFamily:t.fontFamily,fontColor:t.fontColor}).deserialize(t);break;case"KritzelImage":e=lo.create(this._core).deserialize(t);break;case"KritzelCustomElement":e=wo.create(this._core).deserialize(t);break;case"KritzelSelectionGroup":e=So.create(this._core).deserialize(t);break;case"KritzelGroup":e=co.create(this._core).deserialize(t);break;case"KritzelWorkspace":e=x.create(this._core,t).deserialize(t);break;case"KritzelBrushTool":e=new Mo(this._core);break;case"KritzelEraserTool":e=new Ao(this._core);break;case"KritzelImageTool":e=new oh(this._core);break;case"KritzelSelectionTool":e=new yh(this._core);break;case"KritzelTextTool":e=new hh(this._core);break;case"KritzelLineTool":e=new xo(this._core);break;case"KritzelShapeTool":e=new ah(this._core);break;default:e=t}return e}const e=Array.isArray(t)?[]:{};for(const i in t)Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=this.revive(t[i]));return e}return t}}const Uh={activeWorkspace:void 0,activeTool:null,objects:null,snapCandidate:null,snapPreviewCandidate:null,resizeHandleType:null,lineHandleType:null,hasViewportChanged:!1,hasObjectsChanged:!1,isReady:!1,isEnabled:!0,isScaling:!1,isPanning:!1,isSelecting:!1,isResizing:!1,isResizeHandleHovered:!1,isResizeHandleSelected:!1,isRotating:!1,isRotationHandleHovered:!1,isRotationHandleSelected:!1,isLineHandleSelected:!1,isLineHandleDragging:!1,isDragging:!1,isDrawing:!1,isErasing:!1,isWriting:!1,isLoading:!1,isCtrlKeyPressed:!1,isContextMenuVisible:!1,contextMenuItems:[],contextMenuX:0,contextMenuY:0,contextMenuWorldX:0,contextMenuWorldY:0,skipContextMenu:!1,debugInfo:{showObjectInfo:!1,showViewportInfo:!1,showSyncProviderInfo:!1,showAssetResolverInfo:!1,showMigrationInfo:!1},host:null,pointerX:0,pointerY:0,scale:1,scaleMax:1,scaleMin:1,startX:0,startY:0,translateX:0,translateXMax:400,translateXMin:0,translateY:0,translateYMax:400,translateYMin:0,viewportWidth:0,viewportHeight:0,longTouchTimeout:null,longTouchDelay:300,pointers:new Map,workspaces:[],cursor:{icon:"default",iconActive:"default"},lockDrawingScale:!0,viewportBoundaryLeft:-1/0,viewportBoundaryRight:1/0,viewportBoundaryTop:-1/0,viewportBoundaryBottom:1/0};class Kh{static calculateSelectionBounds(t){const e=t.map((t=>t.rotatedBoundingBox));return{minX:Math.min(...e.map((t=>t.x))),minY:Math.min(...e.map((t=>t.y))),maxX:Math.max(...e.map((t=>t.x+t.width))),maxY:Math.max(...e.map((t=>t.y+t.height)))}}static calculateAlignedPositions(t,e){const i=new Map;if(t.length<2)return i;const n=this.calculateSelectionBounds(t);for(const r of t){const t=r.rotatedBoundingBox;let s=r.translateX,o=r.translateY;const h=t.x-r.translateX,a=t.y-r.translateY;switch(e){case Th.StartHorizontal:s=n.minX-h;break;case Th.CenterHorizontal:s=r.translateX+((n.minX+n.maxX)/2-(t.x+t.width/2));break;case Th.EndHorizontal:s=r.translateX+(n.maxX-(t.x+t.width));break;case Th.StartVertical:o=n.minY-a;break;case Th.CenterVertical:o=r.translateY+((n.minY+n.maxY)/2-(t.y+t.height/2));break;case Th.EndVertical:o=r.translateY+(n.maxY-(t.y+t.height))}i.set(r.id,{translateX:s,translateY:o})}return i}}class Hh{core;registry={};constructor(t){this.core=t}registerTool(t,e){const i=new e(this.core);return i.name=t,this.registry[t]=i,i}hasTool(t){return t in this.registry}getTool(t){return this.registry[t]||(console.warn(`Unknown tool: ${t}`),null)}getToolByIndex(t){return Object.values(this.registry)[t]??null}}class Vh{bounds;capacity;objects=[];children=null;_size=0;get size(){return this._size}constructor(t,e=16){this.bounds=t,this.capacity=e}reset(){this.objects=[],this.children=null,this._size=0}insert(t){if(!this.intersects(t.rotatedBoundingBox,this.bounds))return!1;if(this.objects.length<this.capacity&&null===this.children)return this.objects.push(t),this._size++,!0;null===this.children&&this.subdivide();for(const e of this.children)if(e.insert(t))return this._size++,!0;return!1}update(t){const e=this.objects.findIndex((e=>e.id===t.id));if(-1!==e)return this.objects[e]=t,!0;if(null!==this.children)for(const e of this.children)if(e.update(t))return!0;return!1}reindex(t){const e=this.remove((e=>e.id===t.id));return 0!==e&&this.insert(t)}remove(t){let e=0;const i=this.objects.findIndex((e=>t(e)));if(-1!==i&&(this.objects.splice(i,1),e++),null!==this.children)for(const i of this.children)e+=i.remove(t);return this._size-=e,e}query(t){const e=[];return this._queryInto(t,e),e}_queryInto(t,e){if(this.intersects(t,this.bounds)){for(const i of this.objects)this.intersects(i.rotatedBoundingBox,t)&&e.push(i);if(null!==this.children)for(const i of this.children)i._queryInto(t,e)}}filter(t){const e=[];return this._filterInto(t,e),e}_filterInto(t,e){for(const i of this.objects)t(i)&&e.push(i);if(null!==this.children)for(const i of this.children)i._filterInto(t,e)}allObjects(){const t=[];return this._collectAllInto(t),t}_collectAllInto(t){for(const e of this.objects)t.push(e);if(null!==this.children)for(const e of this.children)e._collectAllInto(t)}subdivide(){const{x:t,y:e,z:i,width:n,height:r}=this.bounds,s=n/2,o=r/2;this.children=[new Vh({x:t,y:e,z:i,width:s,height:o},this.capacity),new Vh({x:t+s,y:e,z:i,width:s,height:o},this.capacity),new Vh({x:t,y:e+o,z:i,width:s,height:o},this.capacity),new Vh({x:t+s,y:e+o,z:i,width:s,height:o},this.capacity)]}intersects(t,e){return!(t.x>=e.x+e.width||t.x+t.width<=e.x||t.y>=e.y+e.height||t.y+t.height<=e.y)}}class Gh{quadtree;_ydoc=null;_objectsMap=null;_metadataMap=null;_providers=[];_undoManager=null;_reviver=null;_core=null;_workspaceId=null;_isReady=!1;_temporaryItemsCount=0;_idMap=new Map;_awareness=null;_networkSyncPromise=null;_objectsObserver=null;_stackItemAddedHandler=null;_stackItemPoppedHandler=null;_awarenessChangeHandler=null;_awarenessChangeCallbacks=[];_objectsChangeCallbacks=[];_lastAwarenessEmitTime=0;_awarenessEmitTimeout=null;AWARENESS_THROTTLE_INTERVAL=100;_localOnlyMode=!1;_inTransaction=!1;get isReady(){return this._isReady}whenNetworkSynced(){return this._networkSyncPromise??Promise.resolve()}get awareness(){return this._awareness}get hasAwareness(){return!!this._awareness}get localClientId(){return this._awareness?.clientID??null}setLocalUser(t){if(!this._awareness||!t)return;const e=t.displayName||t.firstName||"Anonymous";this._awareness.setLocalStateField("user",{id:t.id,displayName:e,color:t.color||this.generateColorFromName(e)})}generateColorFromName(t){let e=0;for(let i=0;i<t.length;i++)e=t.charCodeAt(i)+((e<<5)-e);return`hsl(${Math.abs(e%360)}, 45%, 55%)`}updateCursorPosition(t,e){this._awareness&&this._awareness.setLocalStateField("cursor",{x:t,y:e})}clearCursorPosition(){this._awareness&&this._awareness.setLocalStateField("cursor",null)}setActiveDrawingObject(t){this._awareness&&this._awareness.setLocalStateField("activeObjectId",t)}setLocalSelectionBox(t){this._awareness&&this._awareness.setLocalStateField("selectionBox",t)}clearLocalSelectionBox(){this._awareness&&this._awareness.setLocalStateField("selectionBox",null)}removeOrphanedSelectionGroups(){if(!this._awareness)return;const t=this._awareness.getStates(),e=new Set;t.forEach((t=>{const i=t.user?.id;i&&e.add(i)}));const i=this._core?.user?.id,n=this.quadtree.filter((t=>t instanceof So&&null!=t.userId&&t.userId!==i&&!e.has(t.userId)));for(const t of n)this.quadtree.remove((e=>e.id===t.id)),this._idMap.delete(t.id),this._objectsMap&&this._ydoc.transact((()=>{this._objectsMap.delete(t.id)}),"local");n.length>0&&(this._core?.store.invalidateSelectionCache(),this._core?.rerender())}onAwarenessChange(t){return this._awarenessChangeCallbacks.push(t),()=>{this._awarenessChangeCallbacks=this._awarenessChangeCallbacks.filter((e=>e!==t))}}onObjectsChange(t){return this._objectsChangeCallbacks.push(t),()=>{this._objectsChangeCallbacks=this._objectsChangeCallbacks.filter((e=>e!==t))}}get undoManager(){return this._undoManager}get workspaceId(){return this._workspaceId}get undoState(){return{canUndo:!!this._undoManager&&this._undoManager.canUndo(),canRedo:!!this._undoManager&&this._undoManager.canRedo(),undoStackSize:this._undoManager?this._undoManager.undoStack.length:0,redoStackSize:this._undoManager?this._undoManager.redoStack.length:0}}get totalCount(){return this.quadtree.size}findById(t){return this._idMap.get(t)}constructor(){this.quadtree=new Vh({x:-1/0,y:-1/0,z:0,width:1/0,height:1/0},8)}async initialize(t,e,i){this._core=t,this._workspaceId=e,this._reviver=new Wh(t),this._ydoc=new E.Doc,this._objectsMap=this._ydoc.getMap("objects"),this._metadataMap=this._ydoc.getMap("metadata");const n=t.editorId?`kritzel-workspace-${t.editorId}-${e}`:`kritzel-workspace-${e}`,r=i??jh,s=!!t.store?.state?.debugInfo?.showSyncProviderInfo,o=!s;for(const t of r.providers){let e;e="function"==typeof t?new t(n,this._ydoc,{quiet:o}):t.create(n,this._ydoc,{quiet:o}),this._providers.push(e)}if(s){const t=this._providers.map((t=>`${t.constructor.name} (${t.type})`)).join(", ");console.info(`[Kritzel] Workspace sync providers initialized for ${n}: ${t||"none"}`)}this._undoManager=new E.UndoManager([this._objectsMap],{captureTimeout:Number.MAX_SAFE_INTEGER,trackedOrigins:new Set(["local","temporary"]),ignoreRemoteMapChanges:!0}),this._stackItemAddedHandler=t=>{"undo"===t.type&&"temporary"===t.origin&&this._temporaryItemsCount++},this._stackItemPoppedHandler=t=>{"undo"===t.type&&"temporary"===t.origin&&this._temporaryItemsCount>0&&this._temporaryItemsCount--},this._undoManager.on("stack-item-added",this._stackItemAddedHandler),this._undoManager.on("stack-item-popped",this._stackItemPoppedHandler),this._objectsObserver=t=>{this.handleObjectsChange(t)},this._objectsMap.observe(this._objectsObserver);const h=this._providers.filter((t=>"local"===t.type)),a=this._providers.filter((t=>"network"===t.type)),l=await Promise.allSettled(h.map((t=>t.connect())));if(s){const t=l.filter((t=>"fulfilled"===t.status)).length;console.info(`[Kritzel] Workspace local providers connected: ${t}/${h.length}`)}l.forEach(((t,e)=>{s&&"rejected"===t.status&&console.error(`[Kritzel] Sync provider "${h[e]?.constructor.name}" failed to connect:`,t.reason)})),s&&a.length>0&&console.info(`[Kritzel] Workspace network providers connecting in background: ${a.length}`);const u=a.map((t=>t.connect().catch((e=>{s&&console.error(`[Kritzel] Network sync provider "${t.constructor.name}" failed to connect:`,e)}))));this._networkSyncPromise=u.length>0?Promise.allSettled(u).then((()=>{})):null,this._isReady=!0;for(const t of a)if(t.awareness){this._awareness=t.awareness;break}this._awareness&&(this._awarenessChangeHandler=t=>{t.removed.length>0&&this.removeOrphanedSelectionGroups();const e=Date.now(),i=e-this._lastAwarenessEmitTime;if(null!==this._awarenessEmitTimeout&&(clearTimeout(this._awarenessEmitTimeout),this._awarenessEmitTimeout=null),i>=this.AWARENESS_THROTTLE_INTERVAL){this._lastAwarenessEmitTime=e;const t=this._awareness.getStates();for(const e of this._awarenessChangeCallbacks)e(t)}else this._awarenessEmitTimeout=setTimeout((()=>{this._lastAwarenessEmitTime=Date.now(),this._awarenessEmitTimeout=null;const t=this._awareness.getStates();for(const e of this._awarenessChangeCallbacks)e(t)}),this.AWARENESS_THROTTLE_INTERVAL-i),"function"==typeof this._awarenessEmitTimeout.unref&&this._awarenessEmitTimeout.unref()},this._awareness.on("change",this._awarenessChangeHandler)),this.initializeMetadata("workspace",e,t.store?.state?.activeWorkspace?.name??""),Eh(this._ydoc,this._metadataMap,{objects:this._objectsMap},Ih,O,{quiet:!t.store?.state?.debugInfo?.showMigrationInfo}),this.loadFromYjs()}handleObjectsChange(t){if("local"===t.transaction.origin||"temporary"===t.transaction.origin)return void this._core?.rerender();if("migration"===t.transaction.origin)return;const e=Array.from(t.keysChanged),i=[],n=[],r=[];let s=!1;e.forEach((e=>{const o=t.changes.keys.get(e);if(o&&"delete"===o.action)r.push(e),this._idMap.get(e)instanceof f&&(s=!0);else{const t=this._objectsMap?.get(e);if(t){const e=this._reviver?.revive(t);e instanceof So?n.push(e):(i.push(e),e instanceof f&&(s=!0))}}})),r.forEach((t=>{const e=this._idMap.get(t);e instanceof So&&e.deselectAllChildren?.(),this.quadtree.remove((e=>e.id===t)),this._idMap.delete(t)}));const o=[],h=[];i.forEach((t=>{if(this._idMap.has(t.id)){const e=this._idMap.get(t.id);e&&"function"==typeof t.adoptTransientStateFrom&&t.adoptTransientStateFrom(e),this.quadtree.reindex(t),this._idMap.set(t.id,t),h.push(t)}else this.quadtree.insert(t),this._idMap.set(t.id,t),o.push(t)}));const a=new Set;if(n.forEach((t=>{if(this._idMap.has(t.id)){const e=this._idMap.get(t.id);e&&"function"==typeof t.adoptTransientStateFrom&&t.adoptTransientStateFrom(e),this.quadtree.reindex(t),this._idMap.set(t.id,t)}else this.quadtree.insert(t),this._idMap.set(t.id,t);a.add(t.id),t.invalidateObjectsCache(),t.refreshObjectDimensions(void 0,!0),t.captureUnchangedSnapshots(),this.quadtree.reindex(t)})),i.length>0||r.length>0){const t=new Set([...i.map((t=>t.id)),...r]),e=this.quadtree.filter((t=>t instanceof So&&!a.has(t.id)));for(const i of e)i.objectIds.some((e=>t.has(e)))&&(i.invalidateObjectsCache(),i.refreshObjectDimensions(void 0,!0),i.captureUnchangedSnapshots(),this.quadtree.reindex(i))}if(s&&this._core?.anchorManager.rebuildIndex(),this._core?.store.invalidateSelectionCache(),this._core?.rerender(),o.length>0&&this._core?.engine.emitObjectsAdded(o),r.length>0){const t=r.map((t=>({id:t})));this._core?.engine.emitObjectsRemoved(t)}h.length>0&&this._core?.engine.emitObjectsUpdated(h.map((t=>({object:t,changedProperties:[]}))));for(const t of this._objectsChangeCallbacks)t()}initializeMetadata(t,e,i){this._metadataMap&&this._ydoc&&this._ydoc.transact((()=>{this._metadataMap?.get("type")||this._metadataMap?.set("type",t),void 0===this._metadataMap?.get("isPublic")&&this._metadataMap?.set("isPublic",!1),void 0===this._metadataMap?.get("schemaVersion")&&this._metadataMap?.set("schemaVersion",O),this._metadataMap?.set("workspaceId",e),this._metadataMap?.set("workspaceName",i)}),"metadata")}getIsPublic(){return this._metadataMap?.get("isPublic")??!1}setIsPublic(t){this._metadataMap&&this._ydoc&&this._ydoc?.transact((()=>{this._metadataMap?.set("isPublic",t)}),"metadata")}getDocumentType(){return this._metadataMap?.get("type")??"workspace"}getWorkspaceName(){return this._metadataMap?.get("workspaceName")??""}setWorkspaceName(t){this._metadataMap&&this._ydoc&&this._ydoc?.transact((()=>{this._metadataMap?.set("workspaceName",t)}),"metadata")}getMetadataWorkspaceId(){return this._metadataMap?.get("workspaceId")??""}transaction(t){if(this._ydoc){this._inTransaction=!0;try{this._ydoc.transact(t,"local")}finally{this._inTransaction=!1}}}stopUndoCapturing(){this.markUndoBoundary()}markUndoBoundary(){this._inTransaction||this._undoManager?.stopCapturing()}withLocalUpdatesOnly(t){this._localOnlyMode=!0;try{t()}finally{this._localOnlyMode=!1}}loadFromYjs(){if(!this._objectsMap||!this._reviver)return;this.quadtree.reset(),this._idMap.clear();const t=this._core?.user?.id,e=[];this._objectsMap.forEach(((i,n)=>{const r=this._reviver?.revive(i);r instanceof So&&null!=r.userId&&r.userId!==t?e.push(n):r&&(this.quadtree.insert(r),this._idMap.set(r.id,r))})),e.length>0&&this._ydoc.transact((()=>{for(const t of e)this._objectsMap.delete(t)}),"local")}reset(){this.quadtree.reset(),this._idMap.clear(),this.markUndoBoundary(),this._ydoc?.transact((()=>{this._objectsMap?.clear()}),"local")}insert(t){if(!t.id)return!1;if(this.quadtree.insert(t),this._idMap.set(t.id,t),this._objectsMap&&this.isPersistable(t)){const e=t.serialize();this.markUndoBoundary(),this._ydoc?.transact((()=>{this._objectsMap?.set(t.id,e)}),"local")}return!0}update(t,e={}){if(!t.id)return!1;if(!this._idMap.has(t.id))return!1;if(this._localOnlyMode||e.skipReindex?this.quadtree.update(t):this.quadtree.reindex(t),this._idMap.set(t.id,t),!this._localOnlyMode&&this._objectsMap&&this.isPersistable(t)){const i=t.serialize(),n=e.temporary?"temporary":"local";this._ydoc?.transact((()=>{this._objectsMap?.set(t.id,i)}),n)}return!0}remove(t){const e=this.quadtree.filter(t);if(0!==e.length){this.markUndoBoundary();for(const t of e)this.quadtree.remove((e=>e.id===t.id)),this._idMap.delete(t.id),this._objectsMap&&this.isPersistable(t)&&this._ydoc?.transact((()=>{this._objectsMap?.delete(t.id)}),"local")}}filter(t){return this.quadtree.filter(t)}allObjects(){return this.quadtree.allObjects()}query(t){return this.quadtree.query(t)}isPersistable(t){return!(t instanceof gh)}undo(){this._undoManager&&this._undoManager.canUndo()&&(this._undoManager.undo(),this._core?.anchorManager.rebuildIndex(),this._core?.engine.emitObjectsChange())}redo(){this._undoManager&&this._undoManager.canRedo()&&(this._undoManager.redo(),this._core?.anchorManager.rebuildIndex(),this._core?.engine.emitObjectsChange())}canUndo(){return!!this._undoManager&&this._undoManager.canUndo()}canRedo(){return!!this._undoManager&&this._undoManager.canRedo()}clearHistory(){this._undoManager&&(this._undoManager.clear(),this._temporaryItemsCount=0)}consolidateTemporaryItems(){if(!this._undoManager||0===this._temporaryItemsCount)return;const t=this._undoManager.undoStack.length;if(0===t)return void(this._temporaryItemsCount=0);this._undoManager.stopCapturing();const e=Math.min(this._temporaryItemsCount,t);if(e>1){for(let t=0;t<e;t++)this._undoManager.canUndo()&&this._undoManager.undo();this._ydoc?.transact((()=>{for(let t=e-1;t>=0;t--)this._undoManager?.canRedo()&&this._undoManager.redo()}),"local")}this._temporaryItemsCount=0}clearTemporaryItems(){if(!this._undoManager||0===this._temporaryItemsCount)return;const t=Math.min(this._temporaryItemsCount,this._undoManager.undoStack.length);for(let e=0;e<t;e++)this._undoManager.undoStack.length>0&&this._undoManager.undoStack.pop();this._temporaryItemsCount=0}destroy(){this._objectsMap&&this._objectsObserver&&(this._objectsMap.unobserve(this._objectsObserver),this._objectsObserver=null),this._undoManager&&(this._stackItemAddedHandler&&(this._undoManager.off("stack-item-added",this._stackItemAddedHandler),this._stackItemAddedHandler=null),this._stackItemPoppedHandler&&(this._undoManager.off("stack-item-popped",this._stackItemPoppedHandler),this._stackItemPoppedHandler=null),this._undoManager.destroy(),this._undoManager=null),this.quadtree.reset(),this._idMap.clear(),this._awareness&&this._awarenessChangeHandler&&(this._awareness.off("change",this._awarenessChangeHandler),this._awarenessChangeHandler=null),null!==this._awarenessEmitTimeout&&(clearTimeout(this._awarenessEmitTimeout),this._awarenessEmitTimeout=null),this._awareness=null,this._awarenessChangeCallbacks=[],this._providers.forEach((t=>{t.destroy()})),this._providers=[],this._objectsMap=null,this._metadataMap=null,this._ydoc&&(this._ydoc.destroy(),this._ydoc=null),this._core=null,this._reviver=null,this._workspaceId=null,this._isReady=!1,this._temporaryItemsCount=0}}class Xh{_state;_listeners=new Map;_cachedSelectionBox=null;_cachedSelectionGroup=null;_selectionBoxCacheValid=!1;_selectionGroupCacheValid=!1;_localUserId=null;get state(){return this._state}get objects(){if(!this._state.objects)throw new Error("Objects map is not initialized.");return this._state.objects}get host(){if(!this._state.host)throw new Error("Host element is not set.");return this._state.host}get currentZIndex(){return Math.max(0,...this.objects.filter((t=>!(t instanceof So||t instanceof gh))).map((t=>t.zIndex)))+1}get hasViewportBoundaries(){return Number.isFinite(this._state.viewportBoundaryLeft)||Number.isFinite(this._state.viewportBoundaryRight)||Number.isFinite(this._state.viewportBoundaryTop)||Number.isFinite(this._state.viewportBoundaryBottom)}get viewportBoundaryBounds(){const t=this._state.viewportBoundaryLeft,e=this._state.viewportBoundaryRight,i=this._state.viewportBoundaryTop,n=this._state.viewportBoundaryBottom;return{x:Number.isFinite(t)?t:-1/0,y:Number.isFinite(i)?i:-1/0,z:0,width:Number.isFinite(t)&&Number.isFinite(e)?e-t:1/0,height:Number.isFinite(i)&&Number.isFinite(n)?n-i:1/0}}get totalObjectCount(){return this.hasViewportBoundaries?this.allObjects.length:this.objects.totalCount}get allObjects(){return this.hasViewportBoundaries?this.objects.query(this.viewportBoundaryBounds):this.objects.allObjects()}get objectsInViewport(){return this.objects.query({x:-this._state.translateX/this._state.scale,y:-this._state.translateY/this._state.scale,z:this._state.scale,width:this._state.viewportWidth/this._state.scale,height:this._state.viewportHeight/this._state.scale,depth:100}).sort(((t,e)=>t.zIndex-e.zIndex))}get allNonSelectionObjects(){return this.allObjects.filter((t=>!(t instanceof So||t instanceof gh)))}get selectedObjects(){return this.allObjects.filter((t=>!(t instanceof So))).filter((t=>t.isSelected))}get selectionBox(){if(this._selectionBoxCacheValid)return this._cachedSelectionBox;const t=this.objects.filter((t=>t instanceof gh));return this._cachedSelectionBox=t.length>0?t[0]:null,this._selectionBoxCacheValid=!0,this._cachedSelectionBox}get selectionGroup(){if(this._selectionGroupCacheValid)return this._cachedSelectionGroup;const t=this.objects.filter((t=>t instanceof So));return this._cachedSelectionGroup=this._localUserId?t.find((t=>t.userId===this._localUserId))??null:t.length>0?t[0]:null,this._selectionGroupCacheValid=!0,this._cachedSelectionGroup}invalidateSelectionCache(){this._selectionBoxCacheValid=!1,this._selectionGroupCacheValid=!1}setSelectionBox(t){this._cachedSelectionBox=t,this._selectionBoxCacheValid=!0}setSelectionGroup(t){this._cachedSelectionGroup=t,this._selectionGroupCacheValid=!0}setLocalUserId(t){this._localUserId=t,this.invalidateSelectionCache()}get activeText(){const t=this.objects.filter((t=>t instanceof no&&t.isEditing));return t.length>0?t[0]:null}get activeShape(){const t=this.objects.filter((t=>t instanceof po&&t.isEditing));return t.length>0?t[0]:null}get activeInteractiveCustomElement(){return this.selectedObjects.find((t=>uo.isInstanceOf(t,"KritzelCustomElement")&&t.hasFocusedInputElement()))??null}get currentPath(){const t=this.objects.filter((t=>t instanceof c&&!1===t.isCompleted));return t.length>0?t[0]:null}get currentLine(){const t=this.objects.filter((t=>t instanceof f&&!1===t.isCompleted));return t.length>0?t[0]:null}get offsetX(){return this.host.getBoundingClientRect().left}get offsetY(){return this.host.getBoundingClientRect().top}get isDisabled(){return!1===this._state.isEnabled||!1===this._state.isReady||null===this._state.activeWorkspace}get isPointerDown(){return this._state.pointers.size>0}constructor(t){this._state={...t,contextMenuItems:[...t.contextMenuItems],debugInfo:{...t.debugInfo},pointers:new Map(t.pointers),workspaces:[...t.workspaces],cursor:{...t.cursor}},this._state.objects=new Gh}onStateChange(t,e){this._listeners.has(t)||this._listeners.set(t,new Set);const i=this._listeners.get(t);if(!i)throw new Error(`Listeners set for property ${String(t)} was not initialized.`);i.add(e)}getState(t){return this._state[t]}setState(t,e){const i=this._state[t];if(i!==e){this._state[t]=e;const n=this._listeners.get(t);n&&n.forEach((n=>n(e,i,String(t))))}}}class Yh{map;_ydoc=null;_workspacesMap=null;_metadataMap=null;_providers=[];_core=null;_isReady=!1;_onRemoteChangeCallback=null;_workspacesObserver=null;get isReady(){return this._isReady}get hasNetworkSyncProvider(){return this._providers.some((t=>"network"===t.type))}constructor(){this.map=new Map}onRemoteChange(t){this._onRemoteChangeCallback=t}async initialize(t,e){this._core=t,this._ydoc=new E.Doc,this._workspacesMap=this._ydoc.getMap("workspaces"),this._metadataMap=this._ydoc.getMap("metadata");const i=e?.appStateId??this.getOrCreateAppStateInstanceId(t),n=t.editorId?`kritzel-app-state-${t.editorId}-${i}`:`kritzel-app-state-${i}`,r=e??jh,s=!!t.store.state.debugInfo.showSyncProviderInfo,o=!s;for(const t of r.providers){let e;e="function"==typeof t?new t(n,this._ydoc,{quiet:o}):t.create(n,this._ydoc,{quiet:o}),this._providers.push(e)}if(s){const t=this._providers.map((t=>`${t.constructor.name} (${t.type})`)).join(", ");console.info(`[Kritzel] App-state sync providers initialized for ${n}: ${t||"none"}`)}this._workspacesObserver=t=>{this.handleWorkspacesChange(t)},this._workspacesMap.observe(this._workspacesObserver);const h=this._providers.filter((t=>"local"===t.type)),a=this._providers.filter((t=>"network"===t.type)),l=await Promise.allSettled(h.map((t=>t.connect())));if(s){const t=l.filter((t=>"fulfilled"===t.status)).length;console.info(`[Kritzel] App-state local providers connected: ${t}/${h.length}`)}l.forEach(((t,e)=>{s&&"rejected"===t.status&&console.error(`[Kritzel] Sync provider "${h[e]?.constructor.name}" failed to connect:`,t.reason)})),s&&a.length>0&&console.info(`[Kritzel] App-state network providers connecting in background: ${a.length}`);for(const t of a)t.connect().catch((e=>{s&&console.error(`[Kritzel] Network sync provider "${t.constructor.name}" failed to connect:`,e)}));this._isReady=!0,Eh(this._ydoc,this._metadataMap,{workspaces:this._workspacesMap},Oh,I,{quiet:!t.store.state.debugInfo.showMigrationInfo}),this.initializeMetadata("state"),this.loadFromYjs()}getOrCreateAppStateInstanceId(t){const e=globalThis.localStorage;if(!e)throw new Error("[KritzelAppStateMap] localStorage is unavailable. Cannot persist app-state document identity.");const i=t.getStorageKey("kritzel-app-state-instance-id");let n;try{n=e.getItem(i)}catch{throw new Error("[KritzelAppStateMap] Failed to read app-state instance id from localStorage.")}if(n)return n;const r=T.generateUUID();try{e.setItem(i,r)}catch{throw new Error("[KritzelAppStateMap] Failed to persist app-state instance id to localStorage.")}return r}handleWorkspacesChange(t){if("local"===t.transaction.origin)return void this._core?.rerender();if("migration"===t.transaction.origin)return;const e=Array.from(t.keysChanged),i=[],n=[];e.forEach((e=>{const r=t.changes.keys.get(e);if(r&&"delete"===r.action)n.push(e);else{const t=this._workspacesMap.get(e);if(t){const e=this.reviveWorkspace(t);i.push(e)}}})),n.forEach((t=>{this.map.delete(t)})),i.forEach((t=>{this.map.set(t.id,t)})),this._core?.store&&(this._core.store.state.workspaces=this.allWorkspaces()),this._onRemoteChangeCallback&&this._onRemoteChangeCallback(),this._core?.rerender()}reviveWorkspace(t){let e=t.viewport;if(e&&"translateX"in e&&!("centerWorldX"in e)){const t=e.scale??1;e={centerWorldX:-(e.translateX??0)/t,centerWorldY:-(e.translateY??0)/t,scale:t}}const i=new x(t.id,t.name,e);return this._core&&(i._core=this._core),i.createdAt=new Date(t.createdAt),i.updatedAt=new Date(t.updatedAt),i.isPublic=t.isPublic??!1,i}initializeMetadata(t){this._metadataMap&&this._ydoc&&this._ydoc.transact((()=>{this._metadataMap?.get("type")||this._metadataMap?.set("type",t),void 0===this._metadataMap?.get("isPublic")&&this._metadataMap?.set("isPublic",!1),void 0===this._metadataMap?.get("schemaVersion")&&this._metadataMap?.set("schemaVersion",I)}),"metadata")}getIsPublic(){return this._metadataMap?.get("isPublic")??!1}setIsPublic(t){this._metadataMap&&this._ydoc&&this._ydoc.transact((()=>{this._metadataMap?.set("isPublic",t)}),"metadata")}getDocumentType(){return this._metadataMap?.get("type")??"state"}transaction(t){this._ydoc&&this._ydoc.transact(t,"local")}loadFromYjs(){this._workspacesMap&&(this.map.clear(),this._workspacesMap.forEach(((t,e)=>{const i=this.reviveWorkspace(t);this.map.set(e,i)})))}reset(){this.map.clear(),this._ydoc?.transact((()=>{this._workspacesMap?.clear()}),"local")}insert(t){if(!t.id)return!1;if(this.map.set(t.id,t),this._workspacesMap){const e=t.serialize();this._ydoc?.transact((()=>{this._workspacesMap?.set(t.id,e)}),"local")}return!0}update(t){if(!t.id||!this.map.has(t.id))return!1;if(this.map.set(t.id,t),this._workspacesMap){const e=t.serialize();this._ydoc?.transact((()=>{this._workspacesMap?.set(t.id,e)}),"local")}return!0}remove(t){const e=Array.from(this.map.values()).find(t);return!!e&&(this.map.delete(e.id),this._workspacesMap&&this._ydoc?.transact((()=>{this._workspacesMap?.delete(e.id)}),"local"),!0)}get(t){return this.map.get(t)}allWorkspaces(){return Array.from(this.map.values())}filter(t){return Array.from(this.map.values()).filter(t)}find(t){return Array.from(this.map.values()).find(t)}has(t){return this.map.has(t)}destroy(){this._workspacesMap&&this._workspacesObserver&&(this._workspacesMap.unobserve(this._workspacesObserver),this._workspacesObserver=null),this._providers.forEach((t=>{t.disconnect(),t.destroy()})),this._providers=[],this.map.clear(),this._workspacesMap=null,this._metadataMap=null,this._ydoc&&(this._ydoc.destroy(),this._ydoc=null),this._core=null,this._onRemoteChangeCallback=null,this._isReady=!1}}class qh{_core;_targetElement=null;_shadowRoot=null;constructor(t){this._core=t}setTargetElement(t){this._targetElement&&(this._targetElement.style.cursor="",this._targetElement.style.removeProperty("--kritzel-global-pointer-cursor")),this._targetElement=t,this._targetElement&&this._targetElement.style.setProperty("--kritzel-global-pointer-cursor",lh.getPointerCursor())}getTargetElement(){return this._targetElement}setShadowRoot(t){this._shadowRoot=t}resetToDefault(){this._core.store.state.cursor={icon:"default",iconActive:"default"}}updateHoverState(t){if(this._core.store.isPointerDown)return;if(!this._shadowRoot)return;const e=this._shadowRoot.elementsFromPoint(t.clientX,t.clientY);if(!e||0===e.length)return;const i=e.find((t=>t.classList.contains("resize-handle-overlay")));if(i){const t=this._core.store.selectionGroup,e=t?.rotationDegrees??0,n=i.classList.contains("top-left"),r=i.classList.contains("bottom-right");this._core.store.state.cursor={icon:"move-vertical",rotation:e+(n||r?-45:45)}}else this._core.store.state.cursor=e.find((t=>t.classList.contains("rotation-handle-overlay")))||e.find((t=>t.classList.contains("selection-line-handle-overlay")))?{icon:"hand",iconActive:"hand-grab"}:{icon:"default",iconActive:"default"}}applyCursor(){const t=this._core.store.state,e=this._core.store.isPointerDown,i=t.cursor?.icon,n=t.cursor?.iconActive??i,r=t.cursor?.rotation,s=lh.getCursor({iconName:e?n:i,rotation:r});this._targetElement&&(this._targetElement.style.cursor=s)}cleanup(){this._targetElement&&(this._targetElement.style.cursor="",this._targetElement.style.removeProperty("--kritzel-pointer-cursor")),this._targetElement=null,this._shadowRoot=null}}class Jh{_isFirefox=/firefox|fxios/i.test(navigator.userAgent);_isSafari=/safari/i.test(navigator.userAgent)&&!/chrome|chromium|crios|android|edg/i.test(navigator.userAgent);_requestHandlers=new Map;constructor(t){this.registerRequestPermissionHandler("clipboard-read",(async()=>{if(this._isFirefox||this._isSafari)return"granted";try{return"denied"===(await navigator.permissions.query({name:"clipboard-read"})).state?"denied":"granted"}catch{return"granted"}}))}registerRequestPermissionHandler(t,e){this._requestHandlers.set(t,e)}async checkPermission(t){return(await navigator.permissions.query({name:t})).state}async requestPermission(t){const e=this._requestHandlers.get(t);return e?e():this.checkPermission(t)}}class Qh{_core;_providers=[];constructor(t){this._core=t}register(t){this._providers.push(t)}async resolve(t){const e={core:this._core,event:t};for(const t of this._providers){if(!t.canHandle(e))continue;const i=await t.getPasteIntent(e);if("unknown"!==i.type)return i}return{type:"unknown"}}}const Zh="kritzel-clipboard/v1:";class ta{canHandle(t){return!!t.event?.clipboardData}async getPasteIntent(t){const e=t.event?.clipboardData;if(!e)return{type:"unknown"};const i=Array.from(e.files??[]).filter((t=>t.type.startsWith("image/")));if(i.length>0)return{type:"image_files",files:i};if(e.types.includes("text/plain")){const t=this.determineTextPasteIntent(e.getData("text/plain"));if(t)return t}return{type:"unknown"}}parseClipboardPayload(t){if(!t||!t.startsWith(Zh))return null;try{const e=JSON.parse(t.slice(21));return 1===e?.version&&Array.isArray(e.objects)?e:null}catch{return null}}determineTextPasteIntent(t){const e=this.parseClipboardPayload(t);return e?{type:"kritzel_objects",payload:e}:t&&t.trim().length>0?{type:"plain_text",text:t}:null}}class ea{canHandle(t){return!t.event?.clipboardData&&"undefined"!=typeof navigator&&!!navigator.clipboard}async getPasteIntent(t){if("undefined"==typeof navigator||!navigator.clipboard)return{type:"unknown"};const{clipboard:e}=navigator;if("granted"!==await t.core.permissionManager.checkPermission("clipboard-read")&&"granted"!==await t.core.permissionManager.requestPermission("clipboard-read"))return{type:"unknown"};if(e.read)try{const t=await e.read(),{imageFiles:i,text:n}=await this.processClipboardItems(t);if(i.length>0)return{type:"image_files",files:i};if(null!==n){const t=this.determineTextPasteIntent(n);if(t)return t}}catch{}if(e.readText){const t=this.determineTextPasteIntent(await e.readText());if(t)return t}return{type:"unknown"}}async processClipboardItems(t){const e=[];let i=null;return await Promise.all(t.map((async t=>{const n=t.types.find((t=>t.startsWith("image/")));if(n){const i=await t.getType(n);e.push(new File([i],"pasted-image",{type:n}))}else if(null===i&&t.types.includes("text/plain")){const e=await t.getType("text/plain");i=await e.text()}}))),{imageFiles:e,text:i}}parseClipboardPayload(t){if(!t||!t.startsWith(Zh))return null;try{const e=JSON.parse(t.slice(21));return 1===e?.version&&Array.isArray(e.objects)?e:null}catch{return null}}determineTextPasteIntent(t){const e=this.parseClipboardPayload(t);return e?{type:"kritzel_objects",payload:e}:t&&t.trim().length>0?{type:"plain_text",text:t}:null}}class ia{canHandle(t){return!t.event?.clipboardData&&v.isIOS()}async getPasteIntent(t){const e=t.core.clipboardManager.sessionClipboardPayload;return e?{type:"kritzel_objects",payload:e}:{type:"unknown"}}}class na{_core;_pasteIntentRegistry;_sessionClipboardPayload=null;_pasteOffset=0;constructor(t){this._core=t,this._pasteIntentRegistry=new Qh(this._core),this._pasteIntentRegistry.register(new ia),this._pasteIntentRegistry.register(new ta),this._pasteIntentRegistry.register(new ea)}get sessionClipboardPayload(){return this._sessionClipboardPayload}serializeForClipboard(t){const e="function"==typeof t.serialize?t.serialize():t;return uo.isInstanceOf(t,"KritzelGroup")&&(e.__children__=t.children.map((t=>this.serializeForClipboard(t)))),e}serializeClipboardPayload(t){return`${Zh}${JSON.stringify(t)}`}async writeBrowserClipboardPayload(t,e){const i=this.serializeClipboardPayload(t);if(e?.clipboardData)e.clipboardData.setData("text/plain",i);else if("undefined"!=typeof navigator&&navigator.clipboard?.writeText)try{await navigator.clipboard.writeText(i)}catch{}}reviveClipboardObject(t){const e=new Wh(this._core),{__children__:i,...n}=t,r=e.revive(n);if(!r)return null;if(i&&uo.isInstanceOf(r,"KritzelGroup")){const t=i.map((t=>this.reviveClipboardObject(t))).filter((t=>null!=t));r._pendingChildren=t,r.childIds=t.map((t=>t.id))}return r}regenerateIdsAndRemapAnchors(t){const e=[],i=t.length>0&&t.every((t=>uo.isInstanceOf(t,"KritzelLine"))),n=t=>{for(const i of t)e.push(i),uo.isInstanceOf(i,"KritzelGroup")&&n(i._pendingChildren)};n(t);const r=new Map;for(const t of e){const e=t.generateId();r.set(t.id,e),t.id=e,t.isMounted=!1}for(const t of e)uo.isInstanceOf(t,"KritzelGroup")&&(t.childIds=t.childIds.map((t=>r.get(t)??t))),uo.isInstanceOf(t,"KritzelLine")&&(t.startAnchor&&r.has(t.startAnchor.objectId)?t.startAnchor={objectId:r.get(t.startAnchor.objectId)}:i&&(t.startAnchor=void 0),t.endAnchor&&r.has(t.endAnchor.objectId)?t.endAnchor={objectId:r.get(t.endAnchor.objectId)}:i&&(t.endAnchor=void 0))}copy(t){const e=this._core.store.selectionGroup;if(!e)return;const i={version:1,sourceWorkspaceId:this._core.store.state.activeWorkspace?.id,objects:e.objects.sort(((t,e)=>t.zIndex-e.zIndex)).map((t=>this.serializeForClipboard(t)))};this._pasteOffset=0,this._sessionClipboardPayload=i,this.writeBrowserClipboardPayload(i,t)}cut(t){this._core.store.selectionGroup&&(this.copy(t),this._core.delete())}materializeKritzelObjects(t){const e=t.payload.objects.map((t=>this.reviveClipboardObject(t))).filter((t=>null!=t));return this.regenerateIdsAndRemapAnchors(e),e}async materializeImageFiles(t){try{const e=25/this._core.store.state.scale,i=t.files.map((async(t,i)=>{const n=await this.prepareImageFile(t);return lo.fromBlob(this._core,n,{translateX:i*e,translateY:i*e})}));return await Promise.all(i)}catch(t){return console.error("Failed to import pasted image files:",t),null}}async prepareImageFile(t){return sh.isGifFile(t)?t:rh(t,{maxWidthOrHeight:1200})}async materializePlainText(t){const e=no.create(this._core),i=t.text.split("\n").map((t=>0===t.length?{type:"paragraph"}:{type:"paragraph",content:[{type:"text",text:t}]}));return e.setContent({type:"doc",content:i}),[e]}async paste(t,e,i){const n=await this._pasteIntentRegistry.resolve(i);let r=null;"kritzel_objects"===n.type?r=this.materializeKritzelObjects(n):"image_files"===n.type?r=await this.materializeImageFiles(n):"plain_text"===n.type&&(r=await this.materializePlainText(n)),r&&0!==r.length&&await this.insertMaterializedObjects(r,n,t,e)}async insertMaterializedObjects(t,e,i,n){const r=this._core.store.state.activeWorkspace;if(!r)return;const s=t.some((t=>t.workspaceId!==r.id))||"kritzel_objects"!==e.type,o=void 0!==i&&void 0!==n,h=Math.min(...t.map((t=>t.translateX))),a=Math.min(...t.map((t=>t.translateY)));let l,u;const c=25/this._core.store.state.scale;void 0!==i&&void 0!==n?(l=i,u=n):s?(l=h,u=a):(l=h+c+this._pasteOffset,u=a+c+this._pasteOffset,this._pasteOffset+=c);const f=l-h,d=u-a;this._core.removeSelectionGroup(),this._core.removeSelectionBox();const p=So.create(this._core),g=this._core.store.currentZIndex;this._core.store.objects.transaction((()=>{const e=(t,i)=>{if(0===t._pendingChildren.length)return;const n=t._pendingChildren;t._pendingChildren=[],n.forEach(((t,n)=>{t.workspaceId!==r.id&&(t.workspaceId=r.id),t.updatePosition(t.translateX+f,t.translateY+d),t.zIndex=i+n+1,uo.isInstanceOf(t,"KritzelGroup")&&e(t,t.zIndex),this._core.addObject(t)})),t.finalize()},i=[];t.forEach(((t,n)=>{t.workspaceId!==r.id&&(t.workspaceId=r.id),t.updatePosition(t.translateX+f,t.translateY+d),t.zIndex=g+n,uo.isInstanceOf(t,"KritzelGroup")&&e(t,t.zIndex),this._core.addObject(t),i.push(t),p.addOrRemove(t)})),this._core.engine.emitObjectsAdded(i)})),this._core.anchorManager.rebuildIndex(),p.isSelected=!0,1===t.length&&(p.rotation=t[0].rotation),s&&!o&&p.centerInViewport(),this._core.addSelectionGroup(p),this._core.engine.viewport?.bringIntoViewIfNeeded(p),this._core.store.state.isSelecting=!1,await new Promise((t=>{requestAnimationFrame((()=>requestAnimationFrame((()=>t()))))})),p.refreshObjectDimensions(),s&&!o&&p.centerInViewport(),this._core.engine.emitObjectsChange(),this._core.rerender(),this._core.store.setState("activeTool",this._core.toolRegistry.getTool("selection")),this._core.engine.emitObjectsChange(),this._core.rerender()}}class ra{_kritzelEngine;_store;_syncConfig;_assetStorageConfig;_assetResolver;_appStateMap;_anchorManager;_cursorManager;_themeManager;_localizationManager;_licenseManager;_permissionManager;_clipboardManager;_toolRegistry;_editorId;_user;get engine(){return this._kritzelEngine}get store(){return this._store}get appStateMap(){return this._appStateMap}get anchorManager(){return this._anchorManager}get cursorManager(){return this._cursorManager}get themeManager(){return this._themeManager}get localizationManager(){return this._localizationManager}get licenseManager(){return this._licenseManager}get permissionManager(){return this._permissionManager}get toolRegistry(){return this._toolRegistry}get clipboardManager(){return this._clipboardManager}get editorId(){return this._editorId}getStorageKey(t){return this._editorId?`${t}-${this._editorId}`:t}get user(){return this._user}setUser(t){this._user=t,this._store.setLocalUserId(t?.id??null),this._store.objects?.setLocalUser(t)}constructor(t,e){this._kritzelEngine=t,this._editorId=e,this._store=new Xh(Uh),this._appStateMap=new Yh,this._anchorManager=new bh(this),this._cursorManager=new qh(this),this._themeManager=new w(this),this._localizationManager=new zh(this),this._licenseManager=new Ch(this),this._permissionManager=new Jh(this),this._clipboardManager=new na(this),this._toolRegistry=new Hh(this),this._assetResolver=new ao,this._assetResolver.setShowInfo(this._store.state.debugInfo?.showAssetResolverInfo??!1)}get assetResolver(){return this._assetResolver}setSyncConfig(t){this._syncConfig=t}setAssetStorageConfig(t){this._assetStorageConfig=t}setEditorId(t){this._editorId=t,this._themeManager=new w(this),this._localizationManager=new zh(this)}async initializeYjs(){await this._appStateMap.initialize(this,this._syncConfig)}async initializeAssetStorage(){await this._assetResolver.init(this._assetStorageConfig),this.warnIfAssetStorageMismatched()}warnIfAssetStorageMismatched(){this._appStateMap.hasNetworkSyncProvider&&(this._assetResolver.hasRemoteProvider||console.warn("[Kritzel] A network sync provider is configured, but no remote asset storage provider was found. Images added on this device will only be available locally and will appear broken on other devices. Configure a remote asset provider (e.g. HttpAssetProvider) via the `assetStorage` prop to enable cross-device image sync."))}loadWorkspacesFromAppState(){return this._appStateMap.allWorkspaces()}saveWorkspaceToAppState(t){this._appStateMap.has(t.id)?this._appStateMap.update(t):this._appStateMap.insert(t)}deleteWorkspaceFromAppState(t){this._appStateMap.remove((e=>e.id===t))}async initializeWorkspace(t,e){const i=this.loadWorkspacesFromAppState(),n=!t&&!!this._editorId,r=i.length>0?[...i].sort(((t,e)=>{const i=e.createdAt.getTime()-t.createdAt.getTime();return 0!==i?i:e.updatedAt.getTime()-t.updatedAt.getTime()}))[0]:null,s=localStorage.getItem(this.getStorageKey("kritzel-active-workspace-id")),o=s?i.find((t=>t.id===s)):null;let h;if(t)h=t,i.find((e=>e.id===t.id))||(h._core=this,this.saveWorkspaceToAppState(h));else if(o)h=o;else if(r&&!n)h=r;else{if(e?.skipFallbackCreation)return this._store.state.workspaces=i,this._store.state.activeWorkspace=null,void this.rerender();h=new x(T.generateUUID(),"New Workspace"),h._core=this,this.saveWorkspaceToAppState(h)}localStorage.setItem(this.getStorageKey("kritzel-active-workspace-id"),h.id),this._store.objects&&this._store.objects.isReady&&this._store.objects.destroy();const a=new Gh;this._store.state.objects=a,this._store.state.activeWorkspace=h,this._store.state.workspaces=this.loadWorkspacesFromAppState();const l=h.viewport??{centerWorldX:0,centerWorldY:0,scale:1},u=l.scale??1,c=this._store.state.viewportHeight;this._store.state.translateX=this._store.state.viewportWidth/2-(l.centerWorldX??0)*u,this._store.state.translateY=c/2-(l.centerWorldY??0)*u,this._store.state.scale=u,await a.initialize(this,h.id,this._syncConfig),this._user&&a.setLocalUser(this._user),a.onAwarenessChange((t=>{this.engine.emitAwarenessChange(t)})),this._anchorManager.rebuildIndex(),this.engine.emitObjectsChange(),this.rerender()}async loadSharedWorkspace(t){const e=t;let i=this.getWorkspaces().find((t=>t.id===e));i?i.isPublic=!0:(i=new x(e,"Shared Workspace"),i.isPublic=!0,this.createWorkspace(i)),await this.initializeWorkspace(i)}getObjectsInViewport(){return this._store.objects?this._store.objects.query({x:-this._store.state.translateX/this._store.state.scale,y:-this._store.state.translateY/this._store.state.scale,z:this._store.state.scale,width:this._store.state.viewportWidth/this._store.state.scale,height:this._store.state.viewportHeight/this._store.state.scale,depth:100}).filter((t=>!(t instanceof So||t instanceof gh))).sort(((t,e)=>t.zIndex-e.zIndex)):[]}rerender(){this._kritzelEngine&&this._kritzelEngine.forceUpdate++}findObjectById(t){for(const e of this._store.allObjects)if(e.id===t)return e;return null}getWorkspaces(){return this.loadWorkspacesFromAppState()}createWorkspace(t){t._core=this,t.createdAt=new Date,t.updatedAt=new Date,this.saveWorkspaceToAppState(t),this._store.state.workspaces=this.loadWorkspacesFromAppState()}updateWorkspace(t){t.updatedAt=new Date,this.saveWorkspaceToAppState(t),this._store.state.activeWorkspace?.id===t.id&&this._store.objects?.setWorkspaceName(t.name);const e=this._store.state.workspaces,i=e.findIndex((e=>e.id===t.id));-1!==i&&(e[i]=t,this._store.state.workspaces=e)}deleteWorkspace(t){this._store.state.activeWorkspace?.id===t.id&&(this.engine.viewport?.cancelPendingUpdates(),this._store.objects?.destroy()),this.deleteWorkspaceFromAppState(t.id),this._store.state.workspaces=this.loadWorkspacesFromAppState(),window.indexedDB.deleteDatabase(this._editorId?`kritzel-workspace-${this._editorId}-${t.id}`:`kritzel-workspace-${t.id}`)}updateWorkspaceViewport(t,e,i){const n=this._store.state.activeWorkspace;n&&this._store.state.workspaces.some((t=>t.id===n.id))&&(n.viewport={centerWorldX:(this._store.state.viewportWidth/2-t)/i,centerWorldY:(this._store.state.viewportHeight/2-e)/i,scale:i},n.updatedAt=new Date,this.saveWorkspaceToAppState(n))}getIsPublic(){return this._store.state.activeWorkspace?.isPublic??!1}addObject(t){this._store.objects.insert(t)}removeObject(t,e=!1){uo.isInstanceOf(t,"KritzelGroup")&&!e&&[...t.children].forEach((t=>{this.removeObject(t)})),uo.isInstanceOf(t,"KritzelCustomElement")&&t.unmount(),uo.isInstanceOf(t,"KritzelLine")?this._anchorManager.handleLineDeleted(t.id):this._anchorManager.handleObjectDeleted(t.id),t.isMounted=!1,this._store.objects.remove((e=>e.id===t.id))}updateObject(t,e){const i=[];for(const n in e)if(e.hasOwnProperty(n)){const r=e[n];void 0!==r&&(t[n]=r,i.push(n))}t.onAfterUpdate(i),this._store.objects.update(t)}addSelectionGroup(t){this.removeLocalSelectionGroups(),this.removeSelectionBox();for(const e of t.objects??[])if(uo.isInstanceOf(e,"KritzelCustomElement")){const t=e;"function"==typeof t.setIsInteractive?t.setIsInteractive(!0):t.isInteractive=!0}this._store.objects.insert(t),this._store.setSelectionGroup(t),this._kritzelEngine.triggerSelectionChange()}isLocalSelectionGroup(t){const e=this._user?.id;return null==e||t.userId===e||null==t.userId}teardownSelectionGroup(t){t.deselectAllChildren?.();for(const e of t.objects??[])if(uo.isInstanceOf(e,"KritzelCustomElement")){const t=e;"function"==typeof t.setIsInteractive?t.setIsInteractive(!1):t.isInteractive=!1}}removeLocalSelectionGroups(){const t=this._store.objects.allObjects().filter((t=>t instanceof So||uo.isInstanceOf(t,"KritzelSelectionGroup"))).filter((t=>this.isLocalSelectionGroup(t))),e=this._store.selectionGroup;if(e&&this.isLocalSelectionGroup(e)&&!t.some((t=>t.id===e.id))&&t.push(e),0===t.length)return!1;for(const e of t)this.teardownSelectionGroup(e);const i=new Set(t.map((t=>t.id)));return this._store.objects.remove((t=>i.has(t.id))),this._store.setSelectionGroup(null),!0}removeSelectionGroup(){this.removeLocalSelectionGroups()&&this._kritzelEngine.triggerSelectionChange()}removeSelectionBox(){const t=this._store.selectionBox;t&&(this._store.objects.remove((e=>e.id===t.id)),this._store.setSelectionBox(null),this._store.objects.clearLocalSelectionBox())}deselectAllObjects(){this.removeSelectionGroup(),this.rerender()}delete(){const t=this._store.selectionGroup;t&&(this._store.objects.stopUndoCapturing(),this._store.objects.transaction((()=>{t.objects.forEach((t=>this.removeObject(t))),this.removeSelectionGroup()})),this._store.objects.stopUndoCapturing(),this.engine.emitObjectsInViewportChange(),this.rerender())}undo(){this._store.objects?.undo()}redo(){this._store.objects?.redo()}deleteObject(t){const e=this.findObjectById(t);e&&(this.removeObject(e),this.engine.emitObjectsInViewportChange(),this.rerender())}bringForward(t){const e=this._store.selectionGroup,i=t?[t]:e?.objects||[],n=this._store.allNonSelectionObjects.filter((t=>-1===i.findIndex((e=>e.id===t.id)))),r=n.length>0?Math.max(...n.map((t=>t.zIndex)))+1:0;i.forEach((t=>{t.zIndex!==r&&this.updateObject(t,{zIndex:t.zIndex+1})})),this.rerender()}sendBackward(t){const e=this._store.selectionGroup,i=t?[t]:e?.objects||[],n=this._store.allNonSelectionObjects.filter((t=>-1===i.findIndex((e=>e.id===t.id)))),r=n.length>0?Math.min(...n.map((t=>t.zIndex)))-1:0;i.forEach((t=>{t.zIndex!==r&&this.updateObject(t,{zIndex:t.zIndex-1})})),this.rerender()}bringToFront(t){const e=this._store.selectionGroup,i=t?[t]:e?.objects||[],n=this._store.allNonSelectionObjects.filter((t=>-1===i.findIndex((e=>e.id===t.id)))),r=Math.max(...n.map((t=>t.zIndex)))+1;i.forEach((t=>{this.updateObject(t,{zIndex:r})})),this.rerender()}sendToBack(t){const e=this._store.selectionGroup,i=t?[t]:e?.objects||[],n=this._store.allNonSelectionObjects.filter((t=>-1===i.findIndex((e=>e.id===t.id)))),r=Math.min(...n.map((t=>t.zIndex)))-1;i.forEach((t=>{this.updateObject(t,{zIndex:r})})),this.rerender()}alignObjects(t){const e=this._store.selectionGroup;if(!e||e.objects.length<2)return;const i=e.objects,n=Kh.calculateAlignedPositions(i,t);this._store.objects.transaction((()=>{for(const t of i){const e=n.get(t.id);e&&this.updateObject(t,{translateX:e.translateX,translateY:e.translateY})}})),e.refreshObjectDimensions(),this.rerender()}group(){const t=this._store.selectionGroup;if(!t||t.objects.length<2)return;const e=co.createFromObjects(this,t.objects);this.addObject(e),this.removeSelectionGroup();const i=So.create(this);i.addOrRemove(e),i.isSelected=!0,i.rotation=e.rotation,this.addSelectionGroup(i),this.engine.emitObjectsChange(),this.rerender()}ungroup(){const t=this._store.selectionGroup;if(!t)return;const e=t.objects.filter((t=>uo.isInstanceOf(t,"KritzelGroup")));if(0===e.length)return;const i=[],n=t.objects.filter((t=>!uo.isInstanceOf(t,"KritzelGroup")));e.forEach((t=>{const e=t.ungroup();i.push(...e),this.removeObject(t,!0)})),this.removeSelectionGroup();const r=So.create(this);[...i,...n].forEach((t=>{r.addOrRemove(t)})),r.isSelected=!0,this.addSelectionGroup(r),this.engine.emitObjectsChange(),this.rerender()}selectObjects(t){if(0===t.length)return;const e=So.create(this);t.forEach((t=>{t.isSelected=!1,e.addOrRemove(t)})),e.isSelected=!0,1===t.length&&(e.rotation=e.objects[0].rotation),this.addSelectionGroup(e),this.rerender()}selectAllObjects(){const t=this._store.objects.allObjects().filter((t=>!(t instanceof So||t instanceof gh||t instanceof z)));if(t.length>0){const e=So.create(this);t.forEach((t=>{t.isSelected=!1,e.addOrRemove(t)})),e.isSelected=!0,this._store.state.isSelecting=!1,1===t.length&&(e.rotation=e.objects[0].rotation),this.addSelectionGroup(e),this._store.setState("activeTool",this._toolRegistry.getTool("selection")),this.rerender()}}selectAllObjectsInViewport(){const t=this._store.objects.query({x:-this._store.state.translateX/this._store.state.scale,y:-this._store.state.translateY/this._store.state.scale,z:this._store.state.scale,width:this._store.state.viewportWidth/this._store.state.scale,height:this._store.state.viewportHeight/this._store.state.scale,depth:100}).filter((t=>t.isInViewport())).filter((t=>!(t instanceof So||t instanceof gh||t instanceof z)));if(t.length>0){const e=So.create(this);t.forEach((t=>{t.isSelected=!1,e.addOrRemove(t)})),e.isSelected=!0,this._store.state.isSelecting=!1,1===t.length&&(e.rotation=e.objects[0].rotation),this.addSelectionGroup(e),this._store.setState("activeTool",this._toolRegistry.getTool("selection")),this.rerender()}}clearSelection(){this.removeSelectionGroup();const t=this._user?.id;this._store.objects.remove((e=>e instanceof gh||e instanceof So&&(null==t||e.userId===t||null==e.userId))),this._store.setSelectionBox(null),this._store.setSelectionGroup(null);for(const t of this._store.allNonSelectionObjects)t.isSelected&&(t.isSelected=!1);this._store.state.isSelecting=!1,this._store.state.isResizeHandleSelected=!1,this._store.state.isRotationHandleSelected=!1,this._store.state.isLineHandleSelected=!1,this._store.state.isLineHandleDragging=!1,this._store.state.lineHandleType=void 0,this.rerender()}resetActiveText(){const t=this._store.activeText;t&&(t.isEmpty?this.deleteObject(t.id):t.save())}resetActiveShape(){const t=this._store.activeShape;t&&t.save()}getObjectFromPointerEvent(t,e=".object"){const i=this._store.state.host?.shadowRoot;if(!i)return null;const n=t.clientX,r=t.clientY,s=i.elementFromPoint(n,r);if(!s)return null;const o=s.closest(e);if(o){const t=this._store.allObjects.find((t=>o.id===t.id));return t&&t.hitTest(n,r)?t:null}return null}getObjectsFromPointerEvent(t,e=".object"){const i=this._store.state.host?.shadowRoot;if(!i)return[];const n=i.elementsFromPoint(t.clientX,t.clientY);if(!n||0===n.length)return[];const r=new Set;return n.forEach((t=>{const i=t.closest(e);i&&i.id&&r.add(i.id)})),r.size>0?this._store.allObjects.filter((t=>r.has(t.id))).sort(((t,e)=>e.zIndex-t.zIndex)):[]}getElementsAtPoint(t,e){const i=this._store.state.host?.shadowRoot;if(!i)return[];const n=i.elementsFromPoint(t.clientX,t.clientY);return n&&0!==n.length?n.filter((t=>t.matches(e))):[]}isPointerOverElement(t,e){return this.getElementsAtPoint(t,e).length>0}getCanvasPoint(t){if(!this._store.state.host)return{x:0,y:0};const e=this._store.state.host.getBoundingClientRect();return{x:(t.clientX-e.left-this._store.state.translateX)/this._store.state.scale,y:(t.clientY-e.top-this._store.state.translateY)/this._store.state.scale}}beforeWorkspaceChange(){this._kritzelEngine.viewport?.cancelPendingUpdates(),this._store.state.activeWorkspace&&this.updateWorkspaceViewport(this._store.state.translateX,this._store.state.translateY,this._store.state.scale),this.resetActiveText(),this.clearSelection(),this._store.setState("activeTool",this._toolRegistry.getTool("selection"))}displaySelectionGroupUI(t){if(!t.isSelected)return!1;if(t instanceof So&&null!=this._user?.id&&null!=t.userId&&t.userId!==this._user.id)return!0;const e=this._store.selectionGroup;return e?t instanceof So&&t.id===e.id&&(e.objects.length>1||(1!==e.objects.length||!(e.objects[0]instanceof f))):!(t instanceof f)}displaySelectionLineUI(t){if(!(t instanceof f))return!1;const e=this._store.selectionGroup;if(!e)return t.isSelected;if(!e.isSelected)return!1;if(1===e.objects.length){const i=e.objects[0];return i instanceof f&&i.id===t.id}return!1}}class sa{static calculateCombinedBounds(t){if(!t||0===t.length)return null;let e=1/0,i=1/0,n=-1/0,r=-1/0;for(const s of t){const t=s.rotatedBoundingBox;e=Math.min(e,t.x),i=Math.min(i,t.y),n=Math.max(n,t.x+t.width),r=Math.max(r,t.y+t.height)}return{x:e,y:i,z:1,width:n-e,height:r-i}}static generateSvg(t,e={}){const{theme:i,padding:n=0,includeXmlDeclaration:r=!0,rasterSafeForCanvas:s=!1,imageDataUrls:o}=e;if(!t||0===t.length)return"";const h=this.flattenObjects(t),a=this.calculateCombinedBounds(h);if(!a)return"";const l=a.x-n,u=a.y-n,c=a.width+2*n,f=a.height+2*n,d=this.collectDefs(h,i),p=t.sort(((t,e)=>t.zIndex-e.zIndex)).map((t=>this.objectToSvgElement(t,i,o,s))).filter(Boolean).join("\n ");return`${r?'<?xml version="1.0" encoding="UTF-8"?>\n':""}<svg xmlns="http://www.w3.org/2000/svg" viewBox="${l} ${u} ${c} ${f}" width="${c}" height="${f}">${d.length>0?`\n <defs>\n ${d.join("\n ")}\n </defs>`:""}\n ${p}\n</svg>`}static flattenObjects(t){const e=[];for(const i of t)uo.isInstanceOf(i,"KritzelGroup")?e.push(...this.flattenObjects(i.children)):e.push(i);return e}static async resolveImageDataUrls(t,e){const i=new Map;if(!t||0===t.length)return i;const n=this.flattenObjects(t).filter((t=>uo.isInstanceOf(t,"KritzelImage")));return await Promise.all(n.map((async t=>{if(t.src?.startsWith("data:"))i.set(t.id,t.src);else if(t.resolvedSrc?.startsWith("data:"))i.set(t.id,t.resolvedSrc);else if(t.assetId&&e)try{const n=await e.fetchBlob(t.assetId);i.set(t.id,await this.blobToDataUrl(n))}catch(e){console.warn(`[KritzelSvgExportHelper] Failed to inline image asset ${t.assetId} for export:`,e)}}))),i}static async blobToDataUrl(t){if("undefined"!=typeof FileReader)try{return await new Promise(((e,i)=>{const n=new FileReader;n.onload=()=>{"string"!=typeof n.result?i(new Error("FileReader result is not a string")):e(n.result)},n.onerror=()=>i(n.error??new Error("Failed to read blob as data URL")),n.readAsDataURL(t)}))}catch{}const e=new Uint8Array(await t.arrayBuffer());return`data:${t.type||"application/octet-stream"};base64,${this.uint8ToBase64(e)}`}static uint8ToBase64(t){if("undefined"!=typeof Buffer)return Buffer.from(t).toString("base64");let e="";for(let i=0;i<t.length;i+=32768){const n=t.subarray(i,Math.min(i+32768,t.length));e+=String.fromCharCode(...n)}if("function"==typeof btoa)return btoa(e);throw new Error("No base64 encoder available in this runtime")}static collectDefs(t,e){const i=[];for(const n of t)uo.isInstanceOf(n,"KritzelLine")&&(n.hasStartArrow&&i.push(this.generateArrowMarker(n,"start",e)),n.hasEndArrow&&i.push(this.generateArrowMarker(n,"end",e)));return i}static generateArrowMarker(t,e,i){const n="start"===e?t.startMarkerId:t.endMarkerId,r=t.getArrowSize(e),s=t.getArrowFill(e);return`<marker id="${n}" markerWidth="${r}" markerHeight="${r}" refX="0" refY="${r/2}" orient="${"start"===e?"auto-start-reverse":"auto"}" markerUnits="userSpaceOnUse">\n <path d="${t.getArrowPath("start"===e?t.arrows?.start?.style:t.arrows?.end?.style)}" fill="${s}" transform="scale(${r/10})"/>\n </marker>`}static objectToSvgElement(t,e,i,n=!1){return uo.isInstanceOf(t,"KritzelPath")?this.pathToSvg(t,e):uo.isInstanceOf(t,"KritzelLine")?this.lineToSvg(t,e):uo.isInstanceOf(t,"KritzelShape")?this.shapeToSvg(t,e):uo.isInstanceOf(t,"KritzelText")?this.textToSvg(t,e,n):uo.isInstanceOf(t,"KritzelImage")?this.imageToSvg(t,i):uo.isInstanceOf(t,"KritzelCustomElement")?this.customElementToSvg(t,n):uo.isInstanceOf(t,"KritzelGroup")?this.groupToSvg(t,e,i,n):""}static pathToSvg(t,e){const i=this.buildTransform(t),n=g.resolveThemeColor(t.fill,e),r=g.resolveThemeColor(t.stroke,e),s=1!==t.opacity?` opacity="${t.opacity}"`:"",o=this.getObjectScale(t);return`<g transform="${i}"${s}>\n <svg viewBox="${t.viewBox}" width="${t.totalWidth/o}" height="${t.totalHeight/o}" overflow="visible">\n <path d="${t.d}" fill="${n||"none"}" stroke="${r||"none"}"${t.strokeWidth?` stroke-width="${t.strokeWidth}"`:""}/>\n </svg>\n </g>`}static lineToSvg(t,e){const i=this.buildTransform(t),n=g.resolveThemeColor(t.stroke,e),r=1!==t.opacity?` opacity="${t.opacity}"`:"",s=this.getObjectScale(t);return`<g transform="${i}"${r}>\n <svg viewBox="${t.viewBox}" width="${t.totalWidth/s}" height="${t.totalHeight/s}" overflow="visible">\n <path d="${t.d}" fill="none" stroke="${n}" stroke-width="${t.strokeWidth}" stroke-linecap="round"${t.hasStartArrow?` marker-start="url(#${t.startMarkerId})"`:""}${t.hasEndArrow?` marker-end="url(#${t.endMarkerId})"`:""}/>\n </svg>\n </g>`}static shapeToSvg(t,e){const i=this.buildTransform(t),n=g.resolveThemeColor(t.fillColor,e),r=g.resolveThemeColor(t.strokeColor,e),s=1!==t.opacity?` opacity="${t.opacity}"`:"",o=this.getObjectScale(t),h=t.getSvgPath();let a="";if(t.editor&&!t.editor.state.doc.textContent.trim());else if(t.content){const i=this.prosemirrorToHtml(t.content,t,e);if(i){const n=g.resolveThemeColor(t.fontColor,e);a=`\n <foreignObject x="${t.x}" y="${t.y}" width="${t.width}" height="${t.height}">\n <div xmlns="http://www.w3.org/1999/xhtml" style="width: 100%; height: 100%; display: flex; align-items: center; justify-content: center; text-align: center; font-family: ${t.fontFamily}; font-size: ${t.fontSize}px; color: ${n}; overflow: hidden;">\n ${i}\n </div>\n </foreignObject>`}}return`<g transform="${i}"${s}>\n <svg viewBox="${t.viewBox}" width="${t.totalWidth/o}" height="${t.totalHeight/o}" overflow="visible" preserveAspectRatio="none">\n <path d="${h}" fill="${n||"transparent"}" stroke="${r}" stroke-width="${t.strokeWidth}"/>${a}\n </svg>\n </g>`}static textToSvg(t,e,i=!1){if(i)return this.textToSvgRasterSafe(t,e);const n=this.buildTransform(t),r=1!==t.opacity?` opacity="${t.opacity}"`:"",s=g.resolveThemeColor(t.fontColor,e),o=g.resolveThemeColor(t.backgroundColor,e),h=this.getObjectScale(t),a=this.prosemirrorToHtml(t.content,t,e);return`<g transform="${n}"${r}>\n <foreignObject x="0" y="0" width="${t.totalWidth/h}" height="${t.totalHeight/h}">\n <div xmlns="http://www.w3.org/1999/xhtml" style="font-family: ${t.fontFamily}; font-size: ${t.fontSize}pt; color: ${s}; background-color: ${o||"transparent"}; transform: scale(${t.scaleFactor}); transform-origin: top left; white-space: pre-wrap; word-wrap: break-word;">\n ${a}\n </div>\n </foreignObject>\n </g>`}static textToSvgRasterSafe(t,e){const i=this.buildTransform(t),n=1!==t.opacity?` opacity="${t.opacity}"`:"",r=g.resolveThemeColor(t.fontColor,e),s=g.resolveThemeColor(t.backgroundColor,e),o=this.getObjectScale(t),h=t.totalWidth/o,a=t.totalHeight/o,l=this.prosemirrorToPlainTextLines(t.content),u=l.length>0?l:[""],c=Math.max(1,t.fontSize*(t.scaleFactor||1)),f=1.2*c,d=c,p=s&&"transparent"!==s?`<rect x="0" y="0" width="${h}" height="${a}" fill="${s}"/>`:"",m=u.map(((t,e)=>`<tspan x="0" y="${d+e*f}" xml:space="preserve">${this.escapeHtml(t)}</tspan>`)).join("");return`<g transform="${i}"${n}>\n ${p}\n <text font-family="${this.escapeHtml(t.fontFamily)}" font-size="${c}" fill="${r}">${m}</text>\n </g>`}static imageToSvg(t,e){const i=this.buildTransform(t),n=1!==t.opacity?` opacity="${t.opacity}"`:"",r=this.getObjectScale(t),s=t.totalWidth/r,o=t.totalHeight/r;return`<g transform="${i}"${n}>\n <image href="${e?.get(t.id)||t.resolvedSrc||t.src||""}" x="0" y="0" width="${s}" height="${o}" preserveAspectRatio="xMidYMid meet"/>\n </g>`}static customElementToSvg(t,e=!1){const i=this.buildTransform(t),n=1!==t.opacity?` opacity="${t.opacity}"`:"",r=this.getObjectScale(t),s=t.totalWidth/r,o=t.totalHeight/r;return e?(console.warn("[KritzelCustomElement SVG Export] Custom elements do not serialize well to PNG. Use SVG export or screenshot instead."),`<g transform="${i}"${n}>\n <rect x="0" y="0" width="${s}" height="${o}" fill="#f0f0f0" stroke="#999" stroke-width="1" />\n <text x="${s/2}" y="${o/2}" text-anchor="middle" dominant-baseline="middle" font-size="12" fill="#999">[Custom Element]</text>\n </g>`):`<g transform="${i}"${n}>\n <foreignObject x="0" y="0" width="${s}" height="${o}">\n <div xmlns="http://www.w3.org/1999/xhtml" style="width:100%;height:100%;overflow:hidden;">\n ${t.element?.outerHTML||'<div style="border:1px dashed #ccc">Empty</div>'}\n </div>\n </foreignObject>\n </g>`}static groupToSvg(t,e,i,n=!1){const r=t.children.sort(((t,e)=>t.zIndex-e.zIndex)).map((t=>this.objectToSvgElement(t,e,i,n))).filter(Boolean).join("\n ");return r?`<g${1!==t.opacity?` opacity="${t.opacity}"`:""}>\n ${r}\n </g>`:""}static buildTransform(t){const e=[],i=this.getObjectScale(t);if(e.push(`translate(${t.translateX}, ${t.translateY})`),0!==t.rotation){const n=t.rotation*(180/Math.PI);e.push(`rotate(${n}, ${t.totalWidth/2/i}, ${t.totalHeight/2/i})`)}return e.join(" ")}static getObjectScale(t){const e=t.scale??1;return 0===e?1:e}static prosemirrorToHtml(t,e,i){return t&&t.content?t.content.map((t=>this.nodeToHtml(t,i))).join(""):""}static nodeToHtml(t,e){if(!t)return"";switch(t.type){case"paragraph":return`<p style="margin: 0;">${(t.content?t.content.map((t=>this.nodeToHtml(t,e))).join(""):"")||"<br/>"}</p>`;case"text":let i=this.escapeHtml(t.text||"");if(t.marks)for(const n of t.marks)i=this.applyMark(i,n,e);return i;case"hard_break":return"<br/>";case"bullet_list":return`<ul style="margin: 0; padding-left: 1.5em;">${t.content?t.content.map((t=>this.nodeToHtml(t,e))).join(""):""}</ul>`;case"ordered_list":return`<ol style="margin: 0; padding-left: 1.5em;">${t.content?t.content.map((t=>this.nodeToHtml(t,e))).join(""):""}</ol>`;case"list_item":return`<li>${t.content?t.content.map((t=>this.nodeToHtml(t,e))).join(""):""}</li>`;default:return t.content?t.content.map((t=>this.nodeToHtml(t,e))).join(""):""}}static prosemirrorToPlainTextLines(t){if(!t||!Array.isArray(t.content))return[];const e=t.content.map((t=>this.nodeToPlainText(t))).join("").replace(/\r\n/g,"\n").replace(/\n+$/,"");return e?e.split("\n"):[]}static nodeToPlainText(t){if(!t)return"";switch(t.type){case"text":return t.text||"";case"hard_break":return"\n";case"paragraph":return`${Array.isArray(t.content)?t.content.map((t=>this.nodeToPlainText(t))).join(""):""}\n`;case"list_item":return`- ${(Array.isArray(t.content)?t.content.map((t=>this.nodeToPlainText(t))).join(""):"").trim()}\n`;default:return Array.isArray(t.content)?t.content.map((t=>this.nodeToPlainText(t))).join(""):""}}static applyMark(t,e,i){switch(e.type){case"bold":case"strong":return`<strong>${t}</strong>`;case"italic":case"em":return`<em>${t}</em>`;case"underline":return`<u>${t}</u>`;case"strike":return`<s>${t}</s>`;case"code":return`<code>${t}</code>`;case"link":return`<a href="${this.escapeHtml(e.attrs?.href||"#")}">${t}</a>`;default:return t}}static escapeHtml(t){return t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}}const oa=(()=>{let t=0;return()=>(t+=1,`u${`0000${(Math.random()*36**4|0).toString(36)}`.slice(-4)}${t}`)})();function ha(t){const e=[];for(let i=0,n=t.length;i<n;i++)e.push(t[i]);return e}let aa=null;function la(t={}){return aa||(t.includeStyleProperties?(aa=t.includeStyleProperties,aa):(aa=ha(window.getComputedStyle(document.documentElement)),aa))}function ua(t,e){const i=(t.ownerDocument.defaultView||window).getComputedStyle(t).getPropertyValue(e);return i?parseFloat(i.replace("px","")):0}function ca(t,e={}){return{width:e.width||function(t){const e=ua(t,"border-left-width"),i=ua(t,"border-right-width");return t.clientWidth+e+i}(t),height:e.height||function(t){const e=ua(t,"border-top-width"),i=ua(t,"border-bottom-width");return t.clientHeight+e+i}(t)}}const fa=16384;function da(t){return new Promise(((e,i)=>{const n=new Image;n.onload=()=>{n.decode().then((()=>{requestAnimationFrame((()=>e(n)))}))},n.onerror=i,n.crossOrigin="anonymous",n.decoding="async",n.src=t}))}const pa=(t,e)=>{if(t instanceof e)return!0;const i=Object.getPrototypeOf(t);return null!==i&&(i.constructor.name===e.name||pa(i,e))};function ga(t,e,i,n){const r=window.getComputedStyle(t,i),s=r.getPropertyValue("content");if(""===s||"none"===s)return;const o=oa();try{e.className=`${e.className} ${o}`}catch(t){return}const h=document.createElement("style");h.appendChild(function(t,e,i,n){const r=`.${t}:${e}`,s=i.cssText?function(t){const e=t.getPropertyValue("content");return`${t.cssText} content: '${e.replace(/'|"/g,"")}';`}(i):function(t,e){return la(e).map((e=>`${e}: ${t.getPropertyValue(e)}${t.getPropertyPriority(e)?" !important":""};`)).join(" ")}(i,n);return document.createTextNode(`${r}{${s}}`)}(o,i,r,n)),e.appendChild(h)}const ma="application/font-woff",wa="image/jpeg",va={woff:ma,woff2:ma,ttf:"application/font-truetype",eot:"application/vnd.ms-fontobject",png:"image/png",jpg:wa,jpeg:wa,gif:"image/gif",tiff:"image/tiff",svg:"image/svg+xml",webp:"image/webp"};function ya(t){const e=function(t){const e=/\.([^./]*?)$/g.exec(t);return e?e[1]:""}(t).toLowerCase();return va[e]||""}function ba(t){return-1!==t.search(/^(data:)/)}async function ka(t,e,i){const n=await fetch(t,e);if(404===n.status)throw new Error(`Resource "${n.url}" not found`);const r=await n.blob();return new Promise(((t,e)=>{const s=new FileReader;s.onerror=e,s.onloadend=()=>{try{t(i({res:n,result:s.result}))}catch(t){e(t)}},s.readAsDataURL(r)}))}const Ma={};async function Sa(t,e,i){const n=function(t,e,i){let n=t.replace(/\?.*/,"");return i&&(n=t),/ttf|otf|eot|woff2?/i.test(n)&&(n=n.replace(/.*\//,"")),e?`[${e}]${n}`:n}(t,e,i.includeQueryParams);if(null!=Ma[n])return Ma[n];let r;i.cacheBust&&(t+=(/\?/.test(t)?"&":"?")+(new Date).getTime());try{const n=await ka(t,i.fetchRequestInit,(({res:t,result:i})=>(e||(e=t.headers.get("Content-Type")||""),function(t){return t.split(/,/)[1]}(i))));r=function(t,e){return`data:${e};base64,${t}`}(n,e)}catch(e){r=i.imagePlaceholder||"";let n=`Failed to fetch resource: ${t}`;e&&(n="string"==typeof e?e:e.message),n&&console.warn(n)}return Ma[n]=r,r}const xa=t=>null!=t.tagName&&"SLOT"===t.tagName.toUpperCase(),Aa=t=>null!=t.tagName&&"SVG"===t.tagName.toUpperCase();async function $a(t,e,i){return i||!e.filter||e.filter(t)?Promise.resolve(t).then((t=>async function(t,e){return pa(t,HTMLCanvasElement)?async function(t){const e=t.toDataURL();return"data:,"===e?t.cloneNode(!1):da(e)}(t):pa(t,HTMLVideoElement)?async function(t,e){if(t.currentSrc){const e=document.createElement("canvas"),i=e.getContext("2d");return e.width=t.clientWidth,e.height=t.clientHeight,null==i||i.drawImage(t,0,0,e.width,e.height),da(e.toDataURL())}const i=t.poster,n=ya(i);return da(await Sa(i,n,e))}(t,e):pa(t,HTMLIFrameElement)?async function(t,e){var i;try{if(null===(i=null==t?void 0:t.contentDocument)||void 0===i?void 0:i.body)return await $a(t.contentDocument.body,e,!0)}catch(t){}return t.cloneNode(!1)}(t,e):t.cloneNode(Aa(t))}(t,e))).then((i=>async function(t,e,i){var n,r;if(Aa(e))return e;let s=[];return s=xa(t)&&t.assignedNodes?ha(t.assignedNodes()):pa(t,HTMLIFrameElement)&&(null===(n=t.contentDocument)||void 0===n?void 0:n.body)?ha(t.contentDocument.body.childNodes):ha((null!==(r=t.shadowRoot)&&void 0!==r?r:t).childNodes),0===s.length||pa(t,HTMLVideoElement)||await s.reduce(((t,n)=>t.then((()=>$a(n,i))).then((t=>{t&&e.appendChild(t)}))),Promise.resolve()),e}(t,i,e))).then((i=>function(t,e,i){return pa(e,Element)&&(function(t,e,i){const n=e.style;if(!n)return;const r=window.getComputedStyle(t);r.cssText?(n.cssText=r.cssText,n.transformOrigin=r.transformOrigin):la(i).forEach((i=>{let s=r.getPropertyValue(i);if("font-size"===i&&s.endsWith("px")){const t=Math.floor(parseFloat(s.substring(0,s.length-2)))-.1;s=`${t}px`}pa(t,HTMLIFrameElement)&&"display"===i&&"inline"===s&&(s="block"),"d"===i&&e.getAttribute("d")&&(s=`path(${e.getAttribute("d")})`),n.setProperty(i,s,r.getPropertyPriority(i))}))}(t,e,i),function(t,e,i){ga(t,e,":before",i),ga(t,e,":after",i)}(t,e,i),function(t,e){pa(t,HTMLTextAreaElement)&&(e.innerHTML=t.value),pa(t,HTMLInputElement)&&e.setAttribute("value",t.value)}(t,e),function(t,e){if(pa(t,HTMLSelectElement)){const i=Array.from(e.children).find((e=>t.value===e.getAttribute("value")));i&&i.setAttribute("selected","")}}(t,e)),e}(t,i,e))).then((t=>async function(t,e){const i=t.querySelectorAll?t.querySelectorAll("use"):[];if(0===i.length)return t;const n={};for(let r=0;r<i.length;r++){const s=i[r].getAttribute("xlink:href");if(s){const i=t.querySelector(s),r=document.querySelector(s);i||!r||n[s]||(n[s]=await $a(r,e,!0))}}const r=Object.values(n);if(r.length){const e="http://www.w3.org/1999/xhtml",i=document.createElementNS(e,"svg");i.setAttribute("xmlns",e),i.style.position="absolute",i.style.width="0",i.style.height="0",i.style.overflow="hidden",i.style.display="none";const n=document.createElementNS(e,"defs");i.appendChild(n);for(let t=0;t<r.length;t++)n.appendChild(r[t]);t.appendChild(i)}return t}(t,e))):null}const za=/url\((['"]?)([^'"]+?)\1\)/g,Ca=/url\([^)]+\)\s*format\((["']?)([^"']+)\1\)/g,Ta=/src:\s*(?:url\([^)]+\)\s*format\([^)]+\)[,;]\s*)+/g;function Ea(t){return-1!==t.search(za)}async function Oa(t,e,i){if(!Ea(t))return t;const n=function(t,{preferredFontFormat:e}){return e?t.replace(Ta,(t=>{for(;;){const[i,,n]=Ca.exec(t)||[];if(!n)return"";if(n===e)return`src: ${i};`}})):t}(t,i),r=function(t){const e=[];return t.replace(za,((t,i,n)=>(e.push(n),t))),e.filter((t=>!ba(t)))}(n);return r.reduce(((t,n)=>t.then((t=>async function(t,e,i,n){try{const r=i?function(t,e){if(t.match(/^[a-z]+:\/\//i))return t;if(t.match(/^\/\//))return window.location.protocol+t;if(t.match(/^[a-z]+:/i))return t;const i=document.implementation.createHTMLDocument(),n=i.createElement("base"),r=i.createElement("a");return i.head.appendChild(n),i.body.appendChild(r),e&&(n.href=e),r.href=t,r.href}(e,i):e,s=ya(e);let o;return o=await Sa(r,s,n),t.replace(function(t){const e=t.replace(/([.*+?^${}()|\[\]\/\\])/g,"\\$1");return new RegExp(`(url\\(['"]?)(${e})(['"]?\\))`,"g")}(e),`$1${o}$3`)}catch(t){}return t}(t,n,e,i)))),Promise.resolve(n))}async function Ia(t,e,i){var n;const r=null===(n=e.style)||void 0===n?void 0:n.getPropertyValue(t);if(r){const n=await Oa(r,null,i);return e.style.setProperty(t,n,e.style.getPropertyPriority(t)),!0}return!1}async function ja(t,e){pa(t,Element)&&(await async function(t,e){await Ia("background",t,e)||await Ia("background-image",t,e),await Ia("mask",t,e)||await Ia("-webkit-mask",t,e)||await Ia("mask-image",t,e)||await Ia("-webkit-mask-image",t,e)}(t,e),await async function(t,e){const i=pa(t,HTMLImageElement);if((!i||ba(t.src))&&(!pa(t,SVGImageElement)||ba(t.href.baseVal)))return;const n=i?t.src:t.href.baseVal,r=await Sa(n,ya(n),e);await new Promise(((n,s)=>{t.onload=n,t.onerror=e.onImageErrorHandler?(...t)=>{try{n(e.onImageErrorHandler(...t))}catch(t){s(t)}}:s;const o=t;o.decode&&(o.decode=n),"lazy"===o.loading&&(o.loading="eager"),i?(t.srcset="",t.src=r):t.href.baseVal=r}))}(t,e),await async function(t,e){const i=ha(t.childNodes).map((t=>ja(t,e)));await Promise.all(i).then((()=>t))}(t,e))}const Pa={};async function Ra(t){let e=Pa[t];if(null!=e)return e;const i=await fetch(t);return e={url:t,cssText:await i.text()},Pa[t]=e,e}async function Da(t,e){let i=t.cssText;const n=/url\(["']?([^"')]+)["']?\)/g,r=(i.match(/url\([^)]+\)/g)||[]).map((async r=>{let s=r.replace(n,"$1");return s.startsWith("https://")||(s=new URL(s,t.url).href),ka(s,e.fetchRequestInit,(({result:t})=>(i=i.replace(r,`url(${t})`),[r,t])))}));return Promise.all(r).then((()=>i))}function _a(t){if(null==t)return[];const e=[];let i=t.replace(/(\/\*[\s\S]*?\*\/)/gi,"");const n=new RegExp("((@.*?keyframes [\\s\\S]*?){([\\s\\S]*?}\\s*?)})","gi");for(;;){const t=n.exec(i);if(null===t)break;e.push(t[0])}i=i.replace(n,"");const r=/@import[\s\S]*?url\([^)]*\)[\s\S]*?;/gi,s=new RegExp("((\\s*?(?:\\/\\*[\\s\\S]*?\\*\\/)?\\s*?@media[\\s\\S]*?){([\\s\\S]*?)}\\s*?})|(([\\s\\S]*?){([\\s\\S]*?)})","gi");for(;;){let t=r.exec(i);if(null===t){if(t=s.exec(i),null===t)break;r.lastIndex=s.lastIndex}else s.lastIndex=r.lastIndex;e.push(t[0])}return e}function La(t){return t.trim().replace(/["']/g,"")}async function Ba(t,e){const i=await async function(t,e){if(null==t.ownerDocument)throw new Error("Provided element is not within a Document");const i=ha(t.ownerDocument.styleSheets),n=await async function(t,e){const i=[],n=[];return t.forEach((i=>{if("cssRules"in i)try{ha(i.cssRules||[]).forEach(((t,r)=>{if(t.type===CSSRule.IMPORT_RULE){let s=r+1;const o=Ra(t.href).then((t=>Da(t,e))).then((t=>_a(t).forEach((t=>{try{i.insertRule(t,t.startsWith("@import")?s+=1:i.cssRules.length)}catch(e){console.error("Error inserting rule from remote css",{rule:t,error:e})}})))).catch((t=>{console.error("Error loading remote css",t.toString())}));n.push(o)}}))}catch(r){const s=t.find((t=>null==t.href))||document.styleSheets[0];null!=i.href&&n.push(Ra(i.href).then((t=>Da(t,e))).then((t=>_a(t).forEach((t=>{s.insertRule(t,s.cssRules.length)})))).catch((t=>{console.error("Error loading remote stylesheet",t)}))),console.error("Error inlining remote css file",r)}})),Promise.all(n).then((()=>(t.forEach((t=>{if("cssRules"in t)try{ha(t.cssRules||[]).forEach((t=>{i.push(t)}))}catch(e){console.error(`Error while reading CSS rules from ${t.href}`,e)}})),i)))}(i,e);return function(t){return t.filter((t=>t.type===CSSRule.FONT_FACE_RULE)).filter((t=>Ea(t.style.getPropertyValue("src"))))}(n)}(t,e),n=function(t){const e=new Set;return function t(i){(i.style.fontFamily||getComputedStyle(i).fontFamily).split(",").forEach((t=>{e.add(La(t))})),Array.from(i.children).forEach((e=>{e instanceof HTMLElement&&t(e)}))}(t),e}(t);return(await Promise.all(i.filter((t=>n.has(La(t.style.fontFamily)))).map((t=>Oa(t.cssText,t.parentStyleSheet?t.parentStyleSheet.href:null,e))))).join("\n")}async function Fa(t,e={}){const{width:i,height:n}=ca(t,e),r=await $a(t,e,!0);return await async function(t,e){const i=null!=e.fontEmbedCSS?e.fontEmbedCSS:e.skipFonts?null:await Ba(t,e);if(i){const e=document.createElement("style"),n=document.createTextNode(i);e.appendChild(n),t.firstChild?t.insertBefore(e,t.firstChild):t.appendChild(e)}}(r,e),await ja(r,e),function(t,e){const{style:i}=t;e.backgroundColor&&(i.backgroundColor=e.backgroundColor),e.width&&(i.width=`${e.width}px`),e.height&&(i.height=`${e.height}px`);const n=e.style;null!=n&&Object.keys(n).forEach((t=>{i[t]=n[t]}))}(r,e),await async function(t,e,i){const n="http://www.w3.org/2000/svg",r=document.createElementNS(n,"svg"),s=document.createElementNS(n,"foreignObject");return r.setAttribute("width",`${e}`),r.setAttribute("height",`${i}`),r.setAttribute("viewBox",`0 0 ${e} ${i}`),s.setAttribute("width","100%"),s.setAttribute("height","100%"),s.setAttribute("x","0"),s.setAttribute("y","0"),s.setAttribute("externalResourcesRequired","true"),r.appendChild(s),s.appendChild(t),async function(t){return Promise.resolve().then((()=>(new XMLSerializer).serializeToString(t))).then(encodeURIComponent).then((t=>`data:image/svg+xml;charset=utf-8,${t}`))}(r)}(r,i,n)}class Na{static shouldKeepWheelInCustomElement(t,e){if(t.ctrlKey||!0!==e.isSelected)return!1;const i="function"==typeof t.composedPath?t.composedPath():[],n=this.getScrollableContainerFromEventPath(i,e);return!!n&&this.canElementConsumeWheel(n,t.deltaX,t.deltaY)}static getScrollableContainerFromEventPath(t,e){const i=[];e.element instanceof HTMLElement&&i.push(e.element),e.elementRef instanceof HTMLElement&&i.push(e.elementRef);const n=e.elmeentRef;n instanceof HTMLElement&&i.push(n);for(const e of i){const i=t.findIndex((t=>t===e));if(-1!==i)for(const e of t.slice(0,i+1))if(e instanceof HTMLElement&&this.isScrollableElement(e))return e}for(const t of i){if(this.isScrollableElement(t))return t;const e=t.firstElementChild;if(e instanceof HTMLElement&&this.isScrollableElement(e))return e}return null}static isScrollableElement(t){const e=t.scrollHeight-t.clientHeight>0,i=t.scrollWidth-t.clientWidth>0;if(!e&&!i)return!1;const n=window.getComputedStyle(t),r=n.overflowX,s=n.overflowY;return e&&"visible"!==s&&"clip"!==s||i&&"visible"!==r&&"clip"!==r}static canElementConsumeWheel(t,e,i){const n=this.canElementConsumeVerticalWheel(t,i),r=this.canElementConsumeHorizontalWheel(t,e);return n||r}static canElementConsumeVerticalWheel(t,e){if(0===e)return!1;const i=Math.max(0,t.scrollHeight-t.clientHeight);return 0!==i&&(e>0?t.scrollTop<i-1:!!(e<0)&&t.scrollTop>1)}static canElementConsumeHorizontalWheel(t,e){if(0===e)return!1;const i=Math.max(0,t.scrollWidth-t.clientWidth);return 0!==i&&(e>0?t.scrollLeft<i-1:!!(e<0)&&t.scrollLeft>1)}}const Wa=t(class t extends e{get host(){return this}workspace;async onWorkspaceChange(t){const e=t?.id;if(!e)return;await Promise.resolve();const i=this.core.store.state.activeWorkspace?.id;i!==e&&(this.core.beforeWorkspaceChange(),await this.initializeWorkspaceIfNeeded(t),this.activeWorkspaceChange.emit(this.core.store.state.activeWorkspace))}editorId;activeWorkspaceId;async onActiveWorkspaceIdChange(t){t&&this._isYjsInitialized&&await this.switchToWorkspaceById(t)}syncConfig;async onSyncConfigChange(t){this._syncConfigRevision++,this.core.setSyncConfig(t),t&&!this._isYjsInitialized&&this._isViewportReady&&await this.initializeSyncAndWorkspace()}assetStorageConfig;async onAssetStorageConfigChange(t){this._assetStorageConfigRevision++,this.core.setAssetStorageConfig(t),t&&!this._isAssetStorageInitialized&&this._isViewportReady&&await this.initializeAssetStorage()}user;onUserChange(t){this.core.setUser(t)}globalContextMenuItems;onGlobalContextMenuItemsChange(t){this.contextMenuHandler&&(this.contextMenuHandler.globalContextMenuItems=t??[])}objectContextMenuItems;onObjectContextMenuItemsChange(t){this.contextMenuHandler&&(this.contextMenuHandler.objectContextMenuItems=t??[])}scaleMax=k;validateScaleMax(t){t>k?(console.warn(`scaleMax cannot be greater than ${k}.`),this.scaleMax=k,this.core.store.state.scaleMax=this.scaleMax):this.core.store.state.scaleMax=t}scaleMin=M;validateScaleMin(t){t<M?(console.warn(`scaleMin cannot be less than ${M}.`),this.scaleMin=M,this.core.store.state.scaleMin=this.scaleMin):this.core.store.state.scaleMin=t}cursorTarget;onCursorTargetChange(t){this.core.cursorManager.setTargetElement(t||document.body)}lockDrawingScale=!0;onLockDrawingScaleChange(t){this.core.store.state.lockDrawingScale=t}isObjectDistanceFadingActive=!1;onIsObjectDistanceFadingActiveChange(){this.core.rerender()}theme="light";onThemeChange(t){this.core.themeManager.setTheme(t)}licenseKey;onLicenseKeyChange(t){this.core.licenseManager.validate(t)}themes;onThemesChange(t){t&&t.length>0&&(this.core.themeManager.registerThemes(t),this.core.themeManager.applyTheme(this.core.themeManager.currentTheme))}locale="en";onLocaleChange(t){this.core.localizationManager.setLocale(t)}locales;onLocalesChange(t){t&&t.length>0&&(this.core.localizationManager.registerLocales(t),this.core.localizationManager.setLocale(this.locale))}fallbackLocale="en";onFallbackLocaleChange(t){this.core.localizationManager.setFallbackLocale(t),this.core.rerender()}viewportBoundaryLeft=-1/0;onViewportBoundaryLeftChange(t){this.core.store.state.viewportBoundaryLeft=t??-1/0}viewportBoundaryRight=1/0;onViewportBoundaryRightChange(t){this.core.store.state.viewportBoundaryRight=t??1/0}viewportBoundaryTop=-1/0;onViewportBoundaryTopChange(t){this.core.store.state.viewportBoundaryTop=t??-1/0}viewportBoundaryBottom=1/0;onViewportBoundaryBottomChange(t){this.core.store.state.viewportBoundaryBottom=t??1/0}debugInfo;onDebugInfoChange(t){t&&(this.core.store.state.debugInfo=t,this.core.assetResolver.setShowInfo(t.showAssetResolverInfo))}isPanningEnabled=!0;isZoomingEnabled=!0;isLoading=!1;onIsLoadingChange(){this.syncLoadingState()}isEngineReady;activeToolChange;objectsSelectionChange;workspacesChange;activeWorkspaceChange;longpress;objectsChange;objectsAdded;objectsRemoved;objectsUpdated;undoStateChange;objectsInViewportChange;viewportChange;awarenessChange;notificationsChange;loadingChange;syncingChange;forceUpdate=0;isSyncing=!1;async triggerSelectionChange(){this.objectsSelectionChange.emit()}handleWheel(t){if(this.core.store.isDisabled)return;this.core.store.state.isContextMenuVisible&&this.hideContextMenu();const e=this.core.getObjectFromPointerEvent(t);e&&T.isClass(e,"KritzelCustomElement")&&Na.shouldKeepWheelInCustomElement(t,e)||(t.ctrlKey?this.isZoomingEnabled&&this.viewport.handleWheel(t):this.isPanningEnabled&&this.viewport.handleWheel(t),this.core.store.state?.activeTool?.handleWheel(t))}handlePointerDown(t){this.core.store.isDisabled||this.isEmbeddedCustomElementInteraction(t)||(v.isTouchDevice()&&yo.onLongPress(t,(t=>this.longpress.emit(t))),this.host.setPointerCapture(t.pointerId),this.core.store.state.pointers.set(t.pointerId,t),this.viewport.handlePointerDown(t),this.core.store.state?.activeTool?.handlePointerDown(t))}throttledPointerMoveMulti=Lh.throttle((t=>{this.viewport.handlePointerMove(t),this.core.store.state?.activeTool?.handlePointerMove(t)}),16);handlePointerMove(t){this.core.store.isDisabled||t.buttons>0&&!this.core.store.state.pointers.has(t.pointerId)||(this.core.store.state.pointers.has(t.pointerId)&&this.core.store.state.pointers.set(t.pointerId,t),this.core.store.state.pointers.size>1&&this.throttledPointerMoveMulti(t),this.core.cursorManager.updateHoverState(t),this.viewport.handlePointerMove(t),this.core.store.state?.activeTool?.handlePointerMove(t))}handlePointerUp(t){if(this.core.store.isDisabled)return;const e=this.core.store.state.pointers.has(t.pointerId);this.core.store.state.pointers.delete(t.pointerId),this.host.hasPointerCapture(t.pointerId)&&this.host.releasePointerCapture(t.pointerId),0===this.core.store.state.pointers.size&&this.core.cursorManager.resetToDefault(),e&&(this.viewport.handlePointerUp(t),this.core.store.state?.activeTool?.handlePointerUp(t))}handlePointerCancel(t){this.core.store.isDisabled||(this.host.hasPointerCapture(t.pointerId)&&this.host.releasePointerCapture(t.pointerId),this.core.store.state.pointers.delete(t.pointerId),0===this.core.store.state.pointers.size&&this.core.cursorManager.resetToDefault(),this.viewport.handlePointerUp(t),this.core.store.state?.activeTool?.handlePointerUp(t))}isEmbeddedCustomElementInteraction(t){const i=t.composedPath(),n=i.find((t=>t instanceof e&&t.classList.contains("object")));if(!n?.id)return!1;const r=this.core.store.objects.findById(n.id);if(!r||!uo.isInstanceOf(r,"KritzelCustomElement"))return!1;if(!this.core.store.selectionGroup?.objects?.some((t=>t.id===r.id)))return!1;if(!0!==r.isInteractive)return!1;const s=[];return r.element instanceof e&&s.push(r.element),r.elementRef instanceof e&&s.push(r.elementRef),0!==s.length&&s.some((t=>this.isNativeInteractiveEmbeddedTarget(i,t)))}isNativeInteractiveEmbeddedTarget(t,i){const n=t.findIndex((t=>t===i));if(-1===n)return!1;for(const i of t.slice(0,n))if(i instanceof e&&i.matches('input, button, textarea, select, a[href], [contenteditable="true"], [contenteditable=""]'))return!0;return!1}handlePointerLeave(){this.core.store.objects?.clearCursorPosition()}handleLongPress(t){this.contextMenuHandler.handleContextMenu(t.detail)}handleContextMenu(t){t.cancelable&&t.preventDefault(),this.core.store.isDisabled||"touch"!==t.pointerType&&"pen"!==t.pointerType&&this.contextMenuHandler.handleContextMenu(t)}handleResize(){this.viewport.handleResize()}handleKeyDown(t){!this.core.store.isDisabled&&this.shouldHandleGlobalShortcutEvent(t)&&this.keyHandler.handleKeyDown(t)}handleKeyUp(t){!this.core.store.isDisabled&&this.shouldHandleGlobalShortcutEvent(t)&&this.keyHandler.handleKeyUp(t)}handleCopy(t){!this.core.store.isDisabled&&this.shouldHandleGlobalShortcutEvent(t)&&(!this.core.store.selectionGroup||this.core.store.activeText||this.core.store.activeShape||(t.cancelable&&t.preventDefault(),this.core.clipboardManager.copy(t),this.core.rerender()))}handleCut(t){!this.core.store.isDisabled&&this.shouldHandleGlobalShortcutEvent(t)&&(!this.core.store.selectionGroup||this.core.store.activeText||this.core.store.activeShape||(t.cancelable&&t.preventDefault(),this.core.clipboardManager.cut(t)))}handlePaste(t){!this.core.store.isDisabled&&this.shouldHandleGlobalShortcutEvent(t)&&(this.core.store.activeText||this.core.store.activeShape||(t.cancelable&&t.preventDefault(),this.core.clipboardManager.paste(void 0,void 0,t)))}shouldHandleGlobalShortcutEvent(t){const i=t.composedPath();if(i.includes(this.host))return!0;if(i.some((t=>t instanceof e&&("DIALOG"===t.tagName||"KRITZEL-DIALOG"===t.tagName||"dialog"===t.getAttribute?.("role")||"alertdialog"===t.getAttribute?.("role")))))return!1;const n=i[0];return!(n instanceof e&&n.matches?.('input, textarea, select, [contenteditable="true"], [contenteditable=""]'))}preventDoubleTapZoomOnTouchDevices(t){t.cancelable&&t.preventDefault()}async registerTool(t,e,i){if("function"!=typeof e)return console.error(`Failed to register tool "${t}": Tool class must be a constructor function`),null;if(this.core.toolRegistry.hasTool(t)){const e=this.core.toolRegistry.getTool(t);return i&&this.applyToolConfig(e,i),e}const n=this.core.toolRegistry.registerTool(t,this.resolveToolClass(e));return i&&this.applyToolConfig(n,i),Promise.resolve(n)}async changeActiveTool(t){this.core.store.state.activeTool!==t&&(this.core.store.state.activeTool?.onDeactivate(),this.core.store.setState("activeTool",t),this.core.deselectAllObjects(),t?.onActivate())}async changeActiveToolByName(t){const e=this.core.toolRegistry.getTool(t);e?await this.changeActiveTool(e):console.warn(`[KritzelEngine] No tool registered with name: ${t}`)}async disable(){this.core.store.state.isEnabled=!1,this.core.rerender()}async enable(){this.core.store.state.isEnabled=!0,this.core.rerender()}async delete(){this.core.delete()}async copy(){this.core.clipboardManager.copy()}async cut(){this.core.clipboardManager.cut()}async paste(t,e){"granted"===await this.core.permissionManager.requestPermission("clipboard-read")?this.core.clipboardManager.paste(t,e):this.notificationsChange.emit({type:"error",message:"Clipboard read permission is required to paste content. Please grant permission and try again.",id:T.generateUUID()})}async bringForward(t){this.core.bringForward(t)}async sendBackward(t){this.core.sendBackward(t)}async bringToFront(t){this.core.bringToFront(t)}async sendToBack(t){this.core.sendToBack(t)}async alignObjects(t){this.core.alignObjects(t)}async group(){this.core.group()}async ungroup(){this.core.ungroup()}async undo(){this.core.undo()}async redo(){this.core.redo()}async hideContextMenu(){this.core.store.state.pointers.clear(),this.core.store.state.isContextMenuVisible=!1,this.core.store.objects?.remove((t=>t instanceof gh)),this.core.store.setSelectionBox(null),this.core.store.objects?.clearLocalSelectionBox(),this.core.store.state.isSelecting=!1,this.core.store.state.isEnabled=!0,this.core.rerender()}async openContextMenu(t){this.contextMenuHandler.open(t)}async getObjectById(t){return this.core.store.allObjects.find((e=>e.id===t))||null}async getAllObjects(){return this.core.store.allObjects}async findObjects(t){return this.core.store.allNonSelectionObjects.filter(t)}async getObjectsTotalCount(){return this.core.store.totalObjectCount}async addObject(t){if(this.core.deselectAllObjects(),t.id=t.generateId(),t._core=this.core,t.scale=t.scale??this.core.store.state.scale,t.zIndex=this.core.store.currentZIndex,t.workspaceId=this.core.store.state.activeWorkspace.id,uo.isInstanceOf(t,"KritzelImage")&&await t.prepareForInsert(),uo.isInstanceOf(t,"KritzelText")){const e=t.content;t.editor=t.createEditor(),e&&t.setContent(e)}if(uo.isInstanceOf(t,"KritzelGroup")&&t._pendingChildren.length>0){const e=new Map,i=[],n=t=>{if(0===t._pendingChildren.length)return;const r=t._pendingChildren;t._pendingChildren=[],t.childIds=[],r.forEach((r=>{const s=r.id;r.id=r.generateId(),r._core=this.core,r.scale=r.scale??this.core.store.state.scale,r.zIndex=this.core.store.currentZIndex,r.workspaceId=this.core.store.state.activeWorkspace.id,e.set(s,r.id),t.childIds.push(r.id),i.push(r),uo.isInstanceOf(r,"KritzelGroup")&&n(r)}))};n(t),i.forEach((t=>{uo.isInstanceOf(t,"KritzelLine")&&(t.startAnchor&&e.has(t.startAnchor.objectId)&&(t.startAnchor={objectId:e.get(t.startAnchor.objectId)}),t.endAnchor&&e.has(t.endAnchor.objectId)&&(t.endAnchor={objectId:e.get(t.endAnchor.objectId)}))})),i.forEach((t=>{this.core.addObject(t)})),t.finalize(),this.core.anchorManager.rebuildIndex()}return this.core.addObject(t),this.core.rerender(),await new Promise((t=>{requestAnimationFrame((()=>requestAnimationFrame((()=>t()))))})),this.emitObjectsChange(),this.emitObjectsAdded([t]),t}async addObjects(t){if(0===t.length)return[];for(const e of t)e._core=this.core,uo.isInstanceOf(e,"KritzelImage")&&await e.prepareForInsert();return this.core.store.objects.transaction((()=>{for(const e of t){if(e.id=e.generateId(),e._core=this.core,e.zIndex=this.core.store.currentZIndex,e.workspaceId=this.core.store.state.activeWorkspace.id,uo.isInstanceOf(e,"KritzelText")){const t=e.content;e.editor=e.createEditor(),t&&e.setContent(t)}if(uo.isInstanceOf(e,"KritzelGroup")&&e._pendingChildren.length>0){const t=new Map,i=[],n=e=>{if(0===e._pendingChildren.length)return;const r=e._pendingChildren;e._pendingChildren=[],e.childIds=[],r.forEach((r=>{const s=r.id;r.id=r.generateId(),r._core=this.core,r.zIndex=this.core.store.currentZIndex,r.workspaceId=this.core.store.state.activeWorkspace.id,t.set(s,r.id),e.childIds.push(r.id),i.push(r),uo.isInstanceOf(r,"KritzelGroup")&&n(r)}))};n(e),i.forEach((e=>{uo.isInstanceOf(e,"KritzelLine")&&(e.startAnchor&&t.has(e.startAnchor.objectId)&&(e.startAnchor={objectId:t.get(e.startAnchor.objectId)}),e.endAnchor&&t.has(e.endAnchor.objectId)&&(e.endAnchor={objectId:t.get(e.endAnchor.objectId)}))})),i.forEach((t=>{this.core.addObject(t)})),e.finalize(),this.core.anchorManager.rebuildIndex()}this.core.addObject(e)}})),this.core.rerender(),await new Promise((t=>{requestAnimationFrame((()=>requestAnimationFrame((()=>t()))))})),this.emitObjectsChange(),this.emitObjectsAdded(t),t}async updateObject(t,e){return this.core.deselectAllObjects(),this.core.updateObject(t,e),this.core.rerender(),this.emitObjectsChange(),this.emitObjectsUpdated([{object:t,changedProperties:Object.keys(e)}]),t}async removeObject(t){const e=this.core.store.objects;return e?(this.core.deselectAllObjects(),e.remove((e=>e.id===t.id)),this.core.rerender(),this.emitObjectsChange(),this.emitObjectsRemoved([t]),t):null}async removeObjects(t){const e=this.core.store.objects;return e&&0!==t.length?(e.transaction((()=>{for(const e of t)this.core.removeObject(e)})),this.core.rerender(),this.emitObjectsChange(),this.emitObjectsRemoved(t),t):[]}async getSelectedObjects(){const t=this.core.store.selectionGroup;return t?t.objects:[]}async getDisplayableShortcuts(){return this.keyHandler.getDisplayableShortcuts()}async selectObjects(t){const e=this.core.toolRegistry.getTool("selection");e&&(this.core.store.state.activeTool?.onDeactivate(),this.core.store.setState("activeTool",e),this.core.deselectAllObjects(),this.core.selectObjects(t))}async selectAllObjectsInViewport(){const t=this.core.toolRegistry.getTool("selection");t&&(this.core.store.state.activeTool?.onDeactivate(),this.core.store.setState("activeTool",t),this.core.deselectAllObjects(),this.core.selectAllObjectsInViewport())}async clearSelection(){this.core.clearSelection()}async centerObjectInViewport(t){return t.centerInViewport(),this.core.updateObject(t,t),this.core.rerender(),t}async panToObject(t){this.viewport.panTo(t.centerX,t.centerY)}async backToContent(){return this.viewport.centerFitNearestContent(20)}async centerAllObjects(t=!0){return this.viewport.centerFitAllObjects(t)}async centerObjects(t,e=!0){return this.viewport.centerFitObjects(t,e)}async setViewport(t,e,i){this.viewport.setViewport(t,e,i)}async panTo(t,e){this.viewport.panTo(t,e)}async zoomTo(t,e,i){this.viewport.zoomTo(t,e,i)}async zoomIn(t,e){this.viewport.zoomIn(t,e)}async zoomOut(t,e){this.viewport.zoomOut(t,e)}async getViewport(){return this.viewport.getViewport()}async screenToWorld(t,e){return this.viewport.screenToWorld(t,e)}async worldToScreen(t,e){return this.viewport.worldToScreen(t,e)}async getObjectsInViewport(){return this.core.getObjectsInViewport()}async getScreenshot(t="png",e){if(!this.host)return null;const i={objects:this.core.store.objects,activeWorkspace:this.core.store.state.activeWorkspace,workspaces:this.core.store.state.workspaces,activeTool:this.core.store.state.activeTool,isReady:this.core.store.state.isReady,translateX:this.core.store.state.translateX,translateY:this.core.store.state.translateY,scale:this.core.store.state.scale},n={filter:t=>!("KRITZEL-CONTEXT-MENU"===t.tagName||"KRITZEL-AWARENESS-CURSORS"===t.tagName||t.classList&&t.classList.contains("debug-panel"))};let r;(e?.includeBackground??1)||(n.backgroundColor="transparent");try{r="svg"===t?await Fa(this.host,n):await async function(t,e={}){return(await async function(t,e={}){const{width:i,height:n}=ca(t,e),r=await Fa(t,e),s=await da(r),o=document.createElement("canvas"),h=o.getContext("2d"),a=e.pixelRatio||function(){let t,e;try{e=process}catch(t){}const i=e&&e.env?e.env.devicePixelRatio:null;return i&&(t=parseInt(i,10),Number.isNaN(t)&&(t=1)),t||window.devicePixelRatio||1}(),l=e.canvasWidth||i,u=e.canvasHeight||n;return o.width=l*a,o.height=u*a,e.skipAutoScale||function(t){(t.width>fa||t.height>fa)&&(t.width>fa&&t.height>fa?t.width>t.height?(t.height*=fa/t.width,t.width=fa):(t.width*=fa/t.height,t.height=fa):t.width>fa?(t.height*=fa/t.width,t.width=fa):(t.width*=fa/t.height,t.height=fa))}(o),o.style.width=`${l}`,o.style.height=`${u}`,e.backgroundColor&&(h.fillStyle=e.backgroundColor,h.fillRect(0,0,o.width,o.height)),h.drawImage(s,0,0,o.width,o.height),o}(t,e)).toDataURL()}(this.host,n)}finally{this.core.store.state.objects=i.objects,this.core.store.state.activeWorkspace=i.activeWorkspace,this.core.store.state.workspaces=i.workspaces,this.core.store.state.activeTool=i.activeTool,this.core.store.state.isReady=i.isReady,this.core.store.state.translateX=i.translateX,this.core.store.state.translateY=i.translateY,this.core.store.state.scale=i.scale,this.core.rerender()}return r}async exportViewportAsPng(t){try{const e=`${this.core.store.state?.activeWorkspace?.name||"workspace"}-${(new Date).toISOString().replace(/[:.]/g,"-")}.png`,i=await this.getScreenshot("png",t);if(!i)return void console.error("Failed to export viewport as PNG: screenshot could not be generated");const n=document.createElement("a");n.download=e,n.href=i,n.click()}catch(t){console.error("Failed to export viewport as PNG:",t)}}async exportViewportAsSvg(t){try{const e=`${this.core.store.state?.activeWorkspace?.name||"workspace"}-${(new Date).toISOString().replace(/[:.]/g,"-")}.svg`,i=await this.getScreenshot("svg",t);if(!i)return void console.error("Failed to export viewport as SVG: screenshot could not be generated");const n=document.createElement("a");n.download=e,n.href=i,n.click()}catch(t){console.error("Failed to export viewport as SVG:",t)}}async getSelectedObjectsAsSvgString(t){const e=await this.getSelectedObjects();if(!e||0===e.length)return null;const i=t?.theme??this.core.themeManager.getStoredTheme(),n=await sa.resolveImageDataUrls(e,this.core.assetResolver);return sa.generateSvg(e,{theme:i,padding:t?.padding??0,includeXmlDeclaration:!0,rasterSafeForCanvas:t?.rasterSafeForCanvas??!1,imageDataUrls:n})}async exportSelectedObjectsAsSvg(t){try{const e=await this.getSelectedObjectsAsSvgString(t);if(!e)return void console.warn("No objects selected for SVG export");const i=`selection-${(new Date).toISOString().replace(/[:.]/g,"-")}.svg`,n=new Blob([e],{type:"image/svg+xml;charset=utf-8"}),r=URL.createObjectURL(n),s=document.createElement("a");s.download=i,s.href=r,s.click(),URL.revokeObjectURL(r)}catch(t){console.error("Failed to export selected objects as SVG:",t)}}async getSelectedObjectsAsPngDataUrl(t){const e=await this.getSelectedObjectsAsSvgString({theme:t?.theme,padding:t?.padding,rasterSafeForCanvas:!0});if(!e)return null;const i=t?.scale??2;return new Promise(((t,n)=>{const r=new Image,s=new Blob([e],{type:"image/svg+xml;charset=utf-8"}),o=URL.createObjectURL(s);r.onload=()=>{const e=document.createElement("canvas");e.width=r.width*i,e.height=r.height*i;const s=e.getContext("2d");if(!s)return URL.revokeObjectURL(o),void n(new Error("Failed to get canvas context"));s.scale(i,i),s.drawImage(r,0,0),URL.revokeObjectURL(o),t(e.toDataURL("image/png"))},r.onerror=()=>{URL.revokeObjectURL(o),n(new Error("Failed to load SVG for PNG conversion"))},r.src=o}))}async exportSelectedObjectsAsPng(t){try{const e=await this.getSelectedObjectsAsPngDataUrl(t);if(!e)return void console.warn("No objects selected for PNG export");const i=`selection-${(new Date).toISOString().replace(/[:.]/g,"-")}.png`,n=document.createElement("a");n.download=i,n.href=e,n.click()}catch(t){console.error("Failed to export selected objects as PNG:",t)}}async exportAsJson(){const t=this.core.store.state.activeWorkspace;if(!t)throw new Error("Cannot export workspace: no active workspace is loaded");const e=t.serialize({includeObjects:!0});return JSON.stringify(e,null,2)}async importFromJson(t){const e=JSON.parse(t);if(!e.__class__||"KritzelWorkspace"!==e.__class__)throw new Error("Invalid workspace data: missing or incorrect __class__ identifier");e.version&&e.version!==A&&console.warn(`Workspace version mismatch: expected ${A}, got ${e.version}`);const i=T.generateUUID();let n=e.viewport||{centerWorldX:0,centerWorldY:0,scale:1};if("translateX"in n&&!("centerWorldX"in n)){const t=n.scale??1;n={centerWorldX:-(n.translateX??0)/t,centerWorldY:-(n.translateY??0)/t,scale:t}}const r=new x(i,e.name||"Imported Workspace",n);if(this.core.createWorkspace(r),this.workspacesChange.emit(this.core.store.state.workspaces),this.core.beforeWorkspaceChange(),await this.core.initializeWorkspace(r),e.objects&&Array.isArray(e.objects)){const t=new Wh(this.core);for(const n of e.objects){const e=t.revive(n);e&&(e.workspaceId=i,this.core.addObject(e))}}this.core.rerender(),this.activeWorkspaceChange.emit(r)}async loadObjectsFromJson(t){const e=JSON.parse(t);if(!e.__class__||"KritzelWorkspace"!==e.__class__)throw new Error("Invalid workspace data: missing or incorrect __class__ identifier");e.version&&e.version!==A&&console.warn(`Workspace version mismatch: expected ${A}, got ${e.version}`);const i=this.core.store.state.activeWorkspace;if(!i)throw new Error("Cannot load objects: no active workspace is loaded");const n=i.id;let r=0;if(e.objects&&Array.isArray(e.objects)){const t=new Wh(this.core);for(const i of e.objects){const e=t.revive(i);e&&(e.workspaceId=n,this.core.addObject(e),r++)}}return this.core.rerender(),r}async downloadAsJson(t){try{const e=await this.exportAsJson(),i=this.core.store.state?.activeWorkspace?.name||"workspace",n=(new Date).toISOString().replace(/[:.]/g,"-"),r=t||`${i}-${n}`,s=new Blob([e],{type:"application/json;charset=utf-8"}),o=URL.createObjectURL(s),h=document.createElement("a");h.download=`${r}.json`,h.href=o,h.click(),URL.revokeObjectURL(o)}catch(t){console.error("Failed to download workspace as JSON:",t)}}async importFromFile(){return new Promise(((t,e)=>{const i=document.createElement("input");i.type="file",i.accept=".json,application/json",i.style.display="none";const n=()=>{i.removeEventListener("change",r),i.removeEventListener("cancel",s),document.body.removeChild(i)},r=async i=>{const r=i.target,s=r.files?.[0];if(!s)return n(),void t();try{const i=new FileReader;i.onload=async i=>{try{const e=i.target?.result;await this.importFromJson(e),n(),t()}catch(t){n(),console.error("Failed to import workspace from file:",t),e(t)}},i.onerror=()=>{n(),console.error("Failed to read file:",i.error),e(i.error)},i.readAsText(s)}catch(t){n(),console.error("Failed to process file:",t),e(t)}},s=()=>{n(),t()};i.addEventListener("change",r),i.addEventListener("cancel",s),document.body.appendChild(i),i.click()}))}async createWorkspace(t){return await this.core.createWorkspace(t),this.workspacesChange.emit(this.core.store.state.workspaces),t}async updateWorkspace(t){await this.core.updateWorkspace(t),this.workspacesChange.emit(this.core.store.state.workspaces)}async deleteWorkspace(t){await this.core.deleteWorkspace(t),this.workspacesChange.emit(this.core.store.state.workspaces)}async getWorkspaces(){return await this.core.getWorkspaces()}async getActiveWorkspace(){const t=this.core.store.state.activeWorkspace;if(!t)throw new Error("No active workspace is loaded");return t}async getIsPublic(){return this.core.getIsPublic()}async loadSharedWorkspace(t){const e=t;let i=this.core.getWorkspaces().find((t=>t.id===e));i?i.isPublic=!0:(i=new x(e,"Shared Workspace"),i.isPublic=!0,this.core.createWorkspace(i)),this.workspacesChange.emit(this.core.store.state.workspaces),this.core.beforeWorkspaceChange(),await this.initializeWorkspaceIfNeeded(i),this.activeWorkspaceChange.emit(this.core.store.state.activeWorkspace)}async reinitSync(){this.core.setSyncConfig(this.syncConfig),this.core.setAssetStorageConfig(this.assetStorageConfig),this.core.store.objects?.clearCursorPosition(),this.core.store.objects?.destroy(),this.core.appStateMap.destroy(),this.core.assetResolver.destroy(),this._isYjsInitialized=!1,this._isAssetStorageInitialized=!1,await this.initializeSyncAndWorkspace()}async saveSettings(t){const e=this.core.getStorageKey("kritzel-settings");localStorage.setItem(e,JSON.stringify(t))}async loadSettings(){const t=this.core.getStorageKey("kritzel-settings"),e=localStorage.getItem(t);if(!e)return null;try{return JSON.parse(e)}catch{return null}}async registerLocales(t){this.core.localizationManager.registerLocales(t),this.core.localizationManager.setLocale(this.core.localizationManager.currentLocale)}async setLocale(t){this.locale=t,this.core.localizationManager.setLocale(t)}async getLocale(){return this.core.localizationManager.currentLocale}async getAvailableLocales(){return this.core.localizationManager.getAvailableLocales()}async getAvailableLocaleOptions(){return this.core.localizationManager.getAvailableLocaleOptions()}async t(t,e){return this.core.localizationManager.translate(t,e)}async getResolvedTerms(){return this.core.localizationManager.getAllTerms()}core;viewport;contextMenuHandler;keyHandler;contextMenuElement=null;_lastHadSelectionGroup=!1;_isViewportReady=!1;_isYjsInitialized=!1;_isAssetStorageInitialized=!1;_isResolvingActiveWorkspaceId=!1;_stateChangeListenersRegistered=!1;_workspaceInitializationPromise=null;_workspaceInitializationTargetKey=null;_syncInitPromise=null;_syncConfigRevision=0;_assetStorageConfigRevision=0;_isWorkspaceLoading=!1;_hasLoggedUnlicensedWelcomeBanner=!1;_previousVisibleCustomElements=new Set;_revealedImageKeys=new Set;_defaultUndoState={canUndo:!1,canRedo:!1,undoStackSize:0,redoStackSize:0};_objectDistanceFadeNearScale=1;_objectDistanceFadeFarScale=.15;_objectDistanceFadeMinOpacity=0;_objectDistanceFadeCloseStartScale=2;_objectDistanceFadeCloseMaxScale=4;_objectDistanceFadeCloseMinOpacity=0;syncLoadingState(){this.core.store.state.isLoading=this._isWorkspaceLoading||this.isLoading,this.loadingChange.emit(this.core.store.state.isLoading)}syncSyncingState(t){this.isSyncing=t,this.syncingChange.emit(t)}applyToolConfig(t,e){const i=this.normalizeToolConfig(e);if(Object.entries(i).forEach((([e,i])=>{t[e]=i})),"palettes"in i&&"type"in i){const e=i.palettes[i.type];e&&(t.palette=e)}if("sizes"in i&&null!=i.sizes&&"type"in i){const e=i,n=e.sizes?.[e.type];n&&(t.sizes=n)}}normalizeToolConfig(t){return this.isTextToolConfig(t)?{...t,availableFonts:b(t.availableFonts)}:t}isTextToolConfig(t){return"fontFamily"in t&&"size"in t&&"color"in t}static BUILT_IN_TOOL_CLASSES={selection:yh,brush:Mo,eraser:Ao,line:xo,shape:ah,text:hh,image:oh};resolveToolClass(e){if(e.prototype instanceof vo)return e;try{const i=new e(this.core);return t.BUILT_IN_TOOL_CLASSES[i.toolType]??e}catch{return e}}get isSelecting(){return"selection"===this.core.store.state.activeTool?.toolType&&this.core.store.state.isSelecting}get isSelectionActive(){return"selection"===this.core.store.state.activeTool?.toolType&&null!==this.core.store.selectionGroup}constructor(t){super(),!1!==t&&this.__registerHost(),this.__attachShadow(),this.isEngineReady=i(this,"isEngineReady"),this.activeToolChange=i(this,"activeToolChange"),this.objectsSelectionChange=i(this,"objectsSelectionChange"),this.workspacesChange=i(this,"workspacesChange"),this.activeWorkspaceChange=i(this,"activeWorkspaceChange"),this.longpress=i(this,"longpress"),this.objectsChange=i(this,"objectsChange"),this.objectsAdded=i(this,"objectsAdded"),this.objectsRemoved=i(this,"objectsRemoved"),this.objectsUpdated=i(this,"objectsUpdated"),this.undoStateChange=i(this,"undoStateChange"),this.objectsInViewportChange=i(this,"objectsInViewportChange"),this.viewportChange=i(this,"viewportChange"),this.awarenessChange=i(this,"awarenessChange"),this.notificationsChange=i(this,"notificationsChange"),this.loadingChange=i(this,"loadingChange"),this.syncingChange=i(this,"syncingChange"),this.core=new ra(this)}disconnectedCallback(){this.throttledPointerMoveMulti.cancel(),this._revealedImageKeys.clear(),this.core.store.allObjects&&this.core.store.allObjects.forEach((t=>{uo.isInstanceOf(t,"KritzelCustomElement")&&t.unmount()})),this.core.store.objects?.clearCursorPosition(),this.core.store.objects&&this.core.store.objects.destroy(),this.core.appStateMap.destroy(),this.core.cursorManager.cleanup(),this.core.themeManager.cleanup(),this.core.licenseManager.destroy()}componentWillLoad(){this.core.setEditorId(this.editorId),this.themes&&this.themes.length>0&&this.core.themeManager.registerThemes(this.themes);const t=this.host.closest("kritzel-editor");this.core.themeManager.injectThemeEarly(t||this.host),this.locales&&this.locales.length>0&&this.core.localizationManager.registerLocales(this.locales),this.core.localizationManager.setFallbackLocale(this.fallbackLocale),this.core.localizationManager.setLocale(this.locale),this.core.licenseManager.validate(this.licenseKey),this.core.licenseManager.startPeriodicValidation(),this.core.setUser(this.user),this.validateScaleMax(this.scaleMax),this.validateScaleMin(this.scaleMin),this.core.store.state.lockDrawingScale=this.lockDrawingScale,this.core.store.state.viewportBoundaryLeft=this.viewportBoundaryLeft,this.core.store.state.viewportBoundaryRight=this.viewportBoundaryRight,this.core.store.state.viewportBoundaryTop=this.viewportBoundaryTop,this.core.store.state.viewportBoundaryBottom=this.viewportBoundaryBottom,this._isWorkspaceLoading=!0,this.syncLoadingState()}async componentDidLoad(){setTimeout((async()=>{this.contextMenuHandler=new Nh(this.core,this.globalContextMenuItems??[],this.objectContextMenuItems??[]),this.keyHandler=new Fh(this.core),this.viewport=new Bh(this.core,this.host),this._isViewportReady=!0,this.core.cursorManager.setTargetElement(this.cursorTarget||document.body),this.host.shadowRoot&&this.core.cursorManager.setShadowRoot(this.host.shadowRoot);const t=this.host.closest("kritzel-editor");this.core.themeManager.setTargetElement(t||this.host),await this.initializeSyncAndWorkspace(),!1===this.core.store.state.isReady&&(this.core.store.state.isReady=!0,this.logUnlicensedWelcomeBanner(),this.isEngineReady.emit(this.core.store.state))}),50)}async initializeSyncAndWorkspace(){if(this._syncInitPromise)return this._syncInitPromise;this._syncInitPromise=this.doInitializeSyncAndWorkspace();try{await this._syncInitPromise}finally{this._syncInitPromise=null}}async initializeAssetStorage(){if(this._isAssetStorageInitialized)return;const t=this._assetStorageConfigRevision;this.core.setAssetStorageConfig(this.assetStorageConfig),await this.core.initializeAssetStorage(),t!==this._assetStorageConfigRevision&&(this.core.assetResolver.destroy(),this.core.setAssetStorageConfig(this.assetStorageConfig),await this.core.initializeAssetStorage()),this._isAssetStorageInitialized=!0}logUnlicensedWelcomeBanner(){this.core.licenseManager.isLicensed||this._hasLoggedUnlicensedWelcomeBanner||(this._hasLoggedUnlicensedWelcomeBanner=!0,console.info("%c👋 Welcome to Kritzel","color: #007AFF; font-weight: 700;"),console.info("This version of Kritzel is not licensed. Get a license at: https://kritzel.io"))}async doInitializeSyncAndWorkspace(){const t=this._syncConfigRevision;if(this.core.setSyncConfig(this.syncConfig),this.core.setAssetStorageConfig(this.assetStorageConfig),this._isYjsInitialized||(await this.core.initializeYjs(),t!==this._syncConfigRevision&&(this.core.appStateMap.destroy(),this.core.setSyncConfig(this.syncConfig),this.core.setAssetStorageConfig(this.assetStorageConfig),await this.core.initializeYjs()),this._isYjsInitialized=!0),!this._isAssetStorageInitialized&&this.assetStorageConfig&&await this.initializeAssetStorage(),this.activeWorkspaceId){const t=this.core.getWorkspaces().find((t=>t.id===this.activeWorkspaceId));t?await this.initializeWorkspaceIfNeeded(t):await this.initializeWorkspaceIfNeeded()}else{const t=this.resolveStartupWorkspace();await this.initializeWorkspaceIfNeeded(t)}const e=this.core.store.state.activeWorkspace;e&&this.activeWorkspaceChange.emit(e),this._stateChangeListenersRegistered||(this.core.appStateMap.onRemoteChange((()=>{this.workspacesChange.emit(this.core.store.state.workspaces),this.tryResolveActiveWorkspaceFromId()})),this._registerStateChangeListeners(),this._stateChangeListenersRegistered=!0),this.tryResolveActiveWorkspaceFromId()}resolveStartupWorkspace(){if(this.activeWorkspaceId){const t=this.core.getWorkspaces().find((t=>t.id===this.activeWorkspaceId));if(t)return t;console.warn(`[KritzelEngine] No workspace found with ID: ${this.activeWorkspaceId}`)}return this.workspace}tryResolveActiveWorkspaceFromId(){this.activeWorkspaceId&&!this._isResolvingActiveWorkspaceId&&this.core.store.state.activeWorkspace?.id!==this.activeWorkspaceId&&(this._isResolvingActiveWorkspaceId=!0,this.switchToWorkspaceById(this.activeWorkspaceId,!1).finally((()=>{this._isResolvingActiveWorkspaceId=!1})))}async switchToWorkspaceById(t,e=!0){const i=this.core.getWorkspaces().find((e=>e.id===t));i?this.core.store.state.activeWorkspace?.id!==i.id&&(this.core.beforeWorkspaceChange(),await this.initializeWorkspaceIfNeeded(i),this.activeWorkspaceChange.emit(this.core.store.state.activeWorkspace)):e&&console.warn(`[KritzelEngine] No workspace found with ID: ${t}`)}async initializeWorkspaceIfNeeded(t,e){const i=t?.id??null,n=i??(e?.skipFallbackCreation?"__NO_FALLBACK__":"__AUTO__");if(i&&this.core.store.state.activeWorkspace?.id===i)return;if(this._workspaceInitializationPromise&&this._workspaceInitializationTargetKey===n)return void await this._workspaceInitializationPromise;this._isWorkspaceLoading=!0,this.syncLoadingState();const r=this.core.initializeWorkspace(t,e);this._workspaceInitializationPromise=r,this._workspaceInitializationTargetKey=n;try{await r;const t=this.core.store.objects,e=t?.whenNetworkSynced();e?(this.syncSyncingState(!0),e.finally((()=>{this.core.store.objects===t&&this.syncSyncingState(!1)}))):this.syncSyncingState(!1)}finally{this._workspaceInitializationPromise===r&&(this._workspaceInitializationPromise=null,this._workspaceInitializationTargetKey=null,this._isWorkspaceLoading=!1,this.syncLoadingState())}}emitObjectsChange(){const t=this.core.store.objects;if(!t)return this.objectsChange.emit([]),this.undoStateChange.emit(this._defaultUndoState),void(this._lastHadSelectionGroup&&(this._lastHadSelectionGroup=!1,this.objectsSelectionChange.emit()));const e=t.undoState,i=null!==this.core.store.selectionGroup;this.objectsChange.emit(this.core.store.allObjects),this.undoStateChange.emit(e),this._lastHadSelectionGroup!==i&&(this._lastHadSelectionGroup=i,this.objectsSelectionChange.emit())}emitObjectsAdded(t){this.objectsAdded.emit({objects:t})}emitObjectsRemoved(t){this.objectsRemoved.emit({objects:t})}emitObjectsUpdated(t){this.objectsUpdated.emit({objects:t})}emitAwarenessChange(t){this.awarenessChange.emit(t)}emitObjectsInViewportChange(){this.objectsInViewportChange.emit(this.core.store.objectsInViewport)}_registerStateChangeListeners(){this.core.store.onStateChange("activeTool",this._handleActiveToolChange.bind(this))}_handleActiveToolChange(t){"selection"!==t?.toolType&&(this.core.clearSelection(),this.core.store.objects?.remove((t=>t instanceof gh)),this.core.store.setSelectionBox(null),this.core.store.objects?.clearLocalSelectionBox(),this.core.store.state.isSelecting=!1,this.core.store.state.isResizeHandleSelected=!1,this.core.store.state.isRotationHandleSelected=!1),"text"!==t?.toolType&&this.core.resetActiveText(),"shape"!==t?.toolType&&this.core.resetActiveShape(),this.core.store.state.skipContextMenu=!1,t&&this.activeToolChange.emit(t),_.forceHideKeyboard(),this.core.rerender()}getObjectDistanceFadeMultiplier(t,e){if(!this.isObjectDistanceFadingActive)return 1;const i=Math.max(Number.isFinite(e)?e:1,Number.EPSILON)/Math.max(Number.isFinite(t)?t:1,Number.EPSILON),n=this.getFarDistanceFadeMultiplier(i),r=this.getCloseDistanceFadeMultiplier(i);return Math.min(n,r)}getFarDistanceFadeMultiplier(t){if(t>=this._objectDistanceFadeNearScale)return 1;if(t<=this._objectDistanceFadeFarScale)return this._objectDistanceFadeMinOpacity;const e=(this._objectDistanceFadeNearScale-t)/(this._objectDistanceFadeNearScale-this._objectDistanceFadeFarScale);return 1-e*e*(3-2*e)*(1-this._objectDistanceFadeMinOpacity)}getCloseDistanceFadeMultiplier(t){if(t<=this._objectDistanceFadeCloseStartScale)return 1;if(t>=this._objectDistanceFadeCloseMaxScale)return this._objectDistanceFadeCloseMinOpacity;const e=(t-this._objectDistanceFadeCloseStartScale)/(this._objectDistanceFadeCloseMaxScale-this._objectDistanceFadeCloseStartScale);return 1-e*e*(3-2*e)*(1-this._objectDistanceFadeCloseMinOpacity)}shouldApplyDistanceFade(t){return!uo.isInstanceOf(t,"KritzelSelectionGroup")&&!uo.isInstanceOf(t,"KritzelSelectionBox")}getObjectEffectiveOpacity(t,e){const i=Number.isFinite(t.opacity)?t.opacity:1,n=this.shouldApplyDistanceFade(t)?this.getObjectDistanceFadeMultiplier(t.scale,e):1;return{multiplied:(t.markedForRemoval?.5:1)*i*n,overridden:((t.markedForRemoval?.5:i)*n).toString()}}getSelectionHandleCapabilities(t){const e=uo.isInstanceOf(t,"KritzelSelectionGroup")?t.objects:[t];return{canRenderResizeHandles:e.every((t=>!1!==t.isResizable)),canRenderRotationHandle:e.every((t=>!1!==t.isRotatable))}}getImageRevealKey(t){return t.assetId?`asset:${t.assetId}`:t.id?`object:${t.id}`:null}shouldAnimateImageFirstReveal(t){if("ready"!==t.loadState)return!1;const e=this.getImageRevealKey(t);return!!e&&!this._revealedImageKeys.has(e)&&(this._revealedImageKeys.add(e),!0)}render(){if(!this.viewport)return n(r,null);const t=this.core.themeManager.getStoredTheme(),e=window.getComputedStyle(this.host).getPropertyValue("--kritzel-selection-handle-size").trim()||"6px",i=parseFloat(e),s=2*i<14?14:i,o=this.core.store.state.scale,h=this.core.store.state.viewportWidth/2+this.core.store.state.translateX,a=this.core.store.state.viewportHeight/2+this.core.store.state.translateY,l=this.core.store.objectsInViewport,u=t=>this.core.store.state.isScaling||uo.isInstanceOf(t,"KritzelSelectionGroup")?"none":"auto",c=t=>t.markedForRemoval||uo.isInstanceOf(t,"KritzelSelectionGroup")&&1===t.objects.length&&uo.isInstanceOf(t.objects[0],"KritzelCustomElement")?"none":"auto",f=new Set;return l.forEach((t=>{uo.isInstanceOf(t,"KritzelCustomElement")&&f.add(t.id)})),this._previousVisibleCustomElements.forEach((t=>{if(!f.has(t)){const e=this.core.store.objects.findById(t);e&&uo.isInstanceOf(e,"KritzelCustomElement")&&e.unmount()}})),this._previousVisibleCustomElements=f,this.core.cursorManager.applyCursor(),this.core.store.state.hasViewportChanged&&(this.viewportChange.emit(this.viewport.getViewport()),this.core.store.totalObjectCount>0&&this.emitObjectsInViewportChange()),n(r,null,n("kritzel-loading-overlay",{visible:this.core.store.state.isLoading,text:this.core.localizationManager.translate("engine.loading")}),n("kritzel-sync-indicator",{visible:this.isSyncing,text:"Syncing..."}),this.core.store.state.debugInfo.showViewportInfo&&n("div",{class:"debug-panel"},n("div",null,"ActiveWorkspaceId: ",this.core.store.state?.activeWorkspace?.id),n("div",null,"ActiveWorkspaceName: ",this.core.store.state?.activeWorkspace?.name),n("div",null,"TranslateX: ",this.core.store.state?.translateX),n("div",null,"TranslateY: ",this.core.store.state?.translateY),n("div",null,"ViewportWidth: ",this.core.store.state?.viewportWidth),n("div",null,"ViewportHeight: ",this.core.store.state?.viewportHeight),n("div",null,"PointerCount: ",this.core.store.state.pointers.size),n("div",null,"Scale: ",this.core.store.state?.scale),n("div",null,"ActiveTool: ",this.core.store.state?.activeTool?.name),n("div",null,"HasViewportChanged: ",this.core.store.state?.hasViewportChanged?"true":"false"),n("div",null,"IsEnabled: ",this.core.store.state?.isEnabled?"true":"false"),n("div",null,"IsScaling: ",this.core.store.state?.isScaling?"true":"false"),n("div",null,"IsPanning: ",this.core.store.state?.isPanning?"true":"false"),n("div",null,"IsSelecting: ",this.isSelecting?"true":"false"),n("div",null,"IsSelectionActive: ",this.isSelectionActive?"true":"false"),n("div",null,"IsResizeHandleSelected: ",this.core.store.state.isResizeHandleSelected?"true":"false"),n("div",null,"IsRotationHandleSelected: ",this.core.store.state.isRotationHandleSelected?"true":"false"),n("div",null,"IsRotationHandleHovered: ",this.core.store.state.isRotationHandleHovered?"true":"false"),n("div",null,"IsDrawing: ",this.core.store.state.isDrawing?"true":"false"),n("div",null,"IsWriting: ",this.core.store.state.isWriting?"true":"false"),n("div",null,"IsPointerDown: ",this.core.store.isPointerDown?"true":"false"),n("div",null,"PointerX: ",this.core.store.state?.pointerX),n("div",null,"PointerY: ",this.core.store.state?.pointerY),n("div",null,"TotalObjects: ",this.core.store.totalObjectCount),n("div",null,"ObjectsInViewport: ",this.core.store.objectsInViewport.length),n("div",null,"SelectedObjects: ",this.core.store.selectionGroup?.objects.length||0),n("div",null,"ViewportCenter: (",h.toFixed(2),", ",a.toFixed(2),")")),n("div",{id:"origin",class:"origin",style:{transform:`matrix(${this.core.store.state?.scale}, 0, 0, ${this.core.store.state?.scale}, ${this.core.store.state?.translateX}, ${this.core.store.state?.translateY})`}},l?.map((e=>{const{multiplied:r,overridden:h}=this.getObjectEffectiveOpacity(e,o);return n("div",{key:e.id,id:e.id,class:"object",style:{transform:e?.transformationMatrix,transformOrigin:"top left",position:"absolute",zIndex:this.core.displaySelectionLineUI(e)?"10001":e.zIndex.toString(),pointerEvents:u(e)}},uo.isInstanceOf(e,"KritzelPath")&&n("svg",{ref:t=>t&&e.mount(t),xmlns:"http://www.w3.org/2000/svg",style:{height:e?.totalHeight+"px",width:e?.totalWidth+"px",left:"0",top:"0",position:"absolute",transform:0!==e.rotationDegrees?`rotate(${e.rotationDegrees}deg)`:void 0,transformOrigin:0!==e.rotationDegrees?`${e.totalWidth/2}px ${e.totalHeight/2}px`:void 0,pointerEvents:e.markedForRemoval?"none":"auto",overflow:"visible"},viewBox:e?.viewBox},n("path",{d:e?.d,fill:g.applyOpacity(e.fill,r,t),stroke:g.applyOpacity(e?.stroke,r,t),"shape-rendering":e.isLowRes()?"optimizeSpeed":"auto"})),uo.isInstanceOf(e,"KritzelLine")&&n("svg",{ref:t=>t&&e.mount(t),xmlns:"http://www.w3.org/2000/svg",style:{height:e?.totalHeight+"px",width:e?.totalWidth+"px",left:"0",top:"0",position:"absolute",transform:0!==e.rotationDegrees?`rotate(${e.rotationDegrees}deg)`:void 0,transformOrigin:0!==e.rotationDegrees?`${e.totalWidth/2}px ${e.totalHeight/2}px`:void 0,pointerEvents:e.markedForRemoval?"none":"auto",overflow:"visible"},viewBox:e?.viewBox},(e.hasStartArrow||e.hasEndArrow)&&n("defs",null,e.hasStartArrow&&n("marker",{id:e.startMarkerId,markerWidth:e.getArrowSize("start"),markerHeight:e.getArrowSize("start"),refX:0,refY:e.getArrowSize("start")/2,orient:"auto-start-reverse",markerUnits:"userSpaceOnUse"},n("path",{d:e.getArrowPath(e.arrows?.start?.style),fill:g.applyOpacity(e.getArrowFill("start"),r),transform:`scale(${e.getArrowSize("start")/10})`})),e.hasEndArrow&&n("marker",{id:e.endMarkerId,markerWidth:e.getArrowSize("end"),markerHeight:e.getArrowSize("end"),refX:0,refY:e.getArrowSize("end")/2,orient:"auto",markerUnits:"userSpaceOnUse"},n("path",{d:e.getArrowPath(e.arrows?.end?.style),fill:g.applyOpacity(e.getArrowFill("end"),r),transform:`scale(${e.getArrowSize("end")/10})`}))),n("path",{d:this.core.anchorManager.computeClippedLinePath(e),fill:"none",stroke:"transparent","stroke-width":Math.max(e?.strokeWidth||0,10),"stroke-linecap":"round"}),n("path",{d:this.core.anchorManager.computeClippedLinePath(e),fill:"none",stroke:g.applyOpacity(e?.stroke,r,t),"stroke-width":e?.strokeWidth,"stroke-linecap":"round","marker-start":e.hasStartArrow?`url(#${e.startMarkerId})`:void 0,"marker-end":e.hasEndArrow?`url(#${e.endMarkerId})`:void 0})),uo.isInstanceOf(e,"KritzelImage")&&"ready"===e.loadState&&n("img",{ref:t=>t&&e.mount(t),class:this.shouldAnimateImageFirstReveal(e)?"kritzel-image-object kritzel-image-object--first-reveal":"kritzel-image-object",src:e.resolvedSrc||e.src,style:{position:"absolute",left:"0",top:"0",width:e.totalWidth+"px",height:e.totalHeight+"px",transform:0!==e.rotationDegrees?`rotate(${e.rotationDegrees}deg)`:void 0,transformOrigin:0!==e.rotationDegrees?`${e.totalWidth/2}px ${e.totalHeight/2}px`:void 0,opacity:h,pointerEvents:e.markedForRemoval?"none":"auto",backgroundColor:g.resolveThemeColor(e.backgroundColor,t),borderColor:g.resolveThemeColor(e.borderColor,t),borderWidth:e.borderWidth+"px",borderStyle:"solid",padding:e.padding+"px",overflow:"visible",userSelect:"none",imageRendering:this.core.store.state.isScaling||this.core.store.state.isPanning?"pixelated":"auto"},draggable:!1,decoding:"async",loading:"eager",onDragStart:t=>t.preventDefault()}),uo.isInstanceOf(e,"KritzelImage")&&"ready"!==e.loadState&&n("div",{ref:()=>e.ensureLoaded(),style:{position:"absolute",left:"0",top:"0",width:e.totalWidth+"px",height:e.totalHeight+"px",transform:0!==e.rotationDegrees?`rotate(${e.rotationDegrees}deg)`:void 0,transformOrigin:0!==e.rotationDegrees?`${e.totalWidth/2}px ${e.totalHeight/2}px`:void 0,opacity:h,pointerEvents:e.markedForRemoval?"none":"auto",backgroundColor:g.resolveThemeColor({light:"#e5e7eb",dark:"#2a2a2a"},t),borderColor:g.resolveThemeColor("error"===e.loadState?{light:"#9ca3af",dark:"#6b7280"}:e.borderColor,t),borderWidth:"error"===e.loadState?"1px":e.borderWidth+"px",borderStyle:"solid",padding:e.padding+"px",overflow:"hidden",userSelect:"none",display:"flex",alignItems:"center",justifyContent:"center"}},n("kritzel-icon",{name:"error"===e.loadState?"image-off":"image",size:Math.max(16,.3*Math.min(e.totalWidth,e.totalHeight)),style:{color:g.resolveThemeColor({light:"#9ca3af",dark:"#6b7280"},t)}})),uo.isInstanceOf(e,"KritzelCustomElement")&&n("div",{ref:t=>t&&e.mount(t),style:{position:"absolute",left:"0",top:"0",width:e.totalWidth+"px",height:e.totalHeight+"px",transform:0!==e.rotationDegrees?`rotate(${e.rotationDegrees}deg)`:void 0,transformOrigin:0!==e.rotationDegrees?`${e.totalWidth/2}px ${e.totalHeight/2}px`:void 0,opacity:h,pointerEvents:e.markedForRemoval?"none":"auto",backgroundColor:g.resolveThemeColor(e.backgroundColor,t),borderColor:g.resolveThemeColor(e.borderColor,t),borderWidth:e.borderWidth+"px",borderStyle:"solid",padding:e.padding+"px",overflow:"visible",display:"block"}}),uo.isInstanceOf(e,"KritzelSelectionGroup")&&!this.core.displaySelectionLineUI(e)&&n("div",{ref:t=>t&&e.mount(t),style:{position:"absolute",left:"0",top:"0",width:e.totalWidth+"px",height:e.totalHeight+"px",transform:0!==e.rotationDegrees?`rotate(${e.rotationDegrees}deg)`:void 0,transformOrigin:0!==e.rotationDegrees?`${e.totalWidth/2}px ${e.totalHeight/2}px`:void 0,opacity:e.markedForRemoval?"0.5":e.opacity.toString(),pointerEvents:c(e)}}),uo.isInstanceOf(e,"KritzelSelectionBox")&&n("div",{ref:t=>t&&e.mount(t),style:{position:"absolute",left:"0",top:"0",width:e.totalWidth+"px",height:e.totalHeight+"px",transform:0!==e.rotationDegrees?`rotate(${e.rotationDegrees}deg)`:void 0,transformOrigin:0!==e.rotationDegrees?`${e.totalWidth/2}px ${e.totalHeight/2}px`:void 0,opacity:e.markedForRemoval?"0.5":e.opacity.toString(),pointerEvents:e.markedForRemoval?"none":"auto",backgroundColor:g.resolveThemeColor(e.backgroundColor,t),borderColor:g.resolveThemeColor(e.borderColor,t),borderWidth:e.borderWidth+"px",borderStyle:"solid"}}),uo.isInstanceOf(e,"KritzelText")&&n("div",{style:{position:"absolute",left:"0",top:"0",width:e.totalWidth+"px",height:e.totalHeight+"px",transform:0!==e.rotationDegrees?`rotate(${e.rotationDegrees}deg)`:void 0,transformOrigin:0!==e.rotationDegrees?`${e.totalWidth/2}px ${e.totalHeight/2}px`:void 0,opacity:h,pointerEvents:e.markedForRemoval?"none":"auto"}},n("div",{id:"text-object",ref:t=>t&&e.mount(t),onPointerDown:t=>e.handlePointerDown(t),onPointerMove:t=>e.handlePointerMove(t),onPointerUp:t=>e.handlePointerUp(t),style:{minWidth:e.initialWidth+"px",minHeight:e.initialHeight+"px",maxWidth:"500px",height:"auto",width:"max-content",transformOrigin:"top left",transform:`scale(${e.scaleFactor})`,backgroundColor:g.resolveThemeColor(e.backgroundColor,t),overflow:"visible"}})),uo.isInstanceOf(e,"KritzelShape")&&(()=>{const i=g.resolveThemeColor(e.fillColor,t),s=g.resolveThemeColor(e.strokeColor,t),o=!!i&&"transparent"!==i&&s===i;return n("div",{ref:t=>t&&e.mount(t),onPointerDown:t=>e.handlePointerDown(t),onPointerMove:t=>e.handlePointerMove(t),onPointerUp:t=>e.handlePointerUp(t),style:{position:"absolute",left:"0",top:"0",width:e.totalWidth+"px",height:e.totalHeight+"px",transform:0!==e.rotationDegrees?`rotate(${e.rotationDegrees}deg)`:void 0,transformOrigin:0!==e.rotationDegrees?`${e.totalWidth/2}px ${e.totalHeight/2}px`:void 0,pointerEvents:e.markedForRemoval?"none":"auto",overflow:"visible"}},n("svg",{xmlns:"http://www.w3.org/2000/svg",style:{position:"absolute",top:"0",left:"0",width:"100%",height:"100%",overflow:"visible",pointerEvents:"none"},viewBox:e.viewBox,preserveAspectRatio:"none"},n("path",{d:e.getSvgPath(),fill:g.applyOpacity(e.fillColor,r,t),stroke:o?"none":g.applyOpacity(e.strokeColor,r,t),"stroke-width":o?0:e.strokeWidth})),n("div",{ref:t=>t&&e.mountTextEditor(t),style:{position:"absolute",top:"0",left:"0",width:"100%",height:"100%",display:"flex",alignItems:"center",justifyContent:"center",textAlign:"center",overflow:"hidden",pointerEvents:e.isEditing?"auto":"none"}}))})(),this.core.store.state.debugInfo.showObjectInfo&&n("div",{style:{pointerEvents:"none",position:"absolute",left:`${e.totalWidth}px`,top:"0",zIndex:(e.zIndex+2).toString()}},n("div",{style:{whiteSpace:"nowrap",fontSize:"10px"}},"Id: ",e.id),n("div",{style:{whiteSpace:"nowrap",fontSize:"10px"}},"userId: ",e.userId),n("div",{style:{whiteSpace:"nowrap",fontSize:"10px"}},"width: ",e.width),n("div",{style:{whiteSpace:"nowrap",fontSize:"10px"}},"height: ",e.height),n("div",{style:{whiteSpace:"nowrap",fontSize:"10px"}},"translateX: ",e.translateX),n("div",{style:{whiteSpace:"nowrap",fontSize:"10px"}},"translateY: ",e.translateY),n("div",{style:{whiteSpace:"nowrap",fontSize:"10px"}},"scale: ",e.scale),n("div",{style:{whiteSpace:"nowrap",fontSize:"10px"}},"rotationDegrees: ",e.rotationDegrees),n("div",{style:{whiteSpace:"nowrap",fontSize:"10px"}},"zIndex: ",e.zIndex),n("div",{style:{whiteSpace:"nowrap",fontSize:"10px"}},"isSelected: ",e.isSelected?"true":"false"),uo.isInstanceOf(e,"KritzelCustomElement")&&n("div",null,n("div",{style:{whiteSpace:"nowrap",fontSize:"10px"}},"isInteractive: ",e.isInteractive?"true":"false")),uo.isInstanceOf(e,"KritzelImage")&&n("div",null,n("div",{style:{whiteSpace:"nowrap",fontSize:"10px"}},"assetId: ",e.assetId),n("div",{style:{whiteSpace:"nowrap",fontSize:"10px"}},"mimeType: ",e.mimeType))),(this.core.displaySelectionGroupUI(e)||this.core.displaySelectionLineUI(e))&&(()=>{const r=uo.isInstanceOf(e,"KritzelSelectionGroup"),o=this.core.store.objects?.localClientId,h=this.core.store.objects?.awareness?.getStates(),a=r&&(null!=e.userId&&null!=this.core.user?.id&&e.userId!==this.core.user.id||null!=e.userId&&null!=this.core.user?.id&&e.userId===this.core.user.id&&null!=e.clientId&&null!=o&&e.clientId!==o&&!0===h?.has(e.clientId));let l;if(a&&h&&(r&&null!=e.clientId&&(l=h.get(e.clientId)?.user?.color),!l))for(const t of h.values())if(t.user?.id===e.userId){l=t.user.color;break}const u=l??(g.resolveThemeColor(e.borderColor,t)||"var(--kritzel-selection-border-color, #007AFF)"),c=l??"var(--kritzel-selection-handle-stroke-color, #007AFF)",f=null!=e.endAnchor,d=this.core.store.state.snapCandidate??this.core.store.state.snapPreviewCandidate,p=null!=e.startAnchor||"start"===d?.endpoint,m=f||"end"===d?.endpoint,w=this.core.displaySelectionLineUI(e)?"10000":(e.zIndex+1).toString(),v=e.scale??1,{canRenderResizeHandles:y,canRenderRotationHandle:b}=this.getSelectionHandleCapabilities(e);return n("svg",{xmlns:"http://www.w3.org/2000/svg",style:{zIndex:w,height:e?.totalHeight.toString(),width:e?.totalWidth.toString(),left:"0",top:"0",position:"absolute",transform:`rotate(${e.rotationDegrees}deg)`,transformOrigin:`${e.totalWidth/2}px ${e.totalHeight/2}px`,overflow:"visible",pointerEvents:"none"}},this.core.displaySelectionGroupUI(e)&&n("g",{class:"selection-group-ui",style:{pointerEvents:"none"}},(()=>{const t=a&&uo.isInstanceOf(e,"KritzelSelectionGroup")&&1===e.objects.length&&uo.isInstanceOf(e.objects[0],"KritzelLine")?e.objects[0]:null;return t?n("g",{class:"selection-line-borders"},n("path",{class:"selection-line-border",d:this.core.anchorManager.computeClippedLinePath(t,!0),style:{stroke:u,strokeWidth:`calc(var(--kritzel-selection-border-width, 2px) * ${e.scale} / ${this.core.store.state?.scale})`,strokeLinecap:"round",fill:"none"}})):n("g",{class:"selection-group-borders"},n("line",{x1:"0",y1:"0",x2:e.totalWidth,y2:"0",style:{stroke:u,strokeWidth:`calc(var(--kritzel-selection-border-width, 2px) * ${e.scale} / ${this.core.store.state?.scale})`,strokeLinecap:"square"}}),n("line",{x1:"0",y1:"0",x2:"0",y2:e.totalHeight,style:{stroke:u,strokeWidth:`calc(var(--kritzel-selection-border-width, 2px) * ${e.scale} / ${this.core.store.state?.scale})`,strokeLinecap:"square"}}),n("line",{x1:"0",y1:e.totalHeight,x2:e.totalWidth,y2:e.totalHeight,style:{stroke:u,strokeWidth:`calc(var(--kritzel-selection-border-width, 2px) * ${e.scale} / ${this.core.store.state?.scale})`,strokeLinecap:"square"}}),n("line",{x1:e.totalWidth,y1:"0",x2:e.totalWidth,y2:e.totalHeight,style:{stroke:u,strokeWidth:`calc(var(--kritzel-selection-border-width, 2px) * ${e.scale} / ${this.core.store.state?.scale})`,strokeLinecap:"square"}}))})(),!this.isSelecting&&!a&&n("g",{class:"selection-group-handles",style:{pointerEvents:"auto"}},y&&n("g",null,n("rect",{class:"resize-handle top-left",x:""+-(i-1)*v/this.core.store.state?.scale,y:""+-(i-1)*v/this.core.store.state?.scale,width:""+2*(i-1)*v/this.core.store.state?.scale,height:""+2*(i-1)*v/this.core.store.state?.scale,style:{fill:"var(--kritzel-selection-handle-color, #ffffff)",stroke:c,strokeWidth:`calc(2px * ${v} / ${this.core.store.state?.scale})`,paintOrder:"fill"}}),n("rect",{class:"resize-handle-overlay top-left",x:""+-s*v/this.core.store.state?.scale,y:""+-s*v/this.core.store.state?.scale,width:""+2*s*v/this.core.store.state?.scale,height:""+2*s*v/this.core.store.state?.scale,style:{fill:"transparent",paintOrder:"fill"}}),n("rect",{class:"resize-handle top-right",x:""+(e.totalWidth-(i-1)*v/this.core.store.state?.scale),y:""+-(i-1)*v/this.core.store.state?.scale,width:""+2*(i-1)*v/this.core.store.state?.scale,height:""+2*(i-1)*v/this.core.store.state?.scale,style:{fill:"var(--kritzel-selection-handle-color, #ffffff)",stroke:c,strokeWidth:`calc(2px * ${v} / ${this.core.store.state?.scale})`,paintOrder:"fill"}}),n("rect",{class:"resize-handle-overlay top-right",x:""+(e.totalWidth-s*v/this.core.store.state?.scale),y:""+-s*v/this.core.store.state?.scale,width:""+2*s*v/this.core.store.state?.scale,height:""+2*s*v/this.core.store.state?.scale,style:{fill:"transparent",paintOrder:"fill"}}),n("rect",{class:"resize-handle bottom-left",x:""+-(i-1)*v/this.core.store.state?.scale,y:""+(e.totalHeight-(i-1)*v/this.core.store.state?.scale),width:""+2*(i-1)*v/this.core.store.state?.scale,height:""+2*(i-1)*v/this.core.store.state?.scale,style:{fill:"var(--kritzel-selection-handle-color, #ffffff)",stroke:c,strokeWidth:`calc(2px * ${v} / ${this.core.store.state?.scale})`,paintOrder:"fill"}}),n("rect",{class:"resize-handle-overlay bottom-left",x:""+-s*v/this.core.store.state?.scale,y:""+(e.totalHeight-s*v/this.core.store.state?.scale),width:""+2*s*v/this.core.store.state?.scale,height:""+2*s*v/this.core.store.state?.scale,style:{fill:"transparent",paintOrder:"fill"}}),n("rect",{class:"resize-handle bottom-right",x:""+(e.totalWidth-(i-1)*v/this.core.store.state?.scale),y:""+(e.totalHeight-(i-1)*v/this.core.store.state?.scale),width:""+2*(i-1)*v/this.core.store.state?.scale,height:""+2*(i-1)*v/this.core.store.state?.scale,style:{fill:"var(--kritzel-selection-handle-color, #ffffff)",stroke:c,strokeWidth:`calc(2px * ${v} / ${this.core.store.state?.scale})`,paintOrder:"fill"}}),n("rect",{class:"resize-handle-overlay bottom-right",x:""+(e.totalWidth-s*v/this.core.store.state?.scale),y:""+(e.totalHeight-s*v/this.core.store.state?.scale),width:""+2*s*v/this.core.store.state?.scale,height:""+2*s*v/this.core.store.state?.scale,style:{fill:"transparent",paintOrder:"fill"}})),b&&n("g",null,n("line",{x1:e.totalWidth/2,y1:"0",x2:e.totalWidth/2,y2:-15*v/this.core.store.state?.scale,style:{stroke:u,strokeWidth:`calc(var(--kritzel-selection-border-width, 2px) * ${v} / ${this.core.store.state?.scale})`}}),n("circle",{class:"rotation-handle",cx:e.totalWidth/2,cy:-15*v/this.core.store.state?.scale,r:""+(i-1)*v/this.core.store.state?.scale,style:{fill:"var(--kritzel-selection-handle-color, #ffffff)",stroke:c,strokeWidth:`calc(2px * ${v} / ${this.core.store.state?.scale})`,paintOrder:"fill"}}),n("circle",{class:"rotation-handle-overlay",cx:e.totalWidth/2,cy:-15*v/this.core.store.state?.scale,r:""+s*v/this.core.store.state?.scale,style:{fill:"transparent",paintOrder:"fill"}})))),this.core.displaySelectionLineUI(e)&&uo.isInstanceOf(e,"KritzelLine")&&n("g",{class:"selection-line-ui",style:{pointerEvents:"none"}},n("g",{class:"selection-line-borders"},n("path",{class:"selection-line-border",d:this.core.anchorManager.computeClippedLinePath(e,!0),style:{stroke:u,strokeWidth:`calc(var(--kritzel-selection-border-width, 2px) * ${e.scale} / ${this.core.store.state?.scale})`,strokeLinecap:"round",fill:"none"}})),!this.isSelecting&&!a&&n("g",{class:"selection-line-handles",style:{pointerEvents:"auto"}},n("circle",{class:"selection-line-handle start",cx:e.startX-e.x,cy:e.startY-e.y,r:""+(i-1)*e.scale/this.core.store.state?.scale,style:{fill:p?c:"var(--kritzel-selection-handle-color, #000000)",stroke:c,strokeWidth:`calc(2px * ${e.scale} / ${this.core.store.state?.scale})`,paintOrder:"fill"}}),n("circle",{class:"selection-line-handle-overlay start","data-testid":"line-handle-start",cx:e.startX-e.x,cy:e.startY-e.y,r:""+s*e.scale/this.core.store.state?.scale,style:{fill:"transparent",paintOrder:"fill"}}),n("circle",{class:"selection-line-handle center",cx:void 0!==e.controlX?(e.startX+2*e.controlX+e.endX)/4-e.x:(e.startX-e.x+e.endX-e.x)/2,cy:void 0!==e.controlY?(e.startY+2*e.controlY+e.endY)/4-e.y:(e.startY-e.y+e.endY-e.y)/2,r:""+(i-1)*e.scale/this.core.store.state?.scale,style:{fill:"var(--kritzel-selection-handle-color, #000000)",stroke:c,strokeWidth:`calc(2px * ${e.scale} / ${this.core.store.state?.scale})`,paintOrder:"fill"}}),n("circle",{class:"selection-line-handle-overlay center","data-testid":"line-handle-center",cx:void 0!==e.controlX?(e.startX+2*e.controlX+e.endX)/4-e.x:(e.startX-e.x+e.endX-e.x)/2,cy:void 0!==e.controlY?(e.startY+2*e.controlY+e.endY)/4-e.y:(e.startY-e.y+e.endY-e.y)/2,r:""+s*e.scale/this.core.store.state?.scale,style:{fill:"transparent",paintOrder:"fill"}}),n("circle",{class:"selection-line-handle end",cx:e.endX-e.x,cy:e.endY-e.y,r:""+(i-1)*e.scale/this.core.store.state?.scale,style:{fill:m?c:"var(--kritzel-selection-handle-color, #000000)",stroke:c,strokeWidth:`calc(2px * ${e.scale} / ${this.core.store.state?.scale})`,paintOrder:"fill"}}),n("circle",{class:"selection-line-handle-overlay end","data-testid":"line-handle-end",cx:e.endX-e.x,cy:e.endY-e.y,r:""+s*e.scale/this.core.store.state?.scale,style:{fill:"transparent",paintOrder:"fill"}}))))})())})),(()=>{const t=this.core.anchorManager.getSnapIndicatorRenderData()??this.core.anchorManager.getSnapPreviewRenderData();if(!t)return null;const e=null!=this.core.anchorManager.getSnapIndicatorRenderData();return n("svg",{xmlns:"http://www.w3.org/2000/svg",class:"snap-indicator",style:{position:"absolute",left:"0",top:"0",width:"1px",height:"1px",pointerEvents:"none",zIndex:"9999",overflow:"visible"}},n("g",null,t.snapLinePath?n("path",{d:t.snapLinePath,fill:"none",style:{stroke:e?"var(--kritzel-snap-line-stroke, rgba(0, 0, 0, 0.2))":"var(--kritzel-snap-line-stroke, rgba(0, 0, 0, 0.12))",strokeWidth:t.lineStrokeWidth,strokeDasharray:t.dashArray,strokeLinecap:"round"}}):void 0!==t.edgeX&&void 0!==t.edgeY&&n("line",{x1:t.edgeX,y1:t.edgeY,x2:t.centerX,y2:t.centerY,style:{stroke:e?"var(--kritzel-snap-line-stroke, rgba(0, 0, 0, 0.2))":"var(--kritzel-snap-line-stroke, rgba(0, 0, 0, 0.12))",strokeWidth:t.lineStrokeWidth,strokeDasharray:t.dashArray,strokeLinecap:"round"}}),n("circle",{cx:t.centerX,cy:t.centerY,r:t.indicatorRadius,style:{fill:e?"var(--kritzel-snap-indicator-fill, rgba(59, 130, 246, 0.3))":"rgba(59, 130, 246, 0.18)",stroke:e?"var(--kritzel-snap-indicator-stroke, #007bff)":"rgba(59, 130, 246, 0.5)",strokeWidth:t.indicatorStrokeWidth}})))})(),(()=>{const t=this.core.anchorManager.getAnchorLinesRenderData();return t?n("svg",{xmlns:"http://www.w3.org/2000/svg",class:"anchor-lines",style:{position:"absolute",left:"0",top:"0",width:"1px",height:"1px",pointerEvents:"none",zIndex:"9998",overflow:"visible"}},t.startAnchorViz&&n("g",{class:"anchor-line-start"},t.startAnchorViz.pathD?n("path",{d:t.startAnchorViz.pathD,style:{stroke:"var(--kritzel-snap-line-stroke, rgba(0, 0, 0, 0.3))",strokeWidth:`${t.lineStrokeWidth}`,strokeDasharray:t.dashArray,strokeLinecap:"round",fill:"none"}}):n("line",{x1:t.startAnchorViz.edgeX,y1:t.startAnchorViz.edgeY,x2:t.startAnchorViz.centerX,y2:t.startAnchorViz.centerY,style:{stroke:"var(--kritzel-snap-line-stroke, rgba(0, 0, 0, 0.3))",strokeWidth:`${t.lineStrokeWidth}`,strokeDasharray:t.dashArray,strokeLinecap:"round"}}),n("circle",{cx:t.startAnchorViz.centerX,cy:t.startAnchorViz.centerY,r:t.indicatorRadius,style:{fill:"var(--kritzel-snap-indicator-fill, rgba(59, 130, 246, 0.3))",stroke:"var(--kritzel-snap-indicator-stroke, #007bff)",strokeWidth:t.indicatorStrokeWidth}})),t.endAnchorViz&&n("g",{class:"anchor-line-end"},t.endAnchorViz.pathD?n("path",{d:t.endAnchorViz.pathD,style:{stroke:"var(--kritzel-snap-line-stroke, rgba(0, 0, 0, 0.2))",strokeWidth:`${t.lineStrokeWidth}`,strokeDasharray:t.dashArray,strokeLinecap:"round",fill:"none"}}):n("line",{x1:t.endAnchorViz.edgeX,y1:t.endAnchorViz.edgeY,x2:t.endAnchorViz.centerX,y2:t.endAnchorViz.centerY,style:{stroke:"var(--kritzel-snap-line-stroke, rgba(0, 0, 0, 0.2))",strokeWidth:`${t.lineStrokeWidth}`,strokeDasharray:t.dashArray,strokeLinecap:"round"}}),n("circle",{cx:t.endAnchorViz.centerX,cy:t.endAnchorViz.centerY,r:t.indicatorRadius,style:{fill:"var(--kritzel-snap-indicator-fill, rgba(59, 130, 246, 0.3))",stroke:"var(--kritzel-snap-indicator-stroke, #007bff)",strokeWidth:t.indicatorStrokeWidth}}))):null})()),this.core.store.state.isContextMenuVisible&&n("kritzel-context-menu",{class:"context-menu",ref:t=>this.contextMenuElement=t??null,items:this.core.store.state.contextMenuItems,objects:this.core.store.selectionGroup?.objects||[],style:{position:"absolute",left:`${this.core.store.state.contextMenuX}px`,top:`${this.core.store.state.contextMenuY}px`,zIndex:"10002"},onActionSelected:t=>{t.detail.action&&t.detail.action({x:this.core.store.state.contextMenuWorldX,y:this.core.store.state.contextMenuWorldY},this.core.store.selectionGroup?.objects||[]),this.hideContextMenu()},onClose:()=>this.hideContextMenu()}),this.core.store.objects?.hasAwareness&&n("kritzel-awareness-cursors",{core:this.core}),"eraser"===this.core.store.state?.activeTool?.toolType&&!this.core.store.state.isScaling&&n("kritzel-cursor-trail",{core:this.core}),!this.core.licenseManager.isLicensed&&n("kritzel-watermark",{core:this.core,label:this.core.localizationManager.translate("watermark.poweredBy")}))}static get watchers(){return{workspace:[{onWorkspaceChange:0}],activeWorkspaceId:[{onActiveWorkspaceIdChange:0}],syncConfig:[{onSyncConfigChange:0}],assetStorageConfig:[{onAssetStorageConfigChange:0}],user:[{onUserChange:0}],globalContextMenuItems:[{onGlobalContextMenuItemsChange:0}],objectContextMenuItems:[{onObjectContextMenuItemsChange:0}],scaleMax:[{validateScaleMax:0}],scaleMin:[{validateScaleMin:0}],cursorTarget:[{onCursorTargetChange:0}],lockDrawingScale:[{onLockDrawingScaleChange:0}],isObjectDistanceFadingActive:[{onIsObjectDistanceFadingActiveChange:0}],theme:[{onThemeChange:0}],licenseKey:[{onLicenseKeyChange:0}],themes:[{onThemesChange:0}],locale:[{onLocaleChange:0}],locales:[{onLocalesChange:0}],fallbackLocale:[{onFallbackLocaleChange:0}],viewportBoundaryLeft:[{onViewportBoundaryLeftChange:0}],viewportBoundaryRight:[{onViewportBoundaryRightChange:0}],viewportBoundaryTop:[{onViewportBoundaryTopChange:0}],viewportBoundaryBottom:[{onViewportBoundaryBottomChange:0}],debugInfo:[{onDebugInfoChange:0}],isLoading:[{onIsLoadingChange:0}]}}static get style(){return":host{display:block;position:relative;height:100%;width:100%;overflow:hidden;isolation:isolate;background-color:var(--kritzel-engine-background-color, #ffffff)}:host,:host *{touch-action:none;user-select:none}.ProseMirror{outline:none}p,h1,h2,h3,h4,h5,h6,blockquote,pre{margin:0;padding:0}.debug-panel{position:absolute;pointer-events:none;top:0;right:0}.origin{position:relative;top:0;left:0;height:0;width:0;pointer-events:none;-webkit-transform-origin:top left;-moz-transform-origin:top left;transform-origin:top left;overflow:visible}.object{overflow:visible}.kritzel-image-object--first-reveal{animation:kritzel-image-first-reveal 180ms ease-out both;will-change:filter}@keyframes kritzel-image-first-reveal{from{filter:opacity(0)}to{filter:opacity(1)}}@media (prefers-reduced-motion: reduce){.kritzel-image-object--first-reveal{animation:none}}.PlaygroundEditorTheme__quote{margin:0;margin-left:20px;margin-bottom:10px;font-size:15px;color:rgb(101, 103, 107);border-left-color:rgb(206, 208, 212);border-left-width:4px;border-left-style:solid;padding-left:16px}"}},[513,"kritzel-engine",{workspace:[16],editorId:[1,"editor-id"],activeWorkspaceId:[1,"active-workspace-id"],syncConfig:[16],assetStorageConfig:[16],user:[16],globalContextMenuItems:[16],objectContextMenuItems:[16],scaleMax:[1026,"scale-max"],scaleMin:[1026,"scale-min"],cursorTarget:[16],lockDrawingScale:[4,"lock-drawing-scale"],isObjectDistanceFadingActive:[4,"is-object-distance-fading-active"],theme:[1],licenseKey:[1,"license-key"],themes:[16],locale:[1],locales:[16],fallbackLocale:[1,"fallback-locale"],viewportBoundaryLeft:[2,"viewport-boundary-left"],viewportBoundaryRight:[2,"viewport-boundary-right"],viewportBoundaryTop:[2,"viewport-boundary-top"],viewportBoundaryBottom:[2,"viewport-boundary-bottom"],debugInfo:[16],isPanningEnabled:[4,"is-panning-enabled"],isZoomingEnabled:[4,"is-zooming-enabled"],isLoading:[4,"is-loading"],forceUpdate:[32],isSyncing:[32],triggerSelectionChange:[64],registerTool:[64],changeActiveTool:[64],changeActiveToolByName:[64],disable:[64],enable:[64],delete:[64],copy:[64],cut:[64],paste:[64],bringForward:[64],sendBackward:[64],bringToFront:[64],sendToBack:[64],alignObjects:[64],group:[64],ungroup:[64],undo:[64],redo:[64],hideContextMenu:[64],openContextMenu:[64],getObjectById:[64],getAllObjects:[64],findObjects:[64],getObjectsTotalCount:[64],addObject:[64],addObjects:[64],updateObject:[64],removeObject:[64],removeObjects:[64],getSelectedObjects:[64],getDisplayableShortcuts:[64],selectObjects:[64],selectAllObjectsInViewport:[64],clearSelection:[64],centerObjectInViewport:[64],panToObject:[64],backToContent:[64],centerAllObjects:[64],centerObjects:[64],setViewport:[64],panTo:[64],zoomTo:[64],zoomIn:[64],zoomOut:[64],getViewport:[64],screenToWorld:[64],worldToScreen:[64],getObjectsInViewport:[64],getScreenshot:[64],exportViewportAsPng:[64],exportViewportAsSvg:[64],getSelectedObjectsAsSvgString:[64],exportSelectedObjectsAsSvg:[64],getSelectedObjectsAsPngDataUrl:[64],exportSelectedObjectsAsPng:[64],exportAsJson:[64],importFromJson:[64],loadObjectsFromJson:[64],downloadAsJson:[64],importFromFile:[64],createWorkspace:[64],updateWorkspace:[64],deleteWorkspace:[64],getWorkspaces:[64],getActiveWorkspace:[64],getIsPublic:[64],loadSharedWorkspace:[64],reinitSync:[64],saveSettings:[64],loadSettings:[64],registerLocales:[64],setLocale:[64],getLocale:[64],getAvailableLocales:[64],getAvailableLocaleOptions:[64],t:[64],getResolvedTerms:[64]},[[1,"wheel","handleWheel"],[0,"pointerdown","handlePointerDown"],[0,"pointermove","handlePointerMove"],[0,"pointerup","handlePointerUp"],[0,"pointercancel","handlePointerCancel"],[1,"pointerleave","handlePointerLeave"],[1,"longpress","handleLongPress"],[0,"contextmenu","handleContextMenu"],[9,"resize","handleResize"],[8,"keydown","handleKeyDown"],[8,"keyup","handleKeyUp"],[8,"copy","handleCopy"],[8,"cut","handleCut"],[8,"paste","handlePaste"],[4,"dblclick","preventDoubleTapZoomOnTouchDevices"]],{workspace:[{onWorkspaceChange:0}],activeWorkspaceId:[{onActiveWorkspaceIdChange:0}],syncConfig:[{onSyncConfigChange:0}],assetStorageConfig:[{onAssetStorageConfigChange:0}],user:[{onUserChange:0}],globalContextMenuItems:[{onGlobalContextMenuItemsChange:0}],objectContextMenuItems:[{onObjectContextMenuItemsChange:0}],scaleMax:[{validateScaleMax:0}],scaleMin:[{validateScaleMin:0}],cursorTarget:[{onCursorTargetChange:0}],lockDrawingScale:[{onLockDrawingScaleChange:0}],isObjectDistanceFadingActive:[{onIsObjectDistanceFadingActiveChange:0}],theme:[{onThemeChange:0}],licenseKey:[{onLicenseKeyChange:0}],themes:[{onThemesChange:0}],locale:[{onLocaleChange:0}],locales:[{onLocalesChange:0}],fallbackLocale:[{onFallbackLocaleChange:0}],viewportBoundaryLeft:[{onViewportBoundaryLeftChange:0}],viewportBoundaryRight:[{onViewportBoundaryRightChange:0}],viewportBoundaryTop:[{onViewportBoundaryTopChange:0}],viewportBoundaryBottom:[{onViewportBoundaryBottomChange:0}],debugInfo:[{onDebugInfoChange:0}],isLoading:[{onIsLoadingChange:0}]}]);function Ua(){"undefined"!=typeof customElements&&["kritzel-engine","kritzel-awareness-cursors","kritzel-context-menu","kritzel-cursor-trail","kritzel-icon","kritzel-loading-overlay","kritzel-sync-indicator","kritzel-watermark"].forEach((t=>{switch(t){case"kritzel-engine":customElements.get(s(t))||customElements.define(s(t),Wa);break;case"kritzel-awareness-cursors":customElements.get(s(t))||d();break;case"kritzel-context-menu":customElements.get(s(t))||C();break;case"kritzel-cursor-trail":customElements.get(s(t))||h();break;case"kritzel-icon":customElements.get(s(t))||P();break;case"kritzel-loading-overlay":customElements.get(s(t))||R();break;case"kritzel-sync-indicator":customElements.get(s(t))||D();break;case"kritzel-watermark":customElements.get(s(t))||S()}}))}export{ho as A,_ as B,Ua as C,Sh as D,Mh as E,xh as F,Wa as G,oo as I,no as K,fo as S,Ih as W,lo as a,co as b,po as c,wo as d,vo as e,Mo as f,xo as g,Ao as h,oh as i,hh as j,ah as k,lh as l,yh as m,ao as n,bh as o,zh as p,Ch as q,mo as r,Th as s,Eh as t,Oh as u,bo as v,ko as w,jh as x,So as y,gh as z}